"""The Horror Dungeon: browser adaptation of Shubham Behl's original game.py.

The story, characters, inventory, quiz, and five-room progression come from
the uploaded terminal game. This adaptation replaces recursive input loops
with an explicit state machine, fixes inventory aliases and room transitions,
and exposes JSON-friendly state for a web interface. All gameplay decisions
are made here in Python. The original source is preserved alongside this file.
"""

import random


QUIZ = (
    ("I touch the earth and I touch the sky, but if I touch you, you’ll likely die. What am I?", {"lightning"}, 20),
    ("I follow you wherever you go, but never have a presence. What am I?", {"shadow", "a shadow"}, 20),
    ("Which is known primarily as a film actor: Tom Cruise or Tom Brady?", {"tom cruise", "cruise"}, 20),
    ("What is the world’s smallest country by area?", {"vatican city", "vatican", "the vatican"}, 25),
    ("What is the capital of Japan?", {"tokyo"}, 25),
    ("True or false: the Great Wall of China is visible to the unaided eye from the Moon.", {"false", "f"}, 30),
    ("True or false: a triangle’s interior angles add up to 180 degrees on a flat plane.", {"true", "t"}, 30),
)

ITEMS = {
    "aerosol_spray": "Aerosol spray",
    "match_sticks": "Match stick",
    "gun": "Gun",
    "spinach": "Spinach",
    "pills": "Pills",
}


def option(value, label, hint=""):
    return {"value": value, "label": label, "hint": hint}


class DungeonGame:
    """One independent game per browser worker; no shared player globals."""

    def __init__(self, name="Explorer", rng=None):
        self.name = str(name).strip()[:32] or "Explorer"
        self.rng = rng if rng is not None else random.Random()
        self.scene = "intro"
        self.room = 1
        self.health = 100
        self.inventory = set()
        self.quiz_index = 0
        self.score = 0
        self.notice = ""
        self.outcome = None
        self.chambers = []

    def _finish(self, won, message):
        self.scene = "ending"
        self.outcome = "won" if won else "lost"
        self.notice = message

    def _enter(self, scene, room=None):
        self.scene = scene
        if room is not None:
            self.room = room

    def _collect(self, *items):
        fresh = [ITEMS[item] for item in items if item not in self.inventory]
        self.inventory.update(items)
        self.notice = "Added to your backpack: " + ", ".join(fresh) + "." if fresh else "You already have these supplies."

    def _chance(self):
        self._enter("chance", 5)
        self.chambers = [False, False, True, False, False, True]
        self.rng.shuffle(self.chambers)

    def choose(self, raw):
        value = str(raw).strip()[:128]
        choice = value.casefold()
        self.notice = ""
        valid = {o["value"] for o in self.view()["choices"]}
        if self.scene not in {"quiz", "equation"} and choice not in valid:
            self.notice = "Choose one of the available options."
            return self.view()

        if self.scene == "intro":
            if choice == "mystic": self._enter("mystic")
            elif choice == "turtle": self._enter("turtle")
            elif choice == "quiz": self._enter("quiz", 2)
        elif self.scene == "mystic":
            if choice == "accept":
                self.health = 0
                self._finish(False, "The mystic’s gift was poison. Your journey ends here.")
            else:
                self._collect("aerosol_spray")
                self._enter("mystic_more")
        elif self.scene == "mystic_more":
            if choice == "gun": self._collect("gun")
            elif choice == "advice": self.notice = "The mystic whispers: ‘Don’t trust every gift. Be safe out there.’"
            self._enter("intro")
        elif self.scene == "turtle":
            if choice == "take":
                self._collect("match_sticks")
                self._enter("intro")
            else:
                self._enter("turtle_more")
        elif self.scene == "turtle_more":
            if choice == "advice":
                self.notice = "‘To defeat the fire-breather, think about a combination of something that sprays and something that sparks.’"
                self._enter("intro")
            elif choice == "supplies":
                self._collect("spinach", "pills")
                self._enter("intro")
            elif choice == "equation": self._enter("equation")
            else: self._enter("intro")
        elif self.scene == "equation":
            if choice in {"5", "0.05", "$0.05", "5 cents", "five cents", "5 cent", "five cent"}:
                self.notice = "Correct — the ball costs five cents. The turtle opens a shortcut to room four."
                self._enter("zombie", 4)
            else:
                self.notice = "Not quite. If the ball cost ten cents, the difference would be ninety cents. Try again."
        elif self.scene == "quiz":
            _, answers, penalty = QUIZ[self.quiz_index]
            if not choice:
                self.notice = "Enter an answer before continuing."
                return self.view()
            if choice in answers:
                self.score += 1
                self.notice = "Correct. Keep going."
            else:
                self.health = max(0, self.health - penalty)
                self.notice = f"Not quite. You lose {penalty} health."
            self.quiz_index += 1
            if self.quiz_index == len(QUIZ):
                if self.score == len(QUIZ):
                    self.notice = "Seven out of seven. A perfect score opens a shortcut to the final room."
                    self._chance()
                elif self.score >= 4:
                    self.notice = f"You answered {self.score} of seven correctly. The dragon room opens."
                    self._enter("dragon", 3)
                else:
                    self._finish(False, f"You answered {self.score} of seven correctly. Four were needed to unlock the next room.")
        elif self.scene == "dragon":
            if choice == "backpack": self._enter("dragon_tools")
            else:
                self.health = 0
                self._finish(False, "The dragon spots your escape attempt. This path ends here.")
        elif self.scene == "dragon_tools":
            if choice == "combine" and {"match_sticks", "aerosol_spray"} <= self.inventory:
                self.notice = "The match stick and aerosol spray work together. The dragon retreats and the next door opens."
                self._enter("zombie", 4)
            elif choice == "back": self._enter("dragon")
            elif choice == "try":
                self.health = 0
                self._finish(False, "The tools don’t work together. The dragon blocks your path.")
        elif self.scene == "zombie":
            if choice == "backpack": self._enter("zombie_tools")
            else:
                self.health = 0
                self._finish(False, "The zombie catches up before you can reach the door.")
        elif self.scene == "zombie_tools":
            if choice == "gun" and "gun" in self.inventory:
                self.notice = "You use the gun to stop the zombie. Only the final room remains."
                self._chance()
            elif choice == "back": self._enter("zombie")
            elif choice == "try":
                self.health = 0
                self._finish(False, "That tool is not effective against the zombie. Your journey ends here.")
        elif self.scene == "chance":
            if self.chambers.pop():
                self._finish(False, "You draw a cursed seal. Chance closes the final door.")
            elif self.chambers.pop():
                self._finish(True, "The creator draws a cursed seal. The final door opens — you have escaped the Horror Dungeon.")
            else:
                self.notice = "You and the creator both draw safe seals. The remaining seals are waiting."
        return self.view()

    def view(self):
        choices, prompt = [], None
        if self.scene == "intro":
            title = "The room of introductions"
            text = f"Welcome, {self.name}. The heavy door slams shut. A mystic man and an old turtle wait in the first room. Gather supplies, listen carefully, and choose your way through five rooms."
            choices = [option("mystic", "Talk to the mystic man", "A mysterious offer"), option("turtle", "Talk to the old turtle", "A little wisdom, perhaps"), option("quiz", "Enter the quiz room", "Leave room one behind")]
        elif self.scene == "mystic":
            title, text = "A suspicious gift", "‘You are brave to come here,’ says the mystic. ‘I can help you pass through if you surrender.’ He holds out a bottle. Do you take it?"
            choices = [option("accept", "Accept the bottle"), option("decline", "Decline the offer")]
        elif self.scene == "mystic_more":
            title, text = "Choose a little help", "‘You are clever,’ the mystic says, handing you an aerosol spray. ‘What else would you like?’"
            choices = [option("advice", "Ask for advice"), option("gun", "Take the gun"), option("leave", "Return to the room")]
        elif self.scene == "turtle":
            title, text = "The old turtle", "‘A treasure you can see is not always the treasure you need. Keep an open mind.’ The turtle offers a match stick. Do you take it?"
            choices = [option("take", "Take the match stick"), option("ask", "Ask what else he knows")]
        elif self.scene == "turtle_more":
            title, text = "Wisdom or a shortcut?", "The old turtle has a little more to share. What would you like?"
            choices = [option("advice", "Ask for golden advice"), option("supplies", "Take spinach and pills"), option("equation", "Solve a riddle for a shortcut", "Skip to room four"), option("leave", "Return to the room")]
        elif self.scene == "equation":
            title, text = "The turtle’s riddle", "A bat and a ball cost $1.10 together. The bat costs one dollar more than the ball. How much does the ball cost?"
            prompt = {"label": "Your answer", "placeholder": "Answer in dollars or cents"}
        elif self.scene == "quiz":
            title = f"The quiz · {self.quiz_index + 1} of {len(QUIZ)}"
            text = QUIZ[self.quiz_index][0]
            prompt = {"label": "Your answer", "placeholder": "Type your answer"}
        elif self.scene == "dragon":
            title, text = "The dragon room", "Heavy breathing breaks the silence. A dragon’s scales catch the torchlight. Its eyes follow every move. What do you do?"
            choices = [option("run", "Run for the door"), option("hide", "Find a hiding place"), option("backpack", "Open your backpack")]
        elif self.scene == "dragon_tools":
            title, text = "Think in combinations", "The dragon watches as you open your backpack. Which supplies might work together?"
            if {"match_sticks", "aerosol_spray"} <= self.inventory:
                choices.append(option("combine", "Combine match stick + aerosol spray"))
            choices.extend([option("try", "Try another tool"), option("back", "Close the backpack")])
        elif self.scene == "zombie":
            title, text = "The zombie room", "A zombie approaches through the darkness. Beyond it, a narrow path leads to the final room. What do you do?"
            choices = [option("run", "Try to outrun it"), option("hide", "Hide in the shadows"), option("backpack", "Open your backpack")]
        elif self.scene == "zombie_tools":
            title, text = "One tool. One chance.", "Choose carefully. Your backpack may hold a way through."
            if "gun" in self.inventory: choices.append(option("gun", "Use the gun"))
            choices.extend([option("try", "Try another tool"), option("back", "Close the backpack")])
        elif self.scene == "chance":
            title = "The room of chance"
            text = f"The creator offers six seals: four safe and two cursed. You and the creator draw in turn. A cursed seal ends the journey of whoever draws it. {len(self.chambers)} seals remain."
            choices = [option("draw", "Draw your seal", "Let chance decide")]
        else:
            title = "You found the way out." if self.outcome == "won" else "Every choice leaves a story."
            text = "The dungeon is behind you. A little preparation and a little luck made the difference." if self.outcome == "won" else "The dungeon keeps its secrets this time. Start a fresh journey to try another path."
        return {"scene": self.scene, "room": self.room, "title": title, "text": text,
                "choices": choices, "prompt": prompt, "name": self.name,
                "health": self.health, "inventory": [ITEMS[i] for i in ITEMS if i in self.inventory],
                "notice": self.notice, "outcome": self.outcome, "score": self.score}
