package thb.jeanluc.adventure.game;

import thb.jeanluc.adventure.io.text.StyledText;
import thb.jeanluc.adventure.model.Ending;

/** Detects the first matching ending and renders the end-of-game screen. */
public final class EndingEngine {

    private EndingEngine() {
    }

    /** First ending whose conditions hold, in list order; null if none. */
    public static Ending triggered(GameContext ctx) {
        for (Ending e : ctx.getWorld().getEndings()) {
            if (Conditions.all(e.when(), ctx)) {
                return e;
            }
        }
        return null;
    }

    /** Builds the ending screen: title banner, text, and a run summary. */
    public static StyledText render(Ending e, GameContext ctx, int turns) {
        int total = ctx.getWorld().getQuests().size();
        int done = ctx.getQuestLog().completed().size();
        String bar = "═".repeat(Math.max(12, e.title().length() + 6));

        StyledText.Builder b = StyledText.builder();
        b.heading(bar + "\n").heading("  " + e.title() + "\n").heading(bar + "\n");
        b.plain(e.text().stripTrailing()).plain("\n\n");
        b.dim("Turns: " + turns + "\n");
        b.dim("Quests completed: " + done + " / " + total + "\n");
        b.heading("Rank: " + rank(e, total, done));
        return b.build();
    }

    private static String rank(Ending e, int total, int done) {
        if (e.victory() && total > 0 && done == total) {
            return "Master of the Manor";
        }
        if (e.victory()) {
            return "Manor Reclaimed";
        }
        return "Escaped — the manor keeps its secrets";
    }
}
