"""Demo command - Run Year 1/2/3 demo validation."""

from __future__ import annotations

import asyncio
import sys

import click

from ..utils.backend import default_device_for_backend, resolve_backend_and_engine
from ..utils.config import init_default_config
from ..utils.console import get_console


@click.command(hidden=True)
@click.option(
    "--workload",
    type=click.Choice(["year1", "year2", "year3"]),
    default="year1",
    help="Demo workload tier",
)
@click.option("--output", "-o", type=click.Path(), help="Output metrics JSON path")
@click.option("--verbose", "-v", is_flag=True, help="Verbose logging")
@click.option("--config", "config_path", type=click.Path(exists=True), help="Config file path")
def demo(workload: str, output: str | None, verbose: bool, config_path: str | None) -> None:
    """Run Year 1/2/3 demo validation.

    \b
    Examples:
            sagellm demo                            # Run Year1 with CPU engine (default)
        sagellm demo --workload year1 -o out.json
        sagellm demo --verbose
    """
    init_default_config()
    console = get_console()

    console.print(f"\n🎯 [bold blue]Running {workload.upper()} Demo Contract[/bold blue]\n")

    try:
        from sagellm_core import DemoRunner
        from sagellm_core.config import (
            BackendConfig,
            DemoConfig,
            EngineConfig,
            OutputConfig,
            WorkloadConfig,
            WorkloadSegment,
        )

        backend_kind, engine_kind = resolve_backend_and_engine(backend=None)
        model_name = "sshleifer/tiny-gpt2"

        # Create default config for demo
        output_path = output or "metrics.json"
        cfg = DemoConfig(
            backend=BackendConfig(
                kind=backend_kind,
                device=default_device_for_backend(backend_kind),
            ),
            engine=EngineConfig(kind=engine_kind, model=model_name, model_path=model_name),
            workload=WorkloadConfig(
                segments=[WorkloadSegment.SHORT, WorkloadSegment.LONG, WorkloadSegment.STRESS],
                concurrency=1,
            ),
            output=OutputConfig(
                metrics_path=output_path,
                report_path="report.md",
            ),
        )

        # Create and run demo
        runner = DemoRunner(config=cfg, verbose=verbose)

        console.print("📋 [cyan]Workload segments:[/cyan]")
        for seg in cfg.workload.segments:
            console.print(f"   • {seg.value}")
        console.print()

        # Run the demo
        metrics = asyncio.run(runner.run())

        # Display results
        console.print("\n[bold green]✅ Demo completed![/bold green]\n")
        console.print("[blue]📊 Results:[/blue]")
        console.print(f"   TTFT:       {metrics.ttft_ms:.2f} ms")
        console.print(
            f"   TBT:        {metrics.tbt_ms:.2f} ms" if metrics.tbt_ms else "   TBT:        N/A"
        )
        console.print(
            f"   TPOT:       {metrics.tpot_ms:.2f} ms" if metrics.tpot_ms else "   TPOT:       N/A"
        )
        console.print(f"   Throughput: {metrics.throughput_tps:.2f} tokens/s")
        console.print(f"   Peak Mem:   {metrics.peak_mem_mb:.0f} MB")
        console.print(f"   Error Rate: {metrics.error_rate:.2%}")

        if output:
            console.print(f"\n📄 Metrics saved to: [cyan]{output}[/cyan]")

    except ImportError as e:
        console.print(f"[red]❌ Import error: {e}[/red]")
        console.print("\n[yellow]💡 Install: pip install isagellm[/yellow]")
        sys.exit(1)
    except Exception as e:
        console.print(f"[red]❌ Error: {e}[/red]")
        if verbose:
            import traceback

            console.print(traceback.format_exc())
        sys.exit(1)
