"""CLI 报告命令。

提供报告列表、状态查询、ID 生成、发布等功能。
"""

from typing import Any

import typer

from hezor_common.cli._common import (
    console,
    create_sdk_from_profile,
    err_console,
    get_profile,
    print_json_output,
    print_table,
    read_json_file,
    run_async,
)

app = typer.Typer(name="reports", help="报告管理。", no_args_is_help=True)


@app.command("list")
def list_reports(
    top_n: int = typer.Option(5, "--top-n", "-n", help="返回数量"),
    creation_id: str | None = typer.Option(None, "--creation-id", "-c", help="按创建 ID 过滤"),
    raw: bool = typer.Option(False, "--raw", help="输出原始 JSON"),
) -> None:
    """列出公开报告。"""
    profile = get_profile()

    async def _run() -> Any:
        sdk = create_sdk_from_profile(profile)
        async with sdk:
            return await sdk.get_public_reports(top_n=top_n, creation_id=creation_id)

    result = run_async(_run())

    if raw:
        print_json_output(result, raw=True)
        return

    items = result.items if hasattr(result, "items") else []
    total = result.total if hasattr(result, "total") else len(items)
    console.print(f"共 [bold]{total}[/bold] 条报告\n")

    if not items:
        console.print("[dim]暂无报告[/dim]")
        return

    rows: list[list[str]] = []
    for item in items:
        obj = item.model_dump() if hasattr(item, "model_dump") else item
        rows.append(
            [
                str(obj.get("report_id", "-")),
                str(obj.get("creation_id", "-")),
                str(obj.get("status", "-")),
                str(obj.get("created_at", "-")),
            ]
        )

    print_table(
        "公开报告",
        [
            ("报告 ID", "cyan"),
            ("创建 ID", "green"),
            ("状态", "yellow"),
            ("创建时间", "dim"),
        ],
        rows,
    )


@app.command("status")
def report_status(
    creation_id: str = typer.Argument(..., help="创建 ID"),
    report_id: str = typer.Argument(..., help="报告 ID"),
    raw: bool = typer.Option(False, "--raw", help="输出原始 JSON"),
) -> None:
    """查询报告状态。"""
    profile = get_profile()

    async def _run() -> Any:
        sdk = create_sdk_from_profile(profile)
        async with sdk:
            return await sdk.get_report_status(creation_id=creation_id, report_id=report_id)

    result = run_async(_run())
    print_json_output(result, raw=raw)


@app.command("generate-id")
def generate_id(
    count: int = typer.Option(1, "--count", "-n", help="生成数量"),
) -> None:
    """生成报告 ID。"""
    profile = get_profile()

    async def _run() -> list[str]:
        sdk = create_sdk_from_profile(profile)
        async with sdk:
            return await sdk.generate_report_id(count=count)

    ids = run_async(_run())

    for rid in ids:
        console.print(rid)


@app.command("publish")
def publish(
    json_file: str = typer.Argument(
        ..., help="本地 JSON 文件路径（CreationGenerateResultV2 格式）"
    ),
    task_id: str | None = typer.Option(None, "--task-id", "-t", help="任务 ID（自动生成如不指定）"),
    execution_id: str | None = typer.Option(
        None, "--execution-id", "-e", help="执行 ID（自动生成如不指定）"
    ),
    raw: bool = typer.Option(False, "--raw", help="输出原始 JSON"),
) -> None:
    """发布创建报告。

    从本地 JSON 文件读取 CreationGenerateResultV2 数据并发布。
    """
    from hezor_common.data_model.creations.core import CreationGenerateResultV2

    profile = get_profile()
    data = read_json_file(json_file)

    try:
        creation_result = CreationGenerateResultV2.model_validate(data)
    except Exception as e:
        err_console.print(f"[red]✗[/red] JSON 数据格式无效: {e}")
        raise typer.Exit(code=1) from e

    async def _run() -> Any:
        sdk = create_sdk_from_profile(profile)
        async with sdk:
            return await sdk.publish_creation_report(
                creation_result=creation_result,
                task_id=task_id,
                execution_id=execution_id,
            )

    result = run_async(_run())

    if raw:
        print_json_output(result, raw=True)
    else:
        console.print("[green]✓[/green] 报告发布成功！")
        print_json_output(result)
