import string
from dataclasses import dataclass
import typing
from enum import Enum, auto

# Direction = Enum("Direction", "North South East West")
class Direction(Enum):
    North = (auto(),)
    South = (auto(),)
    East = (auto(),)
    West = (auto(),)

    def __str__(self):
        match (self):
            case Direction.North:
                return "North"
            case Direction.South:
                return "South"
            case Direction.East:
                return "East"
            case Direction.West:
                return "West"


RoomId = Enum(
    "RoomId",
    "Unknown River Forest Path Gate Entrance Cupboard Dustyroom Darkroom Outside Courtyard Garden Throneroom",
)


@dataclass(frozen=True)
class Room:
    title: str
    desc: str
    exits: typing.Dict[Direction, RoomId]  # (Direction, name of location)


rooms: typing.Dict[RoomId, Room] = {
    RoomId.River: Room(
        title="River",
        desc="You are by a fast flowing river.",
        exits={Direction.East: RoomId.Forest},
    ),
    RoomId.Forest: Room(
        title="Forest",
        desc="You are in a petrified forest.",
        exits={
            Direction.West: RoomId.River,
            Direction.South: RoomId.Path,
        },
    ),
    RoomId.Path: Room(
        title="Path",
        desc="You are on a muddy path.",
        exits={
            Direction.North: RoomId.Forest,
            Direction.East: RoomId.Gate,
        },
    ),
    RoomId.Gate: Room(
        title="Gate",
        desc="You are by the gate to the hidden city.",
        exits={
            Direction.West: RoomId.Path,
            Direction.East: RoomId.Entrance,
        },
    ),
    RoomId.Entrance: Room(
        title="Entrance Hall",
        desc="You are in the entrance hall.",
        exits={
            Direction.North: RoomId.Dustyroom,
            Direction.South: RoomId.Cupboard,
            Direction.East: RoomId.Courtyard,
            Direction.West: RoomId.Gate,
        },
    ),
    RoomId.Cupboard: Room(
        title="Cupboard",
        desc="You are in the Cupboard.",
        exits={
            Direction.North: RoomId.Entrance,
        },
    ),
    RoomId.Dustyroom: Room(
        title="Dusty Room",
        desc="You are in a dusty room.",
        exits={
            Direction.North: RoomId.Outside,
            Direction.East: RoomId.Darkroom,
            Direction.South: RoomId.Entrance,
        },
    ),
    RoomId.Outside: Room(
        title="Outside",
        desc="You are outside a large building",
        exits={
            Direction.South: RoomId.Dustyroom,
        },
    ),
    RoomId.Darkroom: Room(
        title="Dark Room",
        desc="You are in a dark room.",
        exits={
            Direction.South: RoomId.Courtyard,
            Direction.West: RoomId.Dustyroom,
        },
    ),
    RoomId.Courtyard: Room(
        title="Courtyard",
        desc="You are in the court yard.",
        exits={
            Direction.North: RoomId.Darkroom,
            Direction.East: RoomId.Garden,
            Direction.West: RoomId.Entrance,
        },
    ),
    RoomId.Garden: Room(
        title="Garden",
        desc="You are in the garden.",
        exits={
            Direction.South: RoomId.Throneroom,
            Direction.East: RoomId.Courtyard,
        },
    ),
    RoomId.Throneroom: Room(
        title="Throne Room",
        desc="You are in the throne room.",
        exits={
            Direction.North: RoomId.Garden,
        },
    ),
}

ItemId = Enum("ItemId", "Brick Bag Gun Eyeball Chain Lamp TaxInspector")


@dataclass(frozen=True)
class Item:
    id: ItemId
    name: str
    desc: str
    starting_loc: RoomId


item_list = [
    Item(
        id=ItemId.Brick,
        name="Brick",
        desc="A brick lies on the ground.",
        starting_loc=RoomId.Path,
    ),
    Item(
        id=ItemId.Bag,
        name="Bag",
        desc="A bag of marbles lies here.",
        starting_loc=RoomId.Outside,
    ),
    Item(
        id=ItemId.Gun,
        name="Gun",
        desc="There is a gun on the floor.",
        starting_loc=RoomId.Unknown,  # You need to take a swim at the river to find.
    ),
    Item(
        id=ItemId.Eyeball,
        name="Eyeball",
        desc="A Jewelled Eyeball lies on the floor.",
        starting_loc=RoomId.Unknown,  # You need to empty the bag for this to appear.
    ),
    Item(
        id=ItemId.Chain,
        name="Chain",
        desc="There is a chain hanging.",
        starting_loc=RoomId.Throneroom,
    ),
    Item(
        id=ItemId.Lamp,
        name="Lamp",
        desc="You see a lamp.",
        starting_loc=RoomId.Cupboard,
    ),
    Item(
        id=ItemId.TaxInspector,
        name="Tax Inspector",
        desc="A Tax inspector suddenly appears",
        starting_loc=RoomId.Unknown,  # Random change of appear, watch out!
    ),
]


def location_in_direction(location: RoomId, direction: Direction) -> RoomId | None:
    return rooms[location].exits.get(direction)


def lost_in_darkroom(player: "Player", sim: "Simulation"):
    return player.location == RoomId.Darkroom and not (
        player.has_lamp and sim.lamp_alight
    )


class Player:
    def __init__(self):
        self.location = RoomId.River
        self.items: list[Item] = []

    def __repr__(self):
        return f"{{location: {self.location} }}"

    def move(self, direction: Direction, sim: "Simulation"):
        new_location = location_in_direction(self.location, direction)

        if new_location is None:
            print("You can't go in that direction.")
            return False

        self.location = new_location
        return True

    def find_by_id(self, id: ItemId):
        return find(self.items, lambda v: v.id == id)

    def has_item(self, id: ItemId):
        return self.find_by_id(id) != None

    @property
    def has_gun(self):
        return self.has_item(ItemId.Gun)

    @property
    def has_brick(self):
        return self.has_item(ItemId.Brick)

    @property
    def has_lamp(self):
        return self.has_item(ItemId.Lamp)

    @property
    def has_chain(self):
        return self.has_item(ItemId.Chain)

    @property
    def has_eyeball(self):
        return self.has_item(ItemId.Eyeball)

    @property
    def has_bag(self):
        return self.has_item(ItemId.Bag)


class Simulation:
    def __init__(self):
        self.exit = False
        self.game_over = False
        self.items = [(item.starting_loc, item) for item in item_list]
        self.gun_found = False
        self.lamp_alight = False
        self.bag_emptied = False
        self.tax_inspector_event_done = False

    def find_item(self, id: ItemId):
        return find(
            sim.items,
            lambda v: v[1].id == id,
        )

    def display_location(self, location: RoomId):
        room = rooms[location]
        print(room.title)
        print(room.desc)

        items = [item for (item_loc, item) in self.items if item_loc == location]
        for item in items:
            print(f"{item.desc} ")

        print("\nExits:")
        if lost_in_darkroom(player, self):
            print("    You can't see which directions to travel!")
        else:
            for dir in room.exits.keys():
                print(f"    {dir}")


def only_one(items, zero_message, too_many_message):
    length = len(items)
    if length == 0:
        print(zero_message)
    elif length > 1:
        print(too_many_message)

    return length == 1


def process_input(input: str) -> list[str]:
    words = input.lower().translate(str.maketrans("", "", string.punctuation)).split()
    return words


def find(seq: list, predicate):
    return next((x for x in seq if predicate(x)), None)


def take_command(items: list[str], player: Player, sim: Simulation):
    zero_msg = "You are going to have to tell me what to take"
    too_many_msg = "Just on thing at a time."
    if not only_one(items, zero_msg, too_many_msg):
        return

    item_name = items[0]
    item = find(
        sim.items,
        lambda v: v[0] == player.location and v[1].name.lower() == item_name,
    )

    if item != None:
        sim.items.remove(item)
        player.items.append(item[1])
        print(f"You take the {item_name}.")
    else:
        print(f"Sorry, I don't see {item_name} here")


def drop_command(items: list[str], player: Player, sim: Simulation):
    zero_msg = "You are going to have to tell me what to drop"
    too_many_msg = "Just on thing at a time."
    if not only_one(items, zero_msg, too_many_msg):
        return

    item_name = items[0]
    for item in player.items:
        if item.name.lower() == item_name:
            sim.items.append((player.location, item))
            player.items.remove(item)
            print(f"You drop {item_name}.")
            return

    print(f"Sorry, you don't have {item_name}.")


def inventory_command(player: Player):
    if len(player.items) == 0:
        print("You have nothing in your inventory!")
        return

    print("You are carrying")
    for item in player.items:
        print(f"    {item.name}")


def move_command(direction: Direction, player: Player, sim: Simulation):
    import random

    if lost_in_darkroom(player, sim):
        print("You travel in that direction, well you think!")
        print("The darkness stops you from really knowing.")
        print("It looks like you are destined to be lost")
        print("in here forever.")
        return

    tax_inspector = sim.find_item(ItemId.TaxInspector)
    if player.move(direction, sim):
        if tax_inspector and tax_inspector[0] != RoomId.Unknown:
            if len(player.items) == 0:
                print("The Tax Inspector wanted a down payment.")
                print("As you did have anything he locks you")
                print("away in a deep, dark, dungeon for enternity.")
                print("Lets that be a warning - Pay You Taxes!")
                print("Game over.")
                sim.game_over = True
                return
            else:
                item_to_take = random.choice(player.items)
                player.items.remove(item_to_take)
                print(
                    f"The tax inspector takes the {item_to_take.name} as a down payment"
                )

                sim.items.remove(tax_inspector)

        sim.display_location(player.location)

    if not sim.tax_inspector_event_done:
        if random.randint(1, 3) == 1:
            sim.tax_inspector_event_done = True
            print("Suddenly, a tax inspector appears!")

            assert tax_inspector != None
            sim.items.remove(tax_inspector)
            sim.items.append((player.location, tax_inspector[1]))


def look_command(player: Player, sim: Simulation):
    sim.display_location(player.location)


def shoot_command(items: list[str], player: Player, sim: Simulation):
    zero_msg = "mmm, I wander what I should shoot/kill"
    too_many_msg = "I think I should only shoot/kill one thing at a time"
    if not only_one(items, zero_msg, too_many_msg):
        return

    item_name = items[0]

    if player.has_gun:
        if item_name == "taxman" or item_name == "taxinspector" or item_name == "tax":
            tx = find(
                sim.items,
                lambda v: v[1].id == ItemId.TaxInspector,
            )
            if tx and tx[0] == player.location:
                print("You shoot and kill the tax inspector.")
                print("You feel no guilt, what sort of person are you?.")
                sim.items.remove(tx)
            else:
                print("They are no where to be seen")

        else:
            print(f"Honestly, shooting that doesn't feel right.")
            print(f"Perhaps I could find someone really horrible to shoot?")
    else:
        print("You don't have anything that is good for murdering with")


def swim_command(player: Player, sim: Simulation):
    if player.location == RoomId.River:
        if player.has_brick:
            print("What a shame you died")
            sim.game_over = True
            return

        print("You take a nice swim and feel refreshed.")
        if not sim.gun_found:
            print("You found a gun on the far bank.")
            sim.gun_found = True
            item = sim.find_item(ItemId.Gun)
            if item:
                player.items.append(item[1])
                sim.items.remove(item)

    else:
        print("There is nowhere to swim here")


def chain_in_throneroom(player: Player, sim: Simulation):
    if player.has_chain and player.location == RoomId.Throneroom:
        return True

    item = sim.find_item(ItemId.Chain)
    return item != None and item[0] == RoomId.Throneroom


def pull_command(what_to_pull: list[str], player: Player, sim: Simulation):
    if len(what_to_pull) == 0:
        print("mmm, I wander what I should pull")
        return
    elif len(what_to_pull) > 1:
        print("It might be best if I only pull one thing at a time")
        return

    name = what_to_pull[0]

    if name == "chain":
        if chain_in_throneroom(player, sim):
            if player.has_eyeball:
                print("Welll done you have completed the adventure")
            else:
                print("You get flushed down the  toilet and go round the bend")
            sim.game_over = True
        elif player.has_chain:
            print("You pull the chain and nothing happens.")
        else:
            print("Sorry, you can't do that.")
    else:
        print("Sorry, you can pull that.")


def light_command(items: list[str], player: Player, sim: Simulation):
    zero_msg = "mmm, I wander what I should light"
    too_many_msg = "It might be best if I only light one thing at a time"
    if not only_one(items, zero_msg, too_many_msg):
        return

    item_name = items[0]
    if item_name == "lamp" and player.has_lamp:
        if sim.lamp_alight:
            print("The lamp is already alight.")
        sim.lamp_alight = True
    else:
        print("You can't light that.")


def empty_command(items: list[str], player: Player, sim: Simulation):
    zero_msg = "mmm, I wander what I should empty"
    too_many_msg = "It might be best if I only empty one thing at a time"
    if not only_one(items, zero_msg, too_many_msg):
        return

    what_to_empty = items[0]
    if what_to_empty == "gun" and player.has_gun:
        print("Films never showed you how to empty it,")
        print("but the did show you how to shoot it!")
    elif what_to_empty == "bag" and player.has_bag:
        if sim.bag_emptied:
            print("The bag is empty.")
        else:
            sim.bag_emptied = True
            item = sim.find_item(ItemId.Eyeball)

            assert item != None
            sim.items.remove(item)
            sim.items.append((player.location, item[1]))
            print("The marbles roll all over the floor")
    else:
        print("Sorry, you don't know how to empty that.")


def help_command(player: Player):
    if player.location == RoomId.River and player.has_brick:
        print("The brick weighs a lot and ")
        print("if making you arms ache.")
    else:
        print("Type instructions for a list of commands")


def instructions_command():
    print("Command support")
    print("q, quit, exit           - Quit the game.")
    print("n, north                - Move North, if you can.")
    print("e, east                 - Move East, if you can.")
    print("s, South                - Move South, if you can.")
    print("w, west                 - Move West, if you can.")
    print("t, g, get, take         - Pick up an item.")
    print("d, drop, leave          - Drop an object.")
    print("i, inv, inventory       - List what you are carrying.")
    print("shoot, kill             - Shoot/kill something bad!")
    print("swim                    - Swimming, you might like it?")
    print("pull                    - Err, lets you pull something.")
    print("light                   - Light lightable items.")
    print("h, help                 - Maybe give you a hint.")
    print("instructions            - Display this list.")


def dispatch_commands(words: list[str], player: Player, sim: Simulation):
    if len(words) == 0:
        return
    match words:
        case ["q" | "quit" | "exit"]:
            sim.exit = True
        case ["n" | "north"]:
            move_command(Direction.North, player, sim)
        case ["s" | "south"]:
            move_command(Direction.South, player, sim)
        case ["e" | "east"]:
            move_command(Direction.East, player, sim)
        case ["w" | "west"]:
            move_command(Direction.West, player, sim)
        case ["t" | "g" | "get" | "take", *item_name]:
            take_command(item_name, player, sim)
        case ["d" | "drop" | "leave", *item_name]:
            drop_command(item_name, player, sim)
        case ["i" | "inv" | "inventory"]:
            inventory_command(player)
        case ["l" | "look"]:
            look_command(player, sim)
        case ["shoot" | "kill", *item_name]:
            shoot_command(item_name, player, sim)
        case ["swim", *_]:
            swim_command(player, sim)
        case ["pull", *what_to_pull]:
            pull_command(what_to_pull, player, sim)
        case ["light", *what_to_pull]:
            light_command(what_to_pull, player, sim)
        case ["empty", *what_to_empty]:
            empty_command(what_to_empty, player, sim)
        case ["h" | "help"]:
            help_command(player)
        case ["instructions" | "instruction" | "commands"]:
            instructions_command()
        case _:
            print("Sorry, I don't understand")


def intro_text():
    print("Welcome the Adventure!")
    print("In the face of financial")
    print("collapse you have fled the")
    print("country.")
    print("")
    print("The solution to your problem")
    print("lies in finding the fabled")
    print("jewelled eyeball of the purple")
    print("icon and pass the final")
    print("initiative test.")
    print("")
    print("Avoid the Tax Inspector at all")
    print("costs.")
    print()
    print()
    print()
    input("Press Return to start")


if __name__ == "__main__":
    sim = Simulation()
    player = Player()
    intro_text()
    sim.display_location(player.location)
    while not sim.exit:
        while not sim.game_over and not sim.exit:
            line_input = input("What now? ")
            words = process_input(line_input)
            dispatch_commands(words, player, sim)

        if not sim.exit:
            ans = ""
            while ans not in ["yes", "no", "n", "y"]:
                ans = input("Would you like another game? (yes/no) ").lower()

            if ans == "no" or ans == "n":
                sim.exit = True
            else:
                sim = Simulation()
                player = Player()
                intro_text()
