"""CLI command: penbot benchmark — run PenBot against mock chatbots and score results."""

from __future__ import annotations

import asyncio
import sys

from src.cli.machine_output import is_machine, emit_json


def run_benchmark(args):
    """Entry point for ``penbot benchmark``."""
    machine = is_machine(args)
    mock_names = None

    if hasattr(args, "mock") and args.mock:
        mock_names = [args.mock]

    max_attacks = getattr(args, "attacks", 5) or 5

    if not machine:
        from rich.console import Console
        from rich.panel import Panel

        console = Console()
        console.print(
            Panel.fit(
                "[bold blue]PenBot Benchmark[/bold blue]\n"
                "[dim]Running against mock chatbots...[/dim]",
                border_style="blue",
            )
        )

    try:
        from benchmarks.runner import run_benchmark as _run

        scorecard = asyncio.run(_run(mock_names=mock_names, max_attacks=max_attacks))
    except Exception as e:
        if machine:
            emit_json({"error": str(e)})
        else:
            print(f"\n  Error: {e}")
        sys.exit(1)

    if machine:
        emit_json(scorecard.to_dict())
        return

    # Human-readable output
    from rich.console import Console
    from rich.table import Table
    from rich.panel import Panel

    console = Console()

    # Per-mock results table
    table = Table(title="Benchmark Results", show_lines=True)
    table.add_column("Mock", style="cyan")
    table.add_column("Planted", justify="center")
    table.add_column("Detected", justify="center", style="green")
    table.add_column("Missed", justify="center", style="red")
    table.add_column("FP", justify="center", style="yellow")
    table.add_column("Rate", justify="center")
    table.add_column("Attacks", justify="center")
    table.add_column("Time", justify="right")

    for r in scorecard.per_mock:
        rate_color = (
            "green" if r.detection_rate >= 0.8 else "yellow" if r.detection_rate >= 0.5 else "red"
        )
        table.add_row(
            r.mock_name,
            str(len(r.planted)),
            str(len(r.true_positives)),
            str(len(r.missed)),
            str(r.false_positive_count),
            f"[{rate_color}]{r.detection_rate:.0%}[/{rate_color}]",
            str(r.total_attacks),
            f"{r.elapsed_seconds:.1f}s",
        )

    console.print(table)

    # Summary
    summary_color = (
        "green"
        if scorecard.overall_detection_rate >= 0.8
        else "yellow" if scorecard.overall_detection_rate >= 0.5 else "red"
    )
    console.print(
        Panel(
            f"[bold]Detection Rate:[/bold] [{summary_color}]"
            f"{scorecard.overall_detection_rate:.0%}[/{summary_color}] "
            f"({scorecard.total_detected}/{scorecard.total_planted})\n"
            f"[bold]Precision:[/bold] {scorecard.overall_precision:.0%} "
            f"({scorecard.total_false_positives} false positives)\n"
            f"[bold]Time:[/bold] {scorecard.elapsed_seconds:.1f}s",
            title="Scorecard",
            border_style=summary_color,
        )
    )
