"""Verify CLI command - Primary command."""

import json
import sys
from pathlib import Path

import click


@click.command()
@click.argument("policy", type=click.Path(exists=True, path_type=Path))
@click.option(
    "-s", "--scenario",
    required=True,
    help="Scenario ID to verify against",
)
@click.option(
    "-n", "--num-episodes",
    default=5,
    help="Number of episodes to run (default: 5)",
)
@click.option(
    "--wait/--no-wait",
    default=True,
    help="Wait for result (default: True)",
)
@click.option(
    "-o", "--output",
    type=click.Path(path_type=Path),
    help="Output file for JSON report",
)
@click.option(
    "--timeout",
    default=300,
    help="Timeout in seconds (default: 300)",
)
@click.pass_context
def verify(
    ctx: click.Context,
    policy: Path,
    scenario: str,
    num_episodes: int,
    wait: bool,
    output: Path | None,
    timeout: int,
) -> None:
    """Verify a policy for safety.

    This is the primary BotManifold command. It evaluates your policy
    against a scenario and returns a safety verdict.

    \b
    Examples:
        botmanifold verify my_policy.zip --scenario messy_room
        botmanifold verify policy.zip -s messy_room --output report.json
    """
    from botmanifold import BotManifoldClient, BotManifoldError

    client = BotManifoldClient()

    click.echo(f"Verifying {policy.name} against {scenario}...")

    try:
        report = client.verify.run(
            policy=policy,
            scenario=scenario,
            num_episodes=num_episodes,
            timeout=timeout,
            wait=wait,
        )
    except TimeoutError:
        click.echo("Error: Verification timed out", err=True)
        sys.exit(1)
    except BotManifoldError as e:
        click.echo(f"Error: {e}", err=True)
        sys.exit(1)

    # Display result
    if report.is_complete:
        verdict_color = "green" if report.is_safe else "red"
        click.echo()
        click.secho(f"Verdict: {report.verdict.value.upper()}", fg=verdict_color, bold=True)
        click.echo(f"Score: {report.score:.2f}")
        if report.video_url:
            click.echo(f"Video: {report.video_url}")
        if report.report_url:
            click.echo(f"Report: {report.report_url}")
    else:
        click.echo(f"Job ID: {report.job_id}")
        click.echo("Status: PENDING (use --wait to wait for result)")

    # Write JSON output
    if output:
        result = {
            "job_id": report.job_id,
            "verdict": report.verdict.value,
            "score": report.score,
            "scenario": report.scenario,
            "video_url": report.video_url,
            "report_url": report.report_url,
        }
        output.write_text(json.dumps(result, indent=2))
        click.echo(f"Report written to {output}")

    # Exit code based on verdict
    if report.is_complete and not report.is_safe:
        sys.exit(1)
