"""Hezor2 SDK data_retrieve 使用示例。

本示例演示通过 Hezor2 SDK 调用数据检索接口：

1. 基础检索（使用默认参数）
2. 提高 top_k 匹配多个工具
3. 结果详情展示（遍历各工具执行结果）

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

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

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

import asyncio
import logging
import sys
from pathlib import Path

from dotenv import load_dotenv

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

sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent))

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.WARNING,
    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,
    }

    if config.hezor2_app_name:
        kwargs["app_name"] = config.hezor2_app_name

    kwargs["meta_info"] = MetaInfo(
        caller_id="example/data_retrieve",
        subject="example",
        subject_code="example_001",
        creation_name="示例创建",
        creation_slug="example_creation",
        data_coverage="20240101-20241231",
    )

    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.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_basic_retrieve():
    """Example 1: 基础数据检索（默认 top_k=1）。"""
    print("=== Example 1: 基础数据检索 ===")
    print()

    query = "去年稻飞虱高发期的数据"
    print(f"  查询: {query}")
    print("  top_k: 1（默认）")
    print()

    async def run():
        async with _build_sdk() as sdk:
            result = await sdk.data_retrieve(query=query)

            print("  ✓ 检索完成")
            print(f"  原始查询:    {result.query}")
            print(f"  匹配工具数:  {len(result.results)} 个")
            print()

            for tool_name, resp in result.results.items():
                status = "✓" if resp.success else "✗"
                print(f"  {status} 工具: {tool_name}")
                print(f"    success: {resp.success}")
                print(f"    count:   {resp.count}")
                if resp.desc:
                    print(f"    desc:    {resp.desc}")
                if not resp.success and resp.error:
                    print(f"    error:   {resp.error}")

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

    print()


def example_2_multi_tools():
    """Example 2: 提高 top_k 匹配多个工具。"""
    print("=== Example 2: 匹配多个工具（top_k=3）===")
    print()

    query = "统计本月各地区农作物病害发生情况"
    top_k = 3
    print(f"  查询: {query}")
    print(f"  top_k: {top_k}")
    print()

    async def run():
        async with _build_sdk() as sdk:
            result = await sdk.data_retrieve(query=query, top_k=top_k)

            print("  ✓ 检索完成")
            print(f"  匹配工具数:  {len(result.results)} 个")
            print()

            for tool_name, resp in result.results.items():
                status = "✓" if resp.success else "✗"
                print(f"  {status} {tool_name}  (count={resp.count})")

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

    print()


def example_3_result_details():
    """Example 3: 结果详情展示（遍历各工具执行数据）。"""
    print("=== Example 3: 结果详情展示 ===")
    print()

    query = "查询稻飞虱近期监测记录"
    print(f"  查询: {query}")
    print()

    async def run():
        async with _build_sdk() as sdk:
            result = await sdk.data_retrieve(query=query, top_k=2)

            print("  ✓ 检索完成")
            print(f"  query:      {result.query}")
            print(f"  工具数量:   {len(result.results)}")
            print()

            for tool_name, resp in result.results.items():
                print(f"  ── 工具: {tool_name} ──")
                print(f"    success: {resp.success}")
                print(f"    count:   {resp.count}")
                if resp.desc:
                    print(f"    desc:    {resp.desc}")

                if resp.success:
                    data = resp.data
                    if isinstance(data, list):
                        print(f"    data:    list({len(data)} items)")
                        for i, item in enumerate(data[:3]):
                            print(f"      [{i}] {str(item)[:100]}")
                        if len(data) > 3:
                            print(f"      ... 共 {len(data)} 条")
                    elif isinstance(data, dict):
                        print(f"    data:    dict({len(data)} keys)")
                        for k, v in list(data.items())[:5]:
                            print(f"      {k}: {str(v)[:80]}")
                        if len(data) > 5:
                            print(f"      ... 共 {len(data)} 个键")
                else:
                    print(f"    error:   {resp.error}")
                print()

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

    print()


def list_examples():
    """列出所有可用示例。"""
    examples = {
        1: ("基础数据检索（top_k=1）", example_1_basic_retrieve),
        2: ("匹配多个工具（top_k=3）", example_2_multi_tools),
        3: ("结果详情展示（遍历执行数据）", example_3_result_details),
    }

    print("Available examples:")
    for num, (name, _) in examples.items():
        print(f"  {num}. {name}")
    print()
    print("Usage:")
    print(f"  uv run {sys.argv[0]} [example_number]")
    print(f"  uv run {sys.argv[0]}              # 运行所有示例")
    print(f"  uv run {sys.argv[0]} --list       # 列出示例")

    return examples


def main():
    """根据命令行参数运行示例。"""
    examples = {
        1: ("基础数据检索（top_k=1）", example_1_basic_retrieve),
        2: ("匹配多个工具（top_k=3）", example_2_multi_tools),
        3: ("结果详情展示（遍历执行数据）", example_3_result_details),
    }

    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"Error: Example {example_num} not found.")
                print()
                list_examples()
                sys.exit(1)

            name, func = examples[example_num]
            print("=" * 60)
            print(f"data_retrieve - Example {example_num}")
            print("=" * 60)
            print()
            func()
            print("=" * 60)
            print(f"Example {example_num} completed successfully!")
            print("=" * 60)
            return

        except ValueError:
            print(f"Error: Invalid argument '{arg}'")
            print()
            list_examples()
            sys.exit(1)

    # 运行所有示例
    print("=" * 60)
    print("data_retrieve - Usage Examples")
    print("=" * 60)
    print()

    for func in [example_1_basic_retrieve, example_2_multi_tools, example_3_result_details]:
        func()

    print("=" * 60)
    print("All examples completed successfully!")
    print("=" * 60)


if __name__ == "__main__":
    main()
