#!/usr/bin/env python3
"""Standalone localhost web chess board to play or watch Gemini 4 Neon & Hydrogen via `agy`.

Requirements:
    pip install chess
    `agy` CLI installed and authenticated on PATH

Usage:
    python3 play_llm_chess.py
    # Then open http://127.0.0.1:8787 in your browser
"""

from __future__ import annotations

import argparse
import html
import json
import re
import secrets
import subprocess
import threading
import time
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse

import chess
import chess.pgn
import chess.svg

MODELS: dict[str, dict] = {
    "human": {"label": "Human", "kind": "human"},
    "neon-low": {"label": "Gemini 4 Neon (Low)", "kind": "llm", "model": "gemini-4-neon-low"},
    "neon-medium": {"label": "Gemini 4 Neon (Medium)", "kind": "llm", "model": "gemini-4-neon-medium"},
    "neon-high": {"label": "Gemini 4 Neon (High)", "kind": "llm", "model": "gemini-4-neon-high"},
    "hydrogen-low": {"label": "Gemini 4 Hydrogen (Low)", "kind": "llm", "model": "gemini-4-hydrogen-low"},
    "hydrogen-medium": {"label": "Gemini 4 Hydrogen (Medium)", "kind": "llm", "model": "gemini-4-hydrogen-medium"},
    "hydrogen-high": {"label": "Gemini 4 Hydrogen (High)", "kind": "llm", "model": "gemini-4-hydrogen-high"},
}

NO_TOOLS = (
    "Play chess using only your own knowledge and the position below. "
    "Use no tools, no web search, no shell commands, and do not read or write any files."
)
MAX_RETRIES = 3
MAX_PLIES = 240
LLM_TIMEOUT_S = 600


def ascii_board(board: chess.Board) -> str:
    rows = []
    for rank in range(7, -1, -1):
        cells = [
            (board.piece_at(chess.square(f, rank)).symbol() if board.piece_at(chess.square(f, rank)) else ".")
            for f in range(8)
        ]
        rows.append(f"{rank + 1} | {' '.join(cells)}")
    rows.append("  +----------------")
    rows.append("    a b c d e f g h")
    return "\n".join(rows)


def pgn_movetext(sans: list[str]) -> str:
    if not sans:
        return "(start position)"
    out = []
    for i, san in enumerate(sans):
        out.append(f"{i // 2 + 1}. {san}" if i % 2 == 0 else san)
    return " ".join(out)


def build_prompt(board: chess.Board, sans: list[str], *, include_legal: bool = True, retry_note: str | None = None) -> str:
    side = "White" if board.turn == chess.WHITE else "Black"
    lines = [
        NO_TOOLS,
        "",
        f"You are playing {side}. Choose the strongest legal move in this position.",
        f"Move number: {board.fullmove_number} ({side} to move)",
        f"PGN so far: {pgn_movetext(sans)}",
        f"FEN: {board.fen()}",
        "",
        "Board (UPPERCASE = White, lowercase = Black, . = empty):",
        ascii_board(board),
    ]
    if include_legal:
        legal = " ".join(sorted(board.san(m) for m in board.legal_moves))
        lines.extend(["", f"Legal moves (SAN): {legal}"])
    if retry_note:
        lines.extend(["", f"IMPORTANT: PREVIOUS REPLY WAS INVALID: {retry_note}"])
    lines.extend([
        "",
        "Reply in this exact format (no extra headers or code fences):",
        "MOVE: <your chosen legal move in SAN, e.g. Nf3, exd5, O-O, e8=Q>",
        "THOUGHTS: <2-5 concise sentences: candidate moves you considered, your plan, and key threats>",
    ])
    return "\n".join(lines)


def _try_parse_move(board: chess.Board, token: str) -> chess.Move | None:
    tok = re.sub(r"^\d+\.{1,3}\s*", "", token.strip().strip("`*_\"'()[].,;:")).strip()
    if not tok:
        return None
    norm = tok.replace("0-0-0", "O-O-O").replace("0-0", "O-O")
    for cand in (norm, norm.rstrip("!?")):
        try:
            return board.parse_san(cand)
        except ValueError:
            pass
        try:
            mv = board.parse_uci(cand.lower())
            if mv in board.legal_moves:
                return mv
        except ValueError:
            pass
    return None


def parse_reply(text: str, board: chess.Board) -> tuple[chess.Move, str]:
    raw = text.strip()
    if not raw:
        raise ValueError("empty response")
    move_match = re.search(r"(?im)^\s*(?:\*\*)?MOVE(?:\*\*)?\s*:\s*(.+)$", raw)
    thoughts_match = re.search(r"(?ims)^\s*(?:\*\*)?THOUGHTS(?:\*\*)?\s*:\s*(.+)$", raw)
    thoughts = thoughts_match.group(1).strip() if thoughts_match else ""
    move_line = move_match.group(1).strip() if move_match else raw.splitlines()[0].strip()

    mv = _try_parse_move(board, move_line)
    if mv is None:
        for tok in move_line.split():
            mv = _try_parse_move(board, tok)
            if mv is not None:
                break
    if mv is None:
        raise ValueError(f"could not parse a legal move from '{move_line[:80]}'")
    if not thoughts and move_match:
        thoughts = raw[move_match.end():].strip()
    return mv, thoughts


def run_agy(model_name: str, prompt: str) -> str:
    cmd = ["agy", "-p", prompt, "--model", model_name, "--disable-slash-commands", "--print-timeout", f"{LLM_TIMEOUT_S}s"]
    res = subprocess.run(cmd, capture_output=True, text=True, timeout=LLM_TIMEOUT_S + 30)
    if res.returncode != 0:
        err = (res.stderr or res.stdout or "").strip()
        raise RuntimeError(f"agy exited {res.returncode}: {err[:240]}")
    return res.stdout


def legal_uci_map(board: chess.Board) -> dict[str, list[str]]:
    out: dict[str, list[str]] = {}
    for mv in board.legal_moves:
        out.setdefault(chess.square_name(mv.from_square), []).append(mv.uci())
    return out


def to_pgn(doc: dict) -> str:
    g = chess.pgn.Game()
    g.headers["Event"] = "Local LLM Chess Sparring"
    g.headers["Site"] = "localhost"
    g.headers["White"] = MODELS[doc["white"]]["label"]
    g.headers["Black"] = MODELS[doc["black"]]["label"]
    g.headers["Result"] = doc["result"]
    node = g
    for mv_rec in doc["moves"]:
        node = node.add_variation(chess.Move.from_uci(mv_rec["uci"]))
        if mv_rec["thoughts"]:
            node.comment = mv_rec["thoughts"].replace("}", ")")
    return g.accept(chess.pgn.StringExporter(headers=True, variations=False, comments=True)) + "\n"


class GameManager:
    def __init__(self) -> None:
        self._lock = threading.RLock()
        self._games: dict[str, dict] = {}
        self._thinking: dict[str, dict] = {}

    def _board_of(self, doc: dict) -> chess.Board:
        b = chess.Board()
        for m in doc["moves"]:
            b.push(chess.Move.from_uci(m["uci"]))
        return b

    def _check_outcome(self, doc: dict, board: chess.Board) -> None:
        out = board.outcome(claim_draw=True)
        if out is not None:
            doc["status"] = "finished"
            doc["result"] = out.result()
            doc["reason"] = out.termination.name.lower().replace("_", " ")
        elif len(doc["moves"]) >= MAX_PLIES:
            doc["status"] = "finished"
            doc["result"] = "1/2-1/2"
            doc["reason"] = f"{MAX_PLIES // 2}-move cap"

    def create_game(self, white: str, black: str, include_legal: bool = True) -> dict:
        if white not in MODELS or black not in MODELS:
            raise ValueError("unknown player")
        gid = secrets.token_hex(4)
        doc = {
            "id": gid,
            "white": white,
            "black": black,
            "include_legal": bool(include_legal),
            "status": "playing",
            "result": "*",
            "reason": "",
            "last_error": "",
            "moves": [],
        }
        with self._lock:
            self._games[gid] = doc
            snap = self.get_game(gid)
        self._maybe_trigger_llm(gid)
        return snap

    def get_game(self, gid: str) -> dict:
        with self._lock:
            if gid not in self._games:
                raise KeyError(gid)
            doc = json.loads(json.dumps(self._games[gid]))
            b = self._board_of(doc)
            turn = "white" if b.turn == chess.WHITE else "black"
            th = self._thinking.get(gid)
            doc["fen"] = b.fen()
            doc["turn"] = turn
            doc["to_move"] = doc[turn]
            doc["in_check"] = b.is_check()
            doc["legal_moves"] = legal_uci_map(b) if (doc["status"] == "playing" and MODELS[doc[turn]]["kind"] == "human" and not th) else {}
            doc["thinking"] = (
                {"side": th["side"], "attempt": th["attempt"], "elapsed_s": round(time.monotonic() - th["started"], 1)}
                if th else None
            )
            return doc

    def play_human_move(self, gid: str, uci: str) -> dict:
        with self._lock:
            doc = self._games[gid]
            if doc["status"] != "playing":
                raise ValueError("game already finished")
            if gid in self._thinking:
                raise ValueError("LLM is thinking")
            b = self._board_of(doc)
            side = "white" if b.turn == chess.WHITE else "black"
            if MODELS[doc[side]]["kind"] != "human":
                raise ValueError("not human turn")
            mv = chess.Move.from_uci(uci)
            if mv not in b.legal_moves:
                raise ValueError(f"illegal move: {uci}")
            san = b.san(mv)
            fen_before = b.fen()
            b.push(mv)
            doc["moves"].append({
                "ply": len(doc["moves"]) + 1, "side": side, "player": doc[side], "uci": mv.uci(), "san": san,
                "fen_before": fen_before, "fen_after": b.fen(), "thoughts": "", "prompt": "", "raw": "", "elapsed_s": 0.0, "retries": 0,
            })
            doc["last_error"] = ""
            self._check_outcome(doc, b)
            snap = self.get_game(gid)
        self._maybe_trigger_llm(gid)
        return snap

    def resign(self, gid: str) -> dict:
        with self._lock:
            doc = self._games[gid]
            if doc["status"] == "playing":
                b = self._board_of(doc)
                turn = "white" if b.turn == chess.WHITE else "black"
                doc["status"] = "finished"
                doc["result"] = "0-1" if turn == "white" else "1-0"
                doc["reason"] = f"{turn} resigned"
            return self.get_game(gid)

    def _maybe_trigger_llm(self, gid: str) -> None:
        with self._lock:
            doc = self._games[gid]
            if doc["status"] != "playing" or gid in self._thinking:
                return
            b = self._board_of(doc)
            side = "white" if b.turn == chess.WHITE else "black"
            if MODELS[doc[side]]["kind"] != "llm":
                return
            self._thinking[gid] = {"side": side, "attempt": 1, "started": time.monotonic()}
        threading.Thread(target=self._run_llm_turn, args=(gid,), daemon=True).start()

    def _run_llm_turn(self, gid: str) -> None:
        try:
            with self._lock:
                doc = self._games[gid]
                b = self._board_of(doc)
                side = "white" if b.turn == chess.WHITE else "black"
                model = MODELS[doc[side]]["model"]
                sans = [m["san"] for m in doc["moves"]]
                include_legal = doc["include_legal"]
                expected_ply = len(doc["moves"])

            retry_note = None
            t0 = time.monotonic()
            for attempt in range(1, MAX_RETRIES + 1):
                with self._lock:
                    if gid in self._thinking:
                        self._thinking[gid]["attempt"] = attempt
                prompt = build_prompt(b, sans, include_legal=include_legal, retry_note=retry_note)
                raw = run_agy(model, prompt)
                try:
                    mv, thoughts = parse_reply(raw, b)
                    break
                except ValueError as exc:
                    retry_note = f"{exc}. Reply only with MOVE: <legal SAN> and THOUGHTS: <rationale>."
                    if attempt == MAX_RETRIES:
                        raise RuntimeError(f"failed after {MAX_RETRIES} retries: {exc}") from exc

            elapsed = round(time.monotonic() - t0, 2)
            with self._lock:
                doc = self._games[gid]
                if doc["status"] != "playing" or len(doc["moves"]) != expected_ply:
                    return
                san = b.san(mv)
                fen_before = b.fen()
                b.push(mv)
                doc["moves"].append({
                    "ply": len(doc["moves"]) + 1, "side": side, "player": doc[side], "uci": mv.uci(), "san": san,
                    "fen_before": fen_before, "fen_after": b.fen(), "thoughts": thoughts, "prompt": prompt, "raw": raw,
                    "elapsed_s": elapsed, "retries": attempt - 1,
                })
                doc["last_error"] = ""
                self._check_outcome(doc, b)
        except Exception as exc:
            with self._lock:
                if gid in self._games:
                    self._games[gid]["last_error"] = str(exc)
        finally:
            with self._lock:
                self._thinking.pop(gid, None)
            self._maybe_trigger_llm(gid)


PAGE_HTML = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
<title>Play Chess vs. LLM (Localhost)</title>
<style>
  :root { --bg:#f8f9fa; --card:#fff; --bd:#dee2e6; --ink:#212529; --muted:#5c636a; --acc:#212529; --light:#f0d9b5; --dark:#b58863; }
  * { box-sizing:border-box; }
  body { margin:0 auto; max-width:1120px; padding:16px; background:var(--bg); color:var(--ink); font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif; font-size:15px; }
  h1 { font-size:1.25rem; margin:0 0 12px; }
  .card { background:var(--card); border:1px solid var(--bd); border-radius:8px; padding:10px 12px; }
  .topbar { display:flex; flex-wrap:wrap; gap:10px; align-items:center; margin-bottom:14px; }
  label { font-size:.88rem; display:inline-flex; align-items:center; gap:6px; font-weight:500; }
  select, button { font:inherit; font-size:.86rem; padding:5px 10px; border:1px solid #ced4da; border-radius:5px; background:#fff; color:var(--ink); cursor:pointer; }
  button:hover:not(:disabled) { background:#e9ecef; }
  button:disabled { opacity:.45; cursor:default; }
  button.primary { background:var(--acc); color:#fff; border-color:var(--acc); }
  button.primary:hover { background:#343a40; }
  .grid { display:grid; grid-template-columns:minmax(280px,420px) minmax(280px,1fr); gap:14px; align-items:start; }
  @media (max-width:780px) { .grid { grid-template-columns:1fr; } }
  .status { display:flex; justify-content:space-between; align-items:center; gap:8px; margin-bottom:10px; font-weight:600; font-size:.9rem; }
  .dot { width:9px; height:9px; border-radius:50%; background:#198754; display:inline-block; animation:pulse 1.1s infinite; margin-right:6px; }
  @keyframes pulse { 0%,100%{opacity:1;} 50%{opacity:.25;} }
  #board { width:100%; display:block; border:1px solid #8a6d4b; border-radius:4px; user-select:none; }
  .promo { display:flex; gap:6px; justify-content:center; align-items:center; padding:8px; margin-top:8px; background:#fff; border:1px solid var(--acc); border-radius:6px; }
  .ctrls { display:flex; flex-wrap:wrap; gap:6px; margin-top:8px; }
  .moves { max-height:190px; overflow-y:auto; margin-bottom:12px; font-family:ui-monospace,Menlo,monospace; font-size:.85rem; }
  .mgrid { display:grid; grid-template-columns:36px 1fr 1fr; gap:2px 6px; }
  .mnum { color:var(--muted); text-align:right; padding:3px 2px; }
  .mv { padding:3px 6px; border-radius:4px; cursor:pointer; display:flex; justify-content:space-between; }
  .mv:hover { background:#e9ecef; }
  .mv.active { background:var(--acc); color:#fff; font-weight:600; }
  .meta { font-size:.75rem; opacity:.75; }
  .tabs { display:flex; justify-content:space-between; align-items:center; gap:8px; border-bottom:1px solid var(--bd); padding-bottom:8px; margin-bottom:8px; }
  .tbtns { display:flex; gap:6px; }
  .tbtns button.active { background:var(--acc); color:#fff; border-color:var(--acc); }
  .thoughts-wrap { position:relative; min-height:150px; }
  .thoughts { margin:0; line-height:1.5; white-space:pre-wrap; }
  .blurred { filter:blur(6px); opacity:.4; user-select:none; }
  .overlay { position:absolute; inset:0; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:8px; background:rgba(248,249,250,.5); border-radius:6px; }
  .wire { margin:4px 0 8px; padding:8px; background:#f1f3f5; border-radius:5px; font-family:ui-monospace,Menlo,monospace; font-size:.78rem; max-height:220px; overflow:auto; white-space:pre-wrap; }
  .err { margin-bottom:10px; padding:8px 10px; background:#f8d7da; border:1px solid #f5c2c7; border-radius:6px; color:#842029; font-size:.86rem; }
  .hidden { display:none !important; }
</style>
</head>
<body>
<svg width="0" height="0" style="position:absolute" aria-hidden="true"><defs>{{PIECES}}</defs></svg>
<script id="models-json" type="application/json">{{MODELS_JSON}}</script>

<h1>Localhost LLM Chess Arena (<code>agy</code>)</h1>
<div class="card topbar">
  <label>White <select id="sel-w"></select></label>
  <label>Black <select id="sel-b"></select></label>
  <label><input type="checkbox" id="chk-legal" checked> Legal moves in prompt</label>
  <button id="btn-new" class="primary">New Game</button>
</div>

<div class="grid">
  <div>
    <div id="err-box" class="card err hidden"></div>
    <div class="card">
      <div class="status">
        <span id="st-main">Ready</span>
        <span id="st-sub" style="font-size:.8rem;color:#5c636a;font-weight:400"></span>
      </div>
      <svg id="board" viewBox="0 0 360 360"></svg>
      <div id="promo" class="promo hidden">
        <span>Promote:</span>
        <button data-p="q">Queen</button><button data-p="r">Rook</button>
        <button data-p="b">Bishop</button><button data-p="n">Knight</button>
      </div>
      <div class="ctrls">
        <button id="b-flip">Flip</button>
        <button id="b-start">|&lt;</button><button id="b-prev">&lt;</button>
        <button id="b-next">&gt;</button><button id="b-live">Live</button>
        <button id="b-resign">Resign</button><button id="b-pgn">Copy PGN</button>
      </div>
    </div>
  </div>

  <div>
    <div class="card moves">
      <div id="m-empty" style="color:#5c636a">Make a move on the board or start a game.</div>
      <div id="m-grid" class="mgrid"></div>
    </div>
    <div class="card">
      <div class="tabs">
        <div class="tbtns">
          <button id="tab-th" class="active">Thoughts</button>
          <button id="tab-wr">Prompt &amp; Reply</button>
        </div>
        <button id="b-mute">Muted (click to reveal)</button>
      </div>
      <div id="ply-hdr" style="font-size:.8rem;color:#5c636a;margin-bottom:6px"></div>
      <div id="pane-th" class="thoughts-wrap">
        <p id="th-text" class="thoughts"></p>
        <div id="mute-ov" class="overlay hidden">
          <strong>Thoughts hidden during live play</strong>
          <button id="b-unmute">Reveal Thoughts</button>
        </div>
      </div>
      <div id="pane-wr" class="hidden">
        <div style="font-size:.76rem;font-weight:700;color:#5c636a">PROMPT SENT</div>
        <pre id="wr-prompt" class="wire"></pre>
        <div style="font-size:.76rem;font-weight:700;color:#5c636a">RAW REPLY</div>
        <pre id="wr-raw" class="wire"></pre>
      </div>
    </div>
  </div>
</div>

<script>
(() => {
  const MODELS = JSON.parse(document.getElementById("models-json").textContent);
  const FILES = "abcdefgh";
  const PID = { p:"pawn", n:"knight", b:"bishop", r:"rook", q:"queen", k:"king" };
  const $ = id => document.getElementById(id);

  let game = null, orient = "white", selSq = null, viewPly = null, muted = true, tab = "th", pollId = null, promoTarget = null;

  for (const s of [$("sel-w"), $("sel-b")]) {
    s.innerHTML = Object.entries(MODELS).map(([k, v]) => `<option value="${k}">${v.label}</option>`).join("");
  }
  $("sel-w").value = "human";
  $("sel-b").value = "neon-low";

  async function api(path, opts) {
    const r = await fetch(path, opts);
    const d = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(d.error || "HTTP " + r.status);
    return d;
  }

  function parseFen(fen) {
    const sqs = new Array(64).fill(null);
    fen.split(" ")[0].split("/").forEach((row, r) => {
      let f = 0;
      for (const c of row) { if (/\\d/.test(c)) f += Number(c); else sqs[(7 - r) * 8 + f++] = c; }
    });
    return sqs;
  }
  const sqIdx = name => FILES.indexOf(name[0]) + 8 * (Number(name[1]) - 1);
  const idxSq = i => FILES[i % 8] + (Math.floor(i / 8) + 1);
  const xy = i => {
    const f = i % 8, r = Math.floor(i / 8);
    return orient === "white" ? [f * 45, (7 - r) * 45] : [(7 - f) * 45, r * 45];
  };

  function drawBoard() {
    const ply = game ? (viewPly === null ? game.moves.length : viewPly) : 0;
    const mv = (game && ply > 0) ? game.moves[ply - 1] : null;
    const fen = mv ? mv.fen_after : "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
    const sqs = parseFen(fen);
    const last = mv ? [sqIdx(mv.uci.slice(0,2)), sqIdx(mv.uci.slice(2,4))] : [];
    const targets = (selSq !== null && game && game.legal_moves && ply === game.moves.length)
      ? (game.legal_moves[idxSq(selSq)] || []).map(u => sqIdx(u.slice(2,4))) : [];

    let out = "";
    for (let i = 0; i < 64; i++) {
      const dark = (i % 8 + Math.floor(i / 8)) % 2 === 0;
      const [x, y] = xy(i);
      out += `<rect x="${x}" y="${y}" width="45" height="45" fill="${dark ? "var(--dark)" : "var(--light)"}"/>`;
      if (last.includes(i)) out += `<rect x="${x}" y="${y}" width="45" height="45" fill="rgba(246,246,105,.55)"/>`;
      if (selSq === i) out += `<rect x="${x}" y="${y}" width="45" height="45" fill="rgba(40,120,220,.35)"/>`;
    }
    for (let c = 0; c < 8; c++) {
      const f = orient === "white" ? c : 7 - c, r = orient === "white" ? 7 - c : c;
      out += `<text x="${c*45+41}" y="357" font-size="9" text-anchor="end" fill="#444">${FILES[f]}</text>`;
      out += `<text x="3" y="${c*45+11}" font-size="9" fill="#444">${r+1}</text>`;
    }
    sqs.forEach((ch, i) => {
      if (!ch) return;
      const [x, y] = xy(i);
      const href = "#" + (ch === ch.toUpperCase() ? "white-" : "black-") + PID[ch.toLowerCase()];
      out += `<use href="${href}" x="${x}" y="${y}"/>`;
    });
    for (const t of targets) {
      const [x, y] = xy(t);
      out += sqs[t]
        ? `<circle cx="${x+22.5}" cy="${y+22.5}" r="19" fill="none" stroke="rgba(0,0,0,.35)" stroke-width="4"/>`
        : `<circle cx="${x+22.5}" cy="${y+22.5}" r="7" fill="rgba(0,0,0,.3)"/>`;
    }
    $("board").innerHTML = out;
  }

  function render() {
    drawBoard();
    if (!game) return;
    $("err-box").classList.toggle("hidden", !game.last_error);
    $("err-box").textContent = game.last_error || "";

    if (game.status === "finished") {
      $("st-main").textContent = `Finished: ${game.result} (${game.reason})`;
      muted = false;
    } else if (game.thinking) {
      const lbl = MODELS[game[game.thinking.side]].label;
      $("st-main").innerHTML = `<span class="dot"></span>${lbl} thinking… (${game.thinking.elapsed_s.toFixed(1)}s)`;
    } else {
      $("st-main").textContent = `${game.turn === "white" ? "White" : "Black"} to move: ${MODELS[game.to_move].label}`;
    }
    const curPly = viewPly === null ? game.moves.length : viewPly;
    $("st-sub").textContent = viewPly !== null && viewPly !== game.moves.length ? `Ply ${curPly}/${game.moves.length}` : `${game.moves.length} plies`;

    $("m-empty").classList.toggle("hidden", game.moves.length > 0);
    let mhtml = "";
    for (let i = 0; i < game.moves.length; i += 2) {
      const w = game.moves[i], b = game.moves[i + 1];
      mhtml += `<div class="mnum">${i/2+1}.</div>`;
      mhtml += `<div class="mv${w.ply===curPly?" active":""}" data-p="${w.ply}"><span>${w.san}</span><span class="meta">${w.elapsed_s?w.elapsed_s.toFixed(1)+"s":""}</span></div>`;
      mhtml += b ? `<div class="mv${b.ply===curPly?" active":""}" data-p="${b.ply}"><span>${b.san}</span><span class="meta">${b.elapsed_s?b.elapsed_s.toFixed(1)+"s":""}</span></div>` : "<div></div>";
    }
    $("m-grid").innerHTML = mhtml;
    $("m-grid").querySelectorAll(".mv").forEach(el => el.onclick = () => {
      const p = Number(el.dataset.p);
      viewPly = p === game.moves.length ? null : p;
      selSq = null;
      render();
    });

    const mv = curPly > 0 ? game.moves[curPly - 1] : null;
    $("ply-hdr").textContent = mv ? `${Math.ceil(mv.ply/2)}${mv.side==="white"?".":"..."} ${mv.san} · ${MODELS[mv.player].label}` : "Starting position";
    const isHumanLive = game.status === "playing" && (MODELS[game.white].kind === "human" || MODELS[game.black].kind === "human");
    const hideTh = muted && isHumanLive && mv && mv.thoughts;
    $("th-text").textContent = mv ? (mv.thoughts || "(Human move, no LLM rationale)") : "Start playing or select a move.";
    $("th-text").classList.toggle("blurred", Boolean(hideTh));
    $("mute-ov").classList.toggle("hidden", !hideTh);
    $("b-mute").textContent = muted ? "Muted (click to reveal)" : "Thoughts visible";
    $("wr-prompt").textContent = mv && mv.prompt ? mv.prompt : "(No prompt on this ply)";
    $("wr-raw").textContent = mv && mv.raw ? mv.raw : "(No raw reply on this ply)";
    $("b-resign").disabled = game.status !== "playing";
  }

  function schedulePoll() {
    if (pollId) clearTimeout(pollId);
    if (game && game.status === "playing" && (game.thinking || MODELS[game.to_move].kind === "llm")) {
      pollId = setTimeout(async () => {
        try { game = await api("/api/games/" + game.id); render(); } catch(e) {}
        schedulePoll();
      }, 900);
    }
  }

  async function sendMove(uci) {
    selSq = null; promoTarget = null; $("promo").classList.add("hidden");
    game = await api(`/api/games/${game.id}/move`, {
      method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify({ uci })
    });
    viewPly = null;
    render();
    schedulePoll();
  }

  $("board").addEventListener("pointerdown", ev => {
    if (!game || game.status !== "playing" || game.thinking) return;
    if (viewPly !== null && viewPly !== game.moves.length) return;
    if (MODELS[game.to_move].kind !== "human") return;
    const r = $("board").getBoundingClientRect();
    const fx = Math.floor((ev.clientX - r.left) / r.width * 8), fy = Math.floor((ev.clientY - r.top) / r.height * 8);
    if (fx < 0 || fx > 7 || fy < 0 || fy > 7) return;
    const sq = orient === "white" ? fx + 8 * (7 - fy) : (7 - fx) + 8 * fy;
    const sqName = idxSq(sq);
    if (selSq !== null) {
      const matches = (game.legal_moves[idxSq(selSq)] || []).filter(u => u.slice(2,4) === sqName);
      if (matches.length === 1) { sendMove(matches[0]); return; }
      if (matches.length > 1) { promoTarget = matches; $("promo").classList.remove("hidden"); return; }
    }
    selSq = game.legal_moves[sqName] ? sq : null;
    drawBoard();
  });

  $("promo").querySelectorAll("button").forEach(b => b.onclick = () => {
    if (!promoTarget) return;
    const mv = promoTarget.find(u => u.endsWith(b.dataset.p));
    if (mv) sendMove(mv);
  });

  async function newGame() {
    selSq = null; viewPly = null; muted = true;
    game = await api("/api/games", {
      method:"POST", headers:{"Content-Type":"application/json"},
      body:JSON.stringify({ white:$("sel-w").value, black:$("sel-b").value, include_legal:$("chk-legal").checked })
    });
    orient = (game.black === "human" && game.white !== "human") ? "black" : "white";
    render();
    schedulePoll();
  }

  $("btn-new").onclick = newGame;
  $("b-flip").onclick = () => { orient = orient === "white" ? "black" : "white"; drawBoard(); };
  $("b-start").onclick = () => { if (game) { viewPly = 0; selSq = null; render(); } };
  $("b-prev").onclick = () => { if (game) { const p = viewPly===null?game.moves.length:viewPly; viewPly = Math.max(0, p-1); selSq = null; render(); } };
  $("b-next").onclick = () => { if (game) { const p = viewPly===null?game.moves.length:viewPly; viewPly = p+1>=game.moves.length?null:p+1; selSq = null; render(); } };
  $("b-live").onclick = () => { viewPly = null; selSq = null; render(); };
  $("b-resign").onclick = async () => { if (game) { game = await api(`/api/games/${game.id}/resign`, {method:"POST", body:"{}"}); render(); } };
  $("b-pgn").onclick = async () => {
    if (!game) return;
    const txt = await fetch(`/api/games/${game.id}/pgn`).then(r => r.text());
    await navigator.clipboard.writeText(txt);
    $("b-pgn").textContent = "Copied!";
    setTimeout(() => $("b-pgn").textContent = "Copy PGN", 1400);
  };
  $("b-mute").onclick = () => { muted = !muted; render(); };
  $("b-unmute").onclick = () => { muted = false; render(); };
  $("tab-th").onclick = () => { tab = "th"; $("tab-th").classList.add("active"); $("tab-wr").classList.remove("active"); $("pane-th").classList.remove("hidden"); $("pane-wr").classList.add("hidden"); };
  $("tab-wr").onclick = () => { tab = "wr"; $("tab-wr").classList.add("active"); $("tab-th").classList.remove("active"); $("pane-wr").classList.remove("hidden"); $("pane-th").classList.add("hidden"); };

  newGame();
})();
</script>
</body>
</html>
"""


def make_handler(mgr: GameManager):
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, fmt: str, *args) -> None:
            pass

        def _json(self, data: object, status: int = HTTPStatus.OK) -> None:
            body = json.dumps(data, ensure_ascii=False).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Cache-Control", "no-store")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def _text(self, text: str, ctype: str, status: int = HTTPStatus.OK) -> None:
            body = text.encode()
            self.send_response(status)
            self.send_header("Content-Type", ctype)
            self.send_header("Cache-Control", "no-store")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def do_GET(self) -> None:
            path = urlparse(self.path).path
            if path == "/favicon.ico":
                self.send_response(HTTPStatus.NO_CONTENT)
                self.end_headers()
                return
            if path in ("/", "/index.html"):
                page = (
                    PAGE_HTML
                    .replace("{{PIECES}}", "".join(chess.svg.PIECES.values()))
                    .replace("{{MODELS_JSON}}", json.dumps(MODELS).replace("</", "<\\/"))
                )
                self._text(page, "text/html; charset=utf-8")
                return
            m = re.fullmatch(r"/api/games/([^/]+)", path)
            if m:
                try:
                    self._json(mgr.get_game(m.group(1)))
                except KeyError:
                    self._json({"error": "not found"}, HTTPStatus.NOT_FOUND)
                return
            m = re.fullmatch(r"/api/games/([^/]+)/pgn", path)
            if m:
                try:
                    self._text(to_pgn(mgr.get_game(m.group(1))), "application/x-chess-pgn; charset=utf-8")
                except KeyError:
                    self._json({"error": "not found"}, HTTPStatus.NOT_FOUND)
                return
            self._json({"error": "not found"}, HTTPStatus.NOT_FOUND)

        def do_POST(self) -> None:
            path = urlparse(self.path).path
            length = int(self.headers.get("Content-Length", "0") or "0")
            body = json.loads(self.rfile.read(length).decode() or "{}") if length else {}
            try:
                if path == "/api/games":
                    doc = mgr.create_game(body.get("white", "human"), body.get("black", "neon-low"), body.get("include_legal", True))
                    self._json(doc, HTTPStatus.CREATED)
                    return
                m = re.fullmatch(r"/api/games/([^/]+)/move", path)
                if m:
                    self._json(mgr.play_human_move(m.group(1), body.get("uci", "")))
                    return
                m = re.fullmatch(r"/api/games/([^/]+)/resign", path)
                if m:
                    self._json(mgr.resign(m.group(1)))
                    return
            except (KeyError, ValueError) as exc:
                self._json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
                return
            self._json({"error": "not found"}, HTTPStatus.NOT_FOUND)

    return Handler


def main() -> None:
    parser = argparse.ArgumentParser(description="Localhost chess arena against Gemini 4 Neon & Hydrogen via agy")
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=8787)
    args = parser.parse_args()

    srv = ThreadingHTTPServer((args.host, args.port), make_handler(GameManager()))
    print(f"Listening on http://{args.host}:{args.port} (Ctrl+C to stop)", flush=True)
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        srv.server_close()


if __name__ == "__main__":
    main()
