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)",
    )
    play_parser.add_argument(
        "--lichess",
        action="store_true",
        default=False,
        help="Play against a Lichess bot instead of local Stockfish",
    )
    play_parser.add_argument(
        "--bot",
        type=str,
        default=None,
        help="Lichess bot username to challenge (requires --lichess)",
    )
    play_parser.add_argument(
        "--time",
        type=str,
        default="10+0",
        dest="lichess_time",
        help="Time control for Lichess games, e.g. '10+0' (default: 10+0)",
    )

    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)",
    )

    token_parser = subparsers.add_parser("token", help="Set or view Lichess API token")
    token_parser.add_argument(
        "value", nargs="?", default=None, help="Token value (omit to check status)"
    )

    args = parser.parse_args()

    if args.command == "token":
        from chess_cli.settings import load_settings, save_settings

        if args.value:
            settings = load_settings()
            settings.lichess_api_token = args.value
            save_settings(settings)
            print("Lichess API token saved.")
        else:
            settings = load_settings()
            if settings.lichess_api_token:
                masked = settings.lichess_api_token[:8] + "..."
                print(f"Lichess token: {masked}")
            else:
                print("No Lichess token set. Usage: mike-chess token <token>")
        return

    from chess_cli.tui import ChessApp

    if args.command == "play":
        if args.bot and not args.lichess:
            parser.error("--bot requires --lichess")
        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,
            lichess=args.lichess,
            lichess_bot=args.bot,
            lichess_time=args.lichess_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()
