from __future__ import annotations

import argparse
import random

import chess


DIFFICULTY_CHOICES = [
    "newcomer",
    "beginner",
    "novice",
    "amateur",
    "casual",
    "intermediate",
    "proficient",
    "skilled",
    "advanced",
    "strong",
    "expert",
    "candidate",
    "master",
    "veteran",
    "grandmaster",
    "champion",
    "elite",
    "legendary",
    "supreme",
    "maximum",
]


def main() -> None:
    parser = argparse.ArgumentParser(
        prog="mike-chess",
        description="Play chess against Stockfish in your terminal",
    )
    parser.add_argument("--version", action="version", version="mike-chess 0.1.0")
    subparsers = parser.add_subparsers(dest="command")

    play_parser = subparsers.add_parser("play", help="Start a new game")
    play_parser.add_argument(
        "--color",
        choices=["white", "black", "random"],
        default="white",
        help="Play as white, black, or random (default: white)",
    )
    play_parser.add_argument(
        "--difficulty",
        choices=DIFFICULTY_CHOICES,
        default="intermediate",
        help="Stockfish difficulty (default: intermediate)",
    )
    play_parser.add_argument(
        "--threads",
        type=int,
        default=1,
        help="Number of Stockfish threads (default: 1)",
    )
    play_parser.add_argument(
        "--hash",
        type=int,
        default=16,
        dest="hash_mb",
        help="Hash table size in MB (default: 16)",
    )
    play_parser.add_argument(
        "--move-time",
        type=float,
        default=None,
        dest="move_time",
        help="Seconds per engine move (default: auto)",
    )

    analyze_parser = subparsers.add_parser("analyze", help="Analyze a PGN file")
    analyze_parser.add_argument("pgn_file", help="Path to PGN file")
    analyze_parser.add_argument(
        "--depth",
        type=int,
        default=20,
        help="Analysis depth (default: 20)",
    )

    args = parser.parse_args()

    from chess_cli.tui import ChessApp

    if args.command == "play":
        if args.color == "random":
            color = random.choice([chess.WHITE, chess.BLACK])
        elif args.color == "black":
            color = chess.BLACK
        else:
            color = chess.WHITE
        app = ChessApp(
            start_screen="game",
            color=color,
            difficulty=args.difficulty,
            threads=args.threads,
            hash_mb=args.hash_mb,
            move_time=args.move_time,
        )
    elif args.command == "analyze":
        app = ChessApp(start_screen="analyze", pgn_file=args.pgn_file)
    else:
        app = ChessApp(start_screen="menu")

    app.run()


if __name__ == "__main__":
    main()
