"""Arena CLI commands."""

import sys
from pathlib import Path

import click


@click.group()
def arena() -> None:
    """Arena competition commands.

    Submit policies, check status, and view leaderboards.
    """
    pass


@arena.command()
@click.argument("policy", type=click.Path(exists=True, path_type=Path))
@click.option(
    "-s", "--scenario",
    required=True,
    help="Scenario ID to submit to",
)
@click.option(
    "-d", "--description",
    help="Optional description for this submission",
)
@click.option(
    "--wait/--no-wait",
    default=False,
    help="Wait for result (default: False)",
)
@click.pass_context
def submit(
    ctx: click.Context,
    policy: Path,
    scenario: str,
    description: str | None,
    wait: bool,
) -> None:
    """Submit a policy to the arena.

    \b
    Example:
        botmanifold arena submit my_policy.zip --scenario messy_room
    """
    from botmanifold import BotManifoldClient, BotManifoldError

    client = BotManifoldClient()

    click.echo(f"Submitting {policy.name} to {scenario}...")

    try:
        submission = client.arena.submit(policy, scenario, description)
        click.echo(f"Submission ID: {submission.id}")
        click.echo(f"Status: {submission.status.value}")

        if wait:
            click.echo("Waiting for result...")
            submission = client.arena.wait(submission.id)
            click.echo(f"Final status: {submission.status.value}")
            if submission.verdict:
                click.echo(f"Verdict: {submission.verdict.value}")
    except BotManifoldError as e:
        click.echo(f"Error: {e}", err=True)
        sys.exit(1)


@arena.command()
@click.argument("submission_id")
def status(submission_id: str) -> None:
    """Check status of a submission.

    \b
    Example:
        botmanifold arena status abc123
    """
    from botmanifold import BotManifoldClient, BotManifoldError

    client = BotManifoldClient()

    try:
        submission = client.arena.status(submission_id)
        click.echo(f"Submission: {submission.id}")
        click.echo(f"Scenario: {submission.scenario_id}")
        click.echo(f"Status: {submission.status.value}")
        if submission.verdict:
            click.echo(f"Verdict: {submission.verdict.value}")
        if submission.video_url:
            click.echo(f"Video: {submission.video_url}")
    except BotManifoldError as e:
        click.echo(f"Error: {e}", err=True)
        sys.exit(1)


@arena.command()
@click.option(
    "-s", "--scenario",
    help="Filter by scenario",
)
@click.option(
    "-n", "--limit",
    default=10,
    help="Number of entries to show (default: 10)",
)
def leaderboard(scenario: str | None, limit: int) -> None:
    """View the arena leaderboard.

    \b
    Example:
        botmanifold arena leaderboard --scenario messy_room
    """
    from botmanifold import BotManifoldClient, BotManifoldError

    client = BotManifoldClient()

    try:
        entries = client.arena.leaderboard(scenario=scenario, limit=limit)

        if not entries:
            click.echo("No entries found.")
            return

        click.echo(f"{'Rank':<6} {'User':<20} {'Score':<10} {'Verdict':<10}")
        click.echo("-" * 50)
        for entry in entries:
            click.echo(
                f"{entry.rank:<6} {entry.user_id[:18]:<20} "
                f"{entry.score:<10.2f} {entry.verdict.value:<10}"
            )
    except BotManifoldError as e:
        click.echo(f"Error: {e}", err=True)
        sys.exit(1)
