"""
测试动态生成的工具 Schema
"""

import asyncio
import sys
import json
from pathlib import Path

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

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker

from app.core.config import get_settings
from app.services.mid.kb_search_dynamic_tool import KbSearchDynamicTool


async def test_dynamic_tool_schema():
    """测试动态生成的工具 Schema"""
    settings = get_settings()
    
    engine = create_async_engine(settings.database_url)
    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    
    tenant_id = "szmp@ash@2026"
    
    print(f"\n{'='*80}")
    print(f"测试动态生成的工具 Schema")
    print(f"{'='*80}")
    print(f"租户 ID: {tenant_id}")
    
    async with async_session() as session:
        tool = KbSearchDynamicTool(session)
        
        # 获取静态 Schema
        static_schema = tool.get_tool_schema()
        print(f"\n--- 静态 Schema ---")
        print(json.dumps(static_schema, indent=2, ensure_ascii=False))
        
        # 获取动态 Schema
        dynamic_schema = await tool.get_dynamic_tool_schema(tenant_id)
        print(f"\n--- 动态 Schema ---")
        print(json.dumps(dynamic_schema, indent=2, ensure_ascii=False))
        
        # 再次获取，测试缓存
        print(f"\n--- 测试缓存 ---")
        dynamic_schema2 = await tool.get_dynamic_tool_schema(tenant_id)
        print(f"缓存命中: {dynamic_schema == dynamic_schema2}")
        
        # 打印 context 字段的详细结构
        print(f"\n--- context 字段详情 ---")
        context_props = dynamic_schema["parameters"]["properties"].get("context", {}).get("properties", {})
        print(f"过滤字段数量: {len(context_props)}")
        for key, value in context_props.items():
            print(f"  {key}: {value}")


if __name__ == "__main__":
    asyncio.run(test_dynamic_tool_schema())
