"""King and queen against a lone king: can a language model checkmate?

White is the model, Black is Stockfish. Every move the model gets the FEN, a board
with coordinates, the piece list, the moves so far and the legal-move list, and
answers {"move": "<SAN>"}. Results go to a JSONL file, one line per game.

usage: python mate_test.py <backend:model> <games> <seed> <out.jsonl>
  backend: gemini (needs GEMINI_API_KEY) | ollama (local, port 11434)
           | random | stockfish (baselines)
  example: python mate_test.py ollama:llama3.2 20 2026 results.jsonl
env: STOCKFISH=<path> (default: stockfish on PATH), THINK=1 (Gemma: leave thinking on),
     SLICE=lo:hi (play only those positions)

The blog post used seed 2026 and 20 games, so the same 20 positions.
Requires: pip install chess httpx
"""
import json, os, random, shutil, sys, time
import chess, chess.engine, httpx

GEMINI = "https://generativelanguage.googleapis.com/v1beta/models/{m}:generateContent"
OLLAMA = "http://127.0.0.1:11434/api/chat"
MAX_WHITE_MOVES = 50
SF = os.environ.get("STOCKFISH") or shutil.which("stockfish") or "stockfish"

THINK = os.environ.get("THINK") == "1"


def board_text(board):
    rows = []
    for rank in range(7, -1, -1):
        cells = []
        for file in range(8):
            p = board.piece_at(chess.square(file, rank))
            cells.append(p.symbol() if p else ".")
        rows.append(f"{rank + 1} " + " ".join(cells))
    rows.append("  a b c d e f g h")
    names = {chess.KING: "King", chess.QUEEN: "Queen"}
    pieces = []
    for color, label in ((chess.WHITE, "White"), (chess.BLACK, "Black")):
        own = [f"{names[p.piece_type]} {chess.square_name(sq)}" for sq, p in board.piece_map().items() if p.color == color]
        pieces.append(f"{label}: {', '.join(sorted(own, reverse=True))}")
    return "\n".join(rows) + "\n" + "\n".join(pieces)

class ApiError(Exception):
    """The provider kept failing (5xx/429/timeouts). Not the model's fault, so the game is dropped."""


OFF_SAMPLES = []  # first few off-list answers of the current game, for the write-up


def ask(backend, model, prompt):
    for attempt in range(12):
        try:
            if backend == "gemini":
                body = {"contents": [{"role": "user", "parts": [{"text": prompt}]}],
                        "generationConfig": {"responseMimeType": "application/json"}}
                if model.startswith("gemma") and not THINK:
                    body["generationConfig"]["thinkingConfig"] = {"thinkingLevel": "minimal"}
                r = httpx.post(GEMINI.format(m=model), json=body,
                               headers={"x-goog-api-key": os.environ["GEMINI_API_KEY"]}, timeout=600)
                if r.status_code == 200:
                    parts = r.json()["candidates"][0]["content"]["parts"]
                    return [p for p in parts if not p.get("thought")][-1]["text"]
                if r.status_code in (400, 401, 402, 403, 404):
                    sys.exit(f"gemini {r.status_code}: {r.text[:200]}")
            else:
                r = httpx.post(OLLAMA, json={"model": model, "stream": False, "format": "json", "think": False,
                                             "messages": [{"role": "user", "content": prompt}]}, timeout=300)
                if r.status_code == 200:
                    return r.json()["message"]["content"]
        except (httpx.HTTPError, KeyError, IndexError, ValueError):
            pass
        time.sleep(min(60, 5 + attempt * 5))
    raise ApiError(model)


def positions(n, seed):
    rng, out = random.Random(seed), []
    while len(out) < n:
        b = chess.Board(None)
        a, q, k = rng.sample(range(64), 3)
        b.set_piece_at(a, chess.Piece(chess.KING, chess.WHITE))
        b.set_piece_at(q, chess.Piece(chess.QUEEN, chess.WHITE))
        b.set_piece_at(k, chess.Piece(chess.KING, chess.BLACK))
        b.turn = chess.WHITE
        if not b.is_valid() or b.is_game_over():
            continue
        # skip starts where the queen already stands next to the black king with no defender
        if chess.square_distance(q, k) == 1 and not b.is_attacked_by(chess.WHITE, q):
            continue
        out.append(b)
    return out


def parse_answer(board, raw):
    """Same leniency as the LLMPvP arena: SAN, with or without +/#, or UCI.
    A one-item list around the JSON object is unwrapped."""
    try:
        data = json.loads(raw or "")
        if isinstance(data, list) and len(data) == 1:
            data = data[0]
        text = str(data["move"]).strip()
    except Exception:
        return None
    try:
        return board.parse_san(text)
    except ValueError:
        pass
    try:
        move = chess.Move.from_uci(text)
    except ValueError:
        return None
    return move if move in board.legal_moves else None


def play(backend, model, board, engine):
    sans, off_list, calls = [], 0, 0
    for n in range(1, MAX_WHITE_MOVES + 1):
        legal = sorted(board.san(m) for m in board.legal_moves)
        prompt = (
            "You are playing White in a chess endgame: king and queen against a lone king. "
            "Checkmate the black king as fast as possible. Avoid stalemate and threefold repetition.\n"
            f"FEN: {board.fen()}\nBoard (White uppercase):\n{board_text(board)}\n"
            f"Moves so far: {' '.join(sans) or '(none)'}\n"
            f"Legal moves for White: {', '.join(legal)}\n"
            'Reply with JSON only: {"move": "<one move from the legal list, in SAN>"}'
        )
        move = None
        for _ in range(4):  # same as the arena: the 4th illegal answer in a row loses
            calls += 1
            if backend == "random":
                raw = json.dumps({"move": random.choice(legal)})
            elif backend == "stockfish":
                raw = json.dumps({"move": board.san(engine.play(board, chess.engine.Limit(time=0.1)).move)})
            else:
                try:
                    raw = ask(backend, model, prompt)
                except ApiError:
                    return "api_error", n - 1, off_list, calls, sans
            move = parse_answer(board, raw)
            if move is not None:
                break
            off_list += 1
            if len(OFF_SAMPLES) < 5:
                OFF_SAMPLES.append((raw or "")[:120])
        if move is None:
            return "no_legal_answer", n - 1, off_list, calls, sans
        sans.append(board.san(move)); board.push(move)
        if board.is_checkmate():
            return "mate", n, off_list, calls, sans
        if board.is_stalemate():
            return "stalemate", n, off_list, calls, sans
        reply = engine.play(board, chess.engine.Limit(time=0.05)).move
        sans.append(board.san(reply)); board.push(reply)
        if not any(p.piece_type == chess.QUEEN for p in board.piece_map().values()):
            return "queen_lost", n, off_list, calls, sans
        if board.can_claim_threefold_repetition():
            return "repetition", n, off_list, calls, sans
        if board.can_claim_fifty_moves():
            return "fifty_moves", n, off_list, calls, sans
    return "move_limit", MAX_WHITE_MOVES, off_list, calls, sans


if __name__ == "__main__":
    spec, games, seed, out = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4]
    backend, model = spec.split(":", 1)
    engine = chess.engine.SimpleEngine.popen_uci(SF)
    with open(out, "a") as f:
        lo, hi = (int(x) for x in os.environ.get("SLICE", f"0:{games}").split(":"))
        for i, b in list(enumerate(positions(games, seed)))[lo:hi]:
            start = b.fen()
            dtm = engine.analyse(b, chess.engine.Limit(depth=30))["score"].white().mate()
            t0 = time.time()
            OFF_SAMPLES.clear()
            res, moves, off, calls, sans = play(backend, model, b, engine)
            rec = {"model": model + ("+thinking" if THINK else ""), "backend": backend, "game": i, "start": start,
                   "optimal_mate_in": dtm,
                   "result": res, "white_moves": moves, "off_list": off, "calls": calls,
                   "seconds": round(time.time() - t0, 1), "moves": " ".join(sans), "off_list_samples": OFF_SAMPLES}
            f.write(json.dumps(rec) + "\n"); f.flush()
            print(model, i, res, moves, f"opt={dtm}", f"off={off}", flush=True)
    engine.quit()
