"""CLI 应用管理命令。"""

from typing import Any

import typer

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

app = typer.Typer(name="apps", help="应用管理。", no_args_is_help=True)


@app.command("list")
def list_apps(
    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_my_apps()

    apps = run_async(_run())

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

    if not apps:
        console.print("[dim]暂无绑定应用[/dim]")
        return

    rows: list[list[str]] = []
    for a in apps:
        obj = a.model_dump() if hasattr(a, "model_dump") else a
        rows.append(
            [
                str(obj.get("app_name", "-")),
                str(obj.get("display_name", "-")),
                str(obj.get("is_shared", "-")),
            ]
        )

    print_table(
        "绑定应用",
        [
            ("应用名称", "cyan"),
            ("显示名称", "green"),
            ("共享", "yellow"),
        ],
        rows,
    )


@app.command("certs")
def get_certs(
    app_name: str = typer.Argument(..., help="应用名称"),
    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_app_certs(app_name=app_name)

    result = run_async(_run())

    if raw:
        print_json_output(result, raw=True)
    else:
        console.print(f"[green]✓[/green] 应用 [bold]{app_name}[/bold] 的证书信息:\n")
        print_json_output(result)
