"""Hezor2 SDK 使用示例。

本示例演示 Hezor2 SDK 的使用方法：

1. 查询 Webhook Action 文档（webhook_help）
2. 查询报告状态（get_report_status）

Usage
-----
运行所有示例:
    uv run examples/transfer/hezor2_sdk_example.py

运行指定示例:
    uv run examples/transfer/hezor2_sdk_example.py 1
    uv run examples/transfer/hezor2_sdk_example.py 2

列出所有示例:
    uv run examples/transfer/hezor2_sdk_example.py --list
"""

import asyncio
import json
import logging
import sys
from pathlib import Path

from dotenv import load_dotenv

# ⚠️ 重要：必须在导入 SDK 之前加载环境变量
# 因为 constants.py 在模块导入时会读取环境变量创建默认值
env_file = Path(__file__).parent.parent / ".env"
load_dotenv(dotenv_path=env_file)

# 添加项目根目录到 Python 路径
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

# 现在导入 SDK，此时 constants.py 能读取到 .env 中的环境变量
from hezor_common.transfer.hezor2_sdk import Hezor2SDK, MetaInfo  # noqa: E402
from hezor_common.transfer.hezor2_sdk.env_config import Hezor2EnvConfig  # noqa: E402

# 配置日志级别
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)

print(f"✓ 已加载环境变量: {env_file}")
print()

# 从环境变量读取配置
config = Hezor2EnvConfig()
print(f"✓ API Base URL: {config.hezor2_api_base_url}")
print()


def _build_sdk() -> Hezor2SDK:
    """构建 SDK 实例（带可选的认证配置）。"""
    kwargs: dict = {
        "base_url": config.hezor2_api_base_url,
        "api_key": config.hezor2_api_key,
    }

    # 如果配置了应用名称，则传递给 SDK
    if config.hezor2_app_name:
        kwargs["app_name"] = config.hezor2_app_name

    # MetaInfo 始终传递（无私钥时 SDK 会使用匿名密钥签名）
    kwargs["meta_info"] = MetaInfo(
        caller_id="example/hezor2_sdk",
        subject="example",
        subject_code="example_001",
        creation_name="示例创建",
        creation_slug="example_creation",
        data_coverage="20240101-20241231",
    )

    # 如果配置了私钥，则使用私钥签名（否则 SDK 自动使用匿名密钥）
    if config.hezor2_header_pk_filepath:
        private_key_path = Path(config.hezor2_header_pk_filepath)
        if not private_key_path.is_absolute():
            examples_dir = Path(__file__).parent.parent
            private_key_path = examples_dir / private_key_path

        if private_key_path.exists():
            kwargs["private_key_path"] = str(private_key_path)
            if config.hezor2_header_pk_password:
                kwargs["password"] = config.hezor2_header_pk_password.encode()
            print(f"  ✓ 使用私钥认证: {private_key_path}")
        else:
            print(f"  ⚠ 私钥文件不存在: {private_key_path}，将使用匿名密钥签名")

    return Hezor2SDK(**kwargs)


def example_1_webhook_help():
    """Example 1: 查询 Webhook Action 文档。"""
    print("=== Example 1: 查询 Webhook Action 文档 ===")
    print()

    actions = [
        "generate_report_id",
        "publish_creation_report",
        "get_report_status",
    ]

    async def run():
        async with _build_sdk() as sdk:
            for action in actions:
                print(f"--- {action} ---")
                try:
                    info = await sdk.webhook_help(action)
                    print(f"  描述: {info.description[:80]}")
                    print()

                    # 用法
                    print(f"  用法: {info.usage.method} {info.usage.url}")
                    print("  请求头:")
                    for k, v in info.usage.headers.items():
                        print(f"    {k}: {v}")
                    print("  请求体:")
                    for k, v in info.usage.body.items():
                        print(f"    {k}: {v}")
                    print()

                    # Payload schema
                    props = info.payload_schema.get("properties", {})
                    required = info.payload_schema.get("required", [])
                    if props:
                        print("  Payload 字段:")
                        for name, schema in props.items():
                            req_mark = " *" if name in required else ""
                            typ = schema.get("type", schema.get("anyOf", ""))
                            desc = schema.get("description", "")
                            print(f"    {name}{req_mark} ({typ}): {desc}")
                    print()

                    # Response data schema
                    resp_props = info.response_data_schema.get("properties", {})
                    resp_required = info.response_data_schema.get("required", [])
                    if resp_props:
                        print("  Response 字段:")
                        for name, schema in resp_props.items():
                            req_mark = " *" if name in resp_required else ""
                            typ = schema.get("type", schema.get("anyOf", ""))
                            desc = schema.get("description", "")
                            print(f"    {name}{req_mark} ({typ}): {desc}")

                    print()
                except Exception as e:
                    print(f"  ✗ 查询失败: {e}")
                    print()

    try:
        asyncio.run(run())
    except Exception as e:
        print(f"调用失败（需要连接 Hezor2 API）: {e}")

    print()


def example_2_webhook_help_full_schema():
    """Example 2: 查看单个 Action 的完整 Schema。"""
    print("=== Example 2: 查看单个 Action 的完整 Schema ===")
    print()

    async def run():
        async with _build_sdk() as sdk:
            info = await sdk.webhook_help("publish_creation_report")
            print(json.dumps(info.model_dump(), indent=2, ensure_ascii=False))

    try:
        asyncio.run(run())
    except Exception as e:
        print(f"调用失败（需要连接 Hezor2 API）: {e}")

    print()


def example_3_get_report_status():
    """Example 3: 查询报告状态。"""
    print("=== Example 3: 查询报告状态 ===")
    print()

    # 提示：需要替换为实际存在的 ID
    creation_id = "single_store_profit_model"
    report_id = "rpt_TyDyhKtse3o"

    print(f"  Creation ID: {creation_id}")
    print(f"  Report ID:   {report_id}")
    print()

    async def run():
        async with _build_sdk() as sdk:
            metadata = await sdk.get_report_status(
                creation_id=creation_id,
                report_id=report_id,
            )
            print("  ✓ 报告元数据:")
            print(f"    报告 ID:   {metadata.report_id}")
            print(f"    标题:      {metadata.report_title}")
            print(f"    描述:      {metadata.description}")
            print(f"    生成时间:  {metadata.generated_at}")
            print(f"    校验码:    {metadata.verification_code}")
            print(f"    状态消息:  {metadata.status_message}")
            print(f"    摘要:      {metadata.summary}")

    try:
        asyncio.run(run())
    except Exception as e:
        print(f"调用失败（需要连接 Hezor2 API 并提供有效 ID）: {e}")

    print()


# 列出和主函数
def list_examples():
    """列出所有可用示例。"""
    examples = {
        1: ("查询 Webhook Action 文档", example_1_webhook_help),
        2: ("查看单个 Action 的完整 Schema", example_2_webhook_help_full_schema),
        3: ("查询报告状态", example_3_get_report_status),
    }

    print("可用示例:")
    for num, (name, _) in examples.items():
        print(f"  {num}. {name}")
    print()
    print("使用方法:")
    print(f"  uv run {sys.argv[0]} [示例编号]")
    print(f"  uv run {sys.argv[0]}              # 运行所有示例")
    print(f"  uv run {sys.argv[0]} --list       # 列出示例")

    return examples


def main():
    """运行示例。"""
    examples = {
        1: ("查询 Webhook Action 文档", example_1_webhook_help),
        2: ("查看单个 Action 的完整 Schema", example_2_webhook_help_full_schema),
        3: ("查询报告状态", example_3_get_report_status),
    }

    # 解析命令行参数
    if len(sys.argv) > 1:
        arg = sys.argv[1]

        if arg in ["--list", "-l", "list"]:
            list_examples()
            return

        try:
            example_num = int(arg)
            if example_num not in examples:
                print(f"错误: 示例 {example_num} 不存在。")
                print()
                list_examples()
                sys.exit(1)

            # 运行单个示例
            name, func = examples[example_num]
            print("=" * 60)
            print(f"Hezor2 SDK - 示例 {example_num}")
            print("=" * 60)
            print()
            func()
            print("=" * 60)
            print(f"示例 {example_num} 完成！")
            print("=" * 60)
            return

        except ValueError:
            print(f"错误: 无效的参数 '{arg}'")
            print()
            list_examples()
            sys.exit(1)

    # 运行所有示例
    print("=" * 60)
    print("Hezor2 SDK - 使用示例")
    print("=" * 60)
    print()

    for func in [
        example_1_webhook_help,
        example_2_webhook_help_full_schema,
        example_3_get_report_status,
    ]:
        func()

    print("=" * 60)
    print("所有示例完成！")
    print("=" * 60)


if __name__ == "__main__":
    main()
