"""Knowledge Graph SDK 向量搜索使用示例。

演示如何使用 Knowledge Graph SDK 进行向量搜索。

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

运行特定示例:
    uv run examples/transfer/knowledge_graph_sdk_example.py 1
    uv run examples/transfer/knowledge_graph_sdk_example.py 2

列出可用示例:
    uv run examples/transfer/knowledge_graph_sdk_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 / ".env"
if env_file.exists():
    load_dotenv(env_file)
    print(f"✓ 已加载环境变量: {env_file}")
else:
    print(f"⚠️  未找到 .env 文件: {env_file}（使用环境变量默认值）")
print()

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

# 现在导入 SDK，此时 constants.py 能读取到 .env 中的环境变量
from hezor_common.transfer.knowledge_graph_sdk import (  # noqa: E402
    KnowledgeGraphSDK,
    vector_search,
)
from hezor_common.transfer.knowledge_graph_sdk.env_config import (  # noqa: E402
    KnowledgeGraphEnvConfig,
)

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

# 从环境变量读取配置（使用 KnowledgeGraphEnvConfig）
config = KnowledgeGraphEnvConfig()
print(f"✓ API Base URL: {config.knowledge_graph_api_base_url}")
print()


def example_1_basic_search():
    """Example 1: 基本向量搜索."""
    print("=== Example 1: 基本向量搜索 ===")
    print("演示如何使用 SDK 类进行向量搜索")
    print()

    async def run():
        # 不传参数，使用 .env 中的环境变量作为默认值
        async with KnowledgeGraphSDK() as sdk:
            result = await sdk.vector_search(
                question="中式正餐的特点",
                limit=5,
                score_threshold=0.5,
            )

            print(f"✓ 搜索问题: {result.question}")
            print(f"✓ 找到实体: {len(result.search_results.entities)} 个")
            print(f"✓ 找到关系: {len(result.search_results.relationships)} 个")
            print(f"✓ 找到文本块: {len(result.search_results.chunks)} 个")
            print(f"✓ 找到图片: {len(result.search_results.pictures)} 个")
            print(f"✓ 找到社区: {len(result.search_results.communities)} 个")

            if result.search_results.entities:
                print("\n前几个实体:")
                for entity_item in result.search_results.entities[:3]:
                    print(f"  - {entity_item.metadata.name} (得分: {entity_item.score:.4f})")
                    print(f"    类型: {entity_item.metadata.entity_type}")

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

    print()


def example_2_convenience_function():
    """Example 2: 使用便捷函数."""
    print("=== Example 2: 使用便捷函数 ===")
    print("演示如何使用便捷函数进行快速搜索")
    print()

    async def run():
        result = await vector_search(
            question="中式正餐的特点",
            limit=10,
            score_threshold=0.6,
            enable_entity_extraction=True,
        )

        print(f"✓ 搜索问题: {result.question}")
        print(f"✓ 总共找到 {len(result.search_results.entities)} 个相关实体")

        if result.search_results.chunks:
            print(f"\n找到 {len(result.search_results.chunks)} 个文本块:")
            for chunk_item in result.search_results.chunks[:2]:
                content_preview = (
                    chunk_item.content[:100] + "..."
                    if len(chunk_item.content) > 100
                    else chunk_item.content
                )
                print(f"  - 得分: {chunk_item.score:.4f}")
                print(f"    内容: {content_preview}")
                print(f"    文档: {chunk_item.metadata.doc_name}")

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

    print()


def example_3_pagination():
    """Example 3: 分页搜索."""
    print("=== Example 3: 分页搜索 ===")
    print("演示如何使用分页功能")
    print()

    async def run():
        question = "菜品分类"

        # 第一页
        page1 = await vector_search(
            question=question,
            limit=5,
            offset=0,
        )
        print(f"✓ 第一页: 找到 {len(page1.search_results.entities)} 个实体")

        # 第二页
        page2 = await vector_search(
            question=question,
            limit=5,
            offset=5,
        )
        print(f"✓ 第二页: 找到 {len(page2.search_results.entities)} 个实体")

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

    print()


def example_4_health_check():
    """Example 4: 服务健康检查."""
    print("=== Example 4: 服务健康检查 ===")
    print("演示如何检查 Knowledge Graph 服务状态")
    print()

    async def run():
        async with KnowledgeGraphSDK() as sdk:
            is_healthy, health_data = await sdk.health_check()
            print(f"✓ 服务状态: {'健康' if is_healthy else '异常'}")
            if health_data:
                print(f"✓ 响应数据: {health_data}")

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

    print()


def list_examples():
    """List all available examples."""
    examples = {
        1: ("基本向量搜索", example_1_basic_search),
        2: ("使用便捷函数", example_2_convenience_function),
        3: ("分页搜索", example_3_pagination),
        4: ("服务健康检查", example_4_health_check),
    }

    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]}              # Run all examples")
    print(f"  uv run {sys.argv[0]} --list       # List examples")

    return examples


def main():
    """Run examples based on command line arguments."""
    examples = {
        1: ("基本向量搜索", example_1_basic_search),
        2: ("使用便捷函数", example_2_convenience_function),
        3: ("分页搜索", example_3_pagination),
        4: ("服务健康检查", example_4_health_check),
    }

    # Parse command line arguments
    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)

            # Run single example
            name, func = examples[example_num]
            print("=" * 60)
            print(f"Knowledge Graph SDK - 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)

    # Run all examples
    print("=" * 60)
    print("Knowledge Graph SDK - Usage Examples")
    print("=" * 60)
    print()

    for func in [
        example_1_basic_search,
        example_2_convenience_function,
        example_3_pagination,
        example_4_health_check,
    ]:
        func()

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


if __name__ == "__main__":
    main()
