"""测试 DeepResearcher 核心功能"""
import asyncio
import sys
sys.path.insert(0, str(__file__).replace("\\tests\\test_deep_research.py", "\\src"))

from nsfc_spider.tasks.deep_research import (
    DeepResearcher, DeepResearchConfig, ProjectRetriever,
    parse_json_robust, extract_json_from_text
)
from nsfc_spider.tasks.models import ProjectInfo


def test_json_parsing():
    """测试 JSON 解析"""
    print("1. 测试 JSON 解析...")
    
    # 正常 JSON
    r = parse_json_robust('{"key": "value"}')
    assert r == {"key": "value"}, "正常 JSON 解析失败"
    
    # 带 markdown 代码块
    r = parse_json_robust('```json\n{"key": "value"}\n```')
    assert r == {"key": "value"}, "Markdown JSON 解析失败"
    
    # 带前后文本
    r = parse_json_robust('Here is the result: {"key": "value"} end.')
    assert r == {"key": "value"}, "带文本 JSON 解析失败"
    
    print("   ✓ JSON 解析测试通过")


def test_project_retriever():
    """测试项目检索器"""
    print("2. 测试项目检索器...")
    
    projects = [
        ProjectInfo(
            project_name="基于深度学习的图像识别研究",
            project_leader="张三",
            institution="清华大学",
            keywords="深度学习,图像识别,卷积神经网络"
        ),
        ProjectInfo(
            project_name="轨道交通安全风险评估方法",
            project_leader="李四",
            institution="北京交通大学",
            keywords="轨道交通,风险评估,安全管理"
        ),
        ProjectInfo(
            project_name="人工智能在医疗诊断中的应用",
            project_leader="王五",
            institution="复旦大学",
            keywords="人工智能,医疗诊断,机器学习"
        ),
    ]
    
    retriever = ProjectRetriever(projects)
    
    # 测试检索
    results = retriever.retrieve("深度学习", k=2)
    assert len(results) > 0, "检索结果为空"
    assert any("深度学习" in p.project_name for p in results), "未检索到相关项目"
    
    results = retriever.retrieve("轨道交通风险", k=2)
    assert any("轨道交通" in p.project_name for p in results), "未检索到轨道交通项目"
    
    print(f"   ✓ 项目检索器测试通过 (索引 {len(retriever.index)} 个关键词)")


def test_deep_researcher_config():
    """测试 DeepResearchConfig"""
    print("3. 测试 DeepResearchConfig...")
    
    config = DeepResearchConfig(breadth=4, depth=2, concurrency_limit=3)
    
    assert config.breadth == 4
    assert config.depth == 2
    assert config.concurrency_limit == 3
    
    # 默认值
    default = DeepResearchConfig()
    assert default.breadth == 4
    assert default.depth == 2
    assert default.concurrency_limit == 2
    
    print("   ✓ DeepResearchConfig 测试通过")


def main():
    print("=" * 50)
    print("DeepResearcher 单元测试")
    print("=" * 50)
    
    test_json_parsing()
    test_project_retriever()
    test_deep_researcher_config()
    
    print("=" * 50)
    print("✅ 所有测试通过!")
    print("=" * 50)


if __name__ == "__main__":
    main()
