"""CLI commands for scenario management."""

from pathlib import Path
from typing import Optional

import typer
from agenteval.scenarios.loader import ScenarioValidationError, load_scenario_file, scenario_to_yaml
from agenteval.storage.repository import ScenarioRepository
from rich.console import Console
from rich.table import Table

app = typer.Typer(help="评测场景管理")
console = Console()


@app.command("list", help="列出所有评测场景")
def list_scenarios() -> None:
    repo = ScenarioRepository()
    scenarios = repo.list_all()
    if not scenarios:
        console.print("暂无评测场景")
        return

    table = Table(show_header=True, header_style="bold")
    table.add_column("ID")
    table.add_column("名称")
    table.add_column("标签")
    table.add_column("用例数")
    table.add_column("创建时间")

    for s in scenarios:
        table.add_row(
            s.id or "",
            s.name,
            ", ".join(s.tags),
            str(len(s.cases)),
            str(s.created_at)[:19] if s.created_at else "",
        )
    console.print(table)


@app.command("validate", help="校验场景文件格式")
def validate_scenario(path: Path) -> None:
    try:
        scenario = load_scenario_file(path)
        console.print(f"校验通过: {scenario.name}，包含 {len(scenario.cases)} 个用例", style="green")
    except ScenarioValidationError as exc:
        console.print(f"校验失败: {exc}", style="red")
        raise typer.Exit(1)


@app.command("import", help="导入场景文件到数据库")
def import_scenario(path: Path) -> None:
    try:
        scenario = load_scenario_file(path)
    except ScenarioValidationError as exc:
        console.print(f"校验失败: {exc}", style="red")
        raise typer.Exit(1)

    created = ScenarioRepository().create(scenario)
    console.print(f"已导入场景: {created.id} - {created.name}")


@app.command("export", help="导出场景到 YAML 文件")
def export_scenario(
    scenario_id: str,
    output: Optional[Path] = typer.Option(None, help="输出文件路径，默认打印到控制台"),
) -> None:
    scenario = ScenarioRepository().get(scenario_id)
    if not scenario:
        console.print(f"场景不存在: {scenario_id}", style="red")
        raise typer.Exit(1)

    yaml_text = scenario_to_yaml(scenario)
    if output:
        output.write_text(yaml_text, encoding="utf-8")
        console.print(f"已导出到: {output}")
    else:
        console.print(yaml_text)


@app.command("get", help="查看场景详情")
def get_scenario(scenario_id: str) -> None:
    scenario = ScenarioRepository().get(scenario_id)
    if not scenario:
        console.print(f"场景不存在: {scenario_id}", style="red")
        raise typer.Exit(1)

    console.print_json(data=scenario.model_dump())


@app.command("remove", help="删除场景")
def remove_scenario(scenario_id: str) -> None:
    if ScenarioRepository().delete(scenario_id):
        console.print(f"已删除场景: {scenario_id}")
    else:
        console.print(f"场景不存在: {scenario_id}", style="red")
        raise typer.Exit(1)
