"""
Command-line interface for pytablut.

Usage:
    python -m pytablut run client --role white
    python -m pytablut run client --role black --strategy random
"""

import sys

import click
import sharklog

from .client import PlayerClient, PlayerClientConfig
from .rules import Role
from .server import AshtonServer, AshtonServerConfig
from .strategy import Strategy


@click.group()
def cli():
    """Tablut game tools."""
    pass


@cli.group()
def run():
    """Run a component."""
    pass


@run.command()
@click.option(
    '--role', '-r',
    type=click.Choice(['white', 'black'], case_sensitive=False),
    required=True,
    help='Player role (white or black)'
)
@click.option(
    '--timeout', '-t',
    type=float,
    default=60.0,
    help='Timeout for each move in seconds (default: 60.0)'
)
@click.option(
    '--strategy', '-s',
    type=click.Choice(['human', 'random', 'minimax'], case_sensitive=False),
    default='minimax',
    help='Player strategy (default: minimax)'
)
@click.option(
    '--name', '-n',
    default='Player',
    help='Player name (default: Player)'
)
@click.option(
    '--host',
    default='localhost',
    help='Server host (default: localhost)'
)
@click.option(
    '--port', '-p',
    type=int,
    default=0,
    help='Server port (default: auto-select based on role)'
)
@click.option(
    '--log',
    type=click.Choice(['error', 'warning', 'info', 'debug'], case_sensitive=False),
    default='warning',
    help='Logging level (default: warning)'
)
@click.option(
    "--debug",
    is_flag=True,
    help="Set logging level to debug"
)
def client(role, strategy, name, timeout, host, port, log, debug):
    """Run a Tablut client."""
    log_level = sharklog.getLevelName(log.upper())

    # Initialize logging
    sharklog.init(name="pytablut", level=log_level, debug=debug)
    _logger = sharklog.getLogger(name="pytablut.__main__")

    # Parse role
    role_enum = Role.WHITE if role.lower() == 'white' else Role.BLACK

    # Parse strategy
    strategy_enum = Strategy[strategy.upper()]

    # Determine port if not specified
    if not port:
        if role_enum == Role.WHITE:
            port = 5800
        elif role_enum == Role.BLACK:
            port = 5801

    # Create client configuration
    config = PlayerClientConfig(
        role=role_enum,
        name=name,
        server_ip=host,
        server_port=port,
        strategy=strategy_enum,
        timeout=timeout,
    )

    # Create and start client
    client_instance = PlayerClient(config)

    _logger.info(f"Starting {role_enum.name} player with {strategy_enum.name} strategy...")
    _logger.info(f"Connecting to {host}:{config.server_port}")

    try:
        client_instance.start_game()
    except KeyboardInterrupt:
        _logger.warning("Game interrupted by user.")
        sys.exit(0)
    except Exception as e:
        _logger.error(f"Error: {e}")
        if log.lower() == 'debug':
            raise
        sys.exit(1)


@run.command()
@click.option(
    '--host',
    default='localhost',
    help='Server host to bind to (default: localhost)'
)
@click.option(
    '--port-white',
    type=int,
    default=5800,
    help='Port for WHITE player (default: 5800)'
)
@click.option(
    '--port-black',
    type=int,
    default=5801,
    help='Port for BLACK player (default: 5801)'
)
@click.option(
    '--max-turns',
    type=int,
    default=300,
    help='Maximum number of turns before draw (default: 300)'
)
@click.option(
    '--disable-draw-by-repetition',
    is_flag=True,
    help='Disable draw by state repetition (default: enabled)'
)
@click.option(
    '--log',
    type=click.Choice(['error', 'warning', 'info', 'debug'], case_sensitive=False),
    default='info',
    help='Logging level (default: info)'
)
@click.option(
    "--debug",
    is_flag=True,
    help="Set logging level to debug"
)
def server(host, port_white, port_black, max_turns, disable_draw_by_repetition, log, debug):
    """Run a Tablut game server."""
    log_level = sharklog.getLevelName(log.upper())

    # Initialize logging
    sharklog.init(name="pytablut", level=log_level, debug=debug)
    _logger = sharklog.getLogger(name="pytablut.__main__")

    # Create server configuration
    config = AshtonServerConfig(
        host=host,
        port_white=port_white,
        port_black=port_black,
        max_turns=max_turns,
        enable_draw_by_repetition=not disable_draw_by_repetition,
    )

    # Create and start server
    server_instance = AshtonServer(config)

    _logger.info(f"Starting Tablut server on {host}")
    _logger.info(f"WHITE player port: {port_white}")
    _logger.info(f"BLACK player port: {port_black}")
    _logger.info(f"Max turns: {max_turns}")
    _logger.info(f"Draw by repetition: {'enabled' if not disable_draw_by_repetition else 'disabled'}")

    try:
        server_instance.start()
    except KeyboardInterrupt:
        _logger.warning("Server interrupted by user.")
        sys.exit(0)
    except Exception as e:
        _logger.error(f"Error: {e}")
        if debug:
            raise
        sys.exit(1)


if __name__ == "__main__":
    cli()
