#!/usr/bin/env python3
"""
Run your agent against the built-in random agent locally.

Usage:
    python scripts/play_vs_random.py path/to/my_agent.py [--games 10] [--seed 42] [--verbose]

This does NOT require the web server.  Results are printed to the terminal.
"""

import argparse
import importlib.util
import os
import sys
from pathlib import Path

# Make sure the project root is importable
ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(ROOT))

from engine.runner import run_match, run_series
from engine.quarto import board_str, piece_name


def load_module(path: str):
    path = Path(path).resolve()
    if not path.exists():
        print(f"Error: file not found: {path}", file=sys.stderr)
        sys.exit(1)
    spec = importlib.util.spec_from_file_location("user_agent", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def main():
    parser = argparse.ArgumentParser(description="Play your agent vs random.")
    parser.add_argument("agent", help="Path to your agent .py file")
    parser.add_argument("--games", type=int, default=10, help="Number of games (default: 10)")
    parser.add_argument("--seed", type=int, default=None, help="Random seed")
    parser.add_argument("--verbose", "-v", action="store_true", help="Show each game result")
    args = parser.parse_args()

    agent_module = load_module(args.agent)

    import agents.random_agent as random_agent

    print(f"\n{'─'*50}")
    print(f"  Your agent  vs  Random agent")
    print(f"  {args.games} games")
    print(f"{'─'*50}\n")

    import random as _random
    rng = _random.Random(args.seed)
    wins = losses = draws = forfeits = 0

    for i in range(args.games):
        seed = rng.randint(0, 2**31)
        if i % 2 == 0:
            result = run_match(agent_module, random_agent, seed=seed)
            agent_side = 'a'
        else:
            result = run_match(random_agent, agent_module, seed=seed)
            agent_side = 'b'

        if 'forfeit' in result.winner:
            forfeits += 1
            outcome = "FORFEIT"
            if result.error:
                outcome += f" ({result.error[:60]})"
        elif result.winner == 'draw':
            draws += 1
            outcome = "Draw"
        elif result.winner == agent_side:
            wins += 1
            outcome = "WIN"
        else:
            losses += 1
            outcome = "loss"

        if args.verbose:
            print(f"  Game {i+1:2d}/{args.games}: {outcome:10s}  ({result.turns} turns)")

    total = wins + losses + draws
    win_pct = wins / total * 100 if total else 0

    print(f"\n{'─'*50}")
    print(f"  Results: {wins}W  {losses}L  {draws}D  {forfeits} forfeit(s)")
    print(f"  Win rate: {win_pct:.1f}%")
    if wins > losses:
        print(f"  ✓ Your agent beats random!")
    elif wins == losses:
        print(f"  ≈ Even with random.")
    else:
        print(f"  ✗ Random wins more often. Keep improving!")
    print(f"{'─'*50}\n")


if __name__ == "__main__":
    main()
