package thb.jeanluc.adventure.game;

import lombok.RequiredArgsConstructor;
import thb.jeanluc.adventure.command.Command;
import thb.jeanluc.adventure.command.CommandParser;
import thb.jeanluc.adventure.command.CommandRegistry;
import thb.jeanluc.adventure.command.ParsedCommand;
import thb.jeanluc.adventure.io.text.Hud;
import thb.jeanluc.adventure.io.text.MapView;
import thb.jeanluc.adventure.map.MapLayout;
import thb.jeanluc.adventure.model.Ending;

import java.util.Optional;

/**
 * The main game loop. Reads a line, parses it, dispatches the matching
 * command, and writes the result — until {@link #stop()} flips the
 * {@link #running} flag (typically by the quit command or EOF on input).
 */
@RequiredArgsConstructor
public class Game {

    /** Game context shared with every command. */
    private final GameContext ctx;

    /** Command lookup table. */
    private final CommandRegistry registry;

    /** Tokenising parser for player input. */
    private final CommandParser parser;

    /** Loop flag. Flipped to false by {@link #stop()}. */
    private boolean running = true;

    /** Optional onboarding guide; null in normal/loaded play. */
    private TutorialGuide tutorialGuide;

    /** Wires the interactive tutorial (New Game only). */
    public void setTutorialGuide(TutorialGuide tutorialGuide) {
        this.tutorialGuide = tutorialGuide;
    }

    /**
     * Runs the loop until {@link #stop()} is called or input is exhausted.
     */
    public void run() {
        publishHud();
        maybeEnd();
        if (tutorialGuide != null) {
            tutorialGuide.begin(ctx);
        }
        while (running) {
            String input = ctx.getIo().readLine();
            if (input == null) {
                break;
            }
            ParsedCommand parsed = parser.parse(input);
            if (parsed.verb().isEmpty()) {
                continue;
            }
            if (tutorialGuide != null && tutorialGuide.isActive()
                    && parsed.verb().equals("skip")) {
                tutorialGuide.skip(ctx);
                publishHud();
                continue;
            }
            Optional<Command> cmd = registry.find(parsed.verb());
            if (cmd.isEmpty()) {
                ctx.getIo().write("I don't understand '" + parsed.verb() + "'. Type 'help'.");
            } else {
                cmd.get().execute(ctx, parsed.args());
                ctx.getSession().incrementTurn();
                if (ctx.getSession().getTurn() % 10 == 0) {
                    ctx.save();
                }
                if (tutorialGuide != null && tutorialGuide.isActive()) {
                    tutorialGuide.onCommand(ctx, parsed);
                }
            }
            publishHud();
            maybeEnd();
        }
    }

    /** Ends the game if any ending's conditions are met, printing its screen. */
    private void maybeEnd() {
        // Don't end the game (win or lose) while the player is still in the tutorial —
        // a pending ending fires once the walkthrough finishes or is skipped.
        if (tutorialGuide != null && tutorialGuide.isActive()) {
            return;
        }
        Ending e = EndingEngine.triggered(ctx);
        if (e != null) {
            ctx.getIo().print(EndingEngine.render(e, ctx, ctx.getSession().getTurn()));
            stop();
        }
    }

    private void publishHud() {
        QuestEngine.tick(ctx);
        ctx.getIo().setHud(new Hud(
                ctx.getPlayer().getCurrentRoom().getName(),
                ctx.getPlayer().getGold(),
                ctx.getSession().getTurn(),
                Light.carryingLight(ctx)));
        MapView map = MapLayout.compute(
                ctx.getWorld(),
                ctx.getPlayer().getVisitedRoomIds(),
                ctx.getPlayer().getCurrentRoom());
        ctx.getIo().setMap(map);
        ctx.getIo().setQuests(QuestEngine.viewOf(ctx));
        ctx.getIo().setMusic(ctx.getPlayer().getCurrentRoom().getMusic());
    }

    /**
     * Signals the loop to terminate after the current iteration.
     */
    public void stop() {
        running = false;
    }
}
