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

from typing import Any

import typer

from hezor_common.cli._common import (
    console,
    create_sdk_from_profile,
    err_console,
    get_profile,
    run_async,
)
from hezor_common.cli.credential import CredentialManager

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


@app.command("list")
def list_apps() -> None:
    """列出当前用户绑定的应用（需要 JWT 认证，CLI 暂不支持）。"""
    err_console.print("[red]✗[/red] apps list 需要 JWT 认证（Web 登录），CLI 暂不支持。")
    err_console.print("  请向平台管理员获取您有权限的应用名称 (app_name)，然后运行：")
    err_console.print("  [bold]hezor2 apps use <app_name>[/bold]")
    raise typer.Exit(code=1)


@app.command("use")
def use_app(
    app_name: str = typer.Argument(..., help="应用名称"),
) -> None:
    """切换应用，获取证书并保存到凭据中。"""
    cm = CredentialManager()
    profile_name = cm.get_active_profile_name()
    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())

    # 从结果中提取字段（支持 Pydantic 模型或 dict）
    obj = result.model_dump() if hasattr(result, "model_dump") else result

    profile.app_name = obj.get("app_name", app_name)
    profile.client_id = obj.get("client_id")
    profile.client_secret = obj.get("client_secret")
    profile.cert_content = obj.get("cert_content")
    cm.save_profile(profile_name, profile)

    console.print(
        f"[green]✓[/green] 已切换到应用 [bold]{app_name}[/bold]，证书已保存到 Profile [{profile_name}]"
    )
    console.print(f"  app_name:      {profile.app_name}")
    console.print(f"  client_id:     {profile.client_id}")
    secret = profile.client_secret or ""
    console.print(f"  client_secret: {secret[:6]}...")
    cert = profile.cert_content or ""
    console.print(f"  cert_content:  {cert[:30]}...")
