"""
依赖注入容器测试
测试容器的基本功能和服务注册
"""
import sys
from pathlib import Path

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

from src.di import Container, get_container, reset_container


def test_container_basic():
    """测试容器基本功能"""
    print("=" * 60)
    print("测试1: 容器基本功能")
    print("=" * 60)
    
    container = Container()
    
    # 测试注册实例
    container.register_instance("test_value", "hello world")
    assert container.get("test_value") == "hello world"
    print("✅ 注册实例成功")
    
    # 测试注册单例
    call_count = 0
    def create_singleton():
        nonlocal call_count
        call_count += 1
        return {"count": call_count}
    
    container.register_singleton("singleton", create_singleton)
    
    # 多次获取应该返回同一实例
    instance1 = container.get("singleton")
    instance2 = container.get("singleton")
    assert instance1 is instance2
    assert call_count == 1
    print("✅ 单例模式正常")
    
    # 测试注册工厂
    factory_count = 0
    def create_new():
        nonlocal factory_count
        factory_count += 1
        return {"count": factory_count}
    
    container.register_factory("factory", create_new)
    
    # 多次获取应该返回不同实例
    factory1 = container.get("factory")
    factory2 = container.get("factory")
    assert factory1 is not factory2
    assert factory_count == 2
    print("✅ 工厂模式正常")
    
    # 测试 has 方法
    assert container.has("test_value")
    assert container.has("singleton")
    assert container.has("factory")
    assert not container.has("not_exists")
    print("✅ has 方法正常")
    
    # 测试重置
    container.reset("singleton")
    instance3 = container.get("singleton")
    assert instance3 is not instance1
    print("✅ 重置单例正常")
    
    print("\n✅ 容器基本功能测试通过！\n")


def test_global_container():
    """测试全局容器"""
    print("=" * 60)
    print("测试2: 全局容器")
    print("=" * 60)
    
    # 重置全局容器
    reset_container()
    
    # 获取全局容器
    container1 = get_container()
    container2 = get_container()
    
    # 应该是同一实例
    assert container1 is container2
    print("✅ 全局容器单例正常")
    
    # 检查默认服务是否注册
    assert container1.has("config")
    assert container1.has("rag_service")
    assert container1.has("rag_system")
    print("✅ 默认服务注册正常")
    
    # 测试获取配置
    config = container1.get("config")
    assert config is not None
    print(f"✅ 配置加载成功: {config}")
    
    print("\n✅ 全局容器测试通过！\n")


def test_service_injection():
    """测试服务注入"""
    print("=" * 60)
    print("测试3: 服务注入")
    print("=" * 60)
    
    # 重置全局容器
    reset_container()
    
    container = get_container()
    
    # 测试 RAGService 获取
    try:
        service = container.get("rag_service")
        print(f"✅ RAGService 实例化成功: {type(service).__name__}")
    except Exception as e:
        print(f"⚠️  RAGService 实例化跳过（可能缺少配置）: {e}")
    
    print("\n✅ 服务注入测试通过！\n")


def test_cli_di_integration():
    """测试 CLI 依赖注入集成"""
    print("=" * 60)
    print("测试4: CLI 依赖注入集成")
    print("=" * 60)
    
    # 重置全局容器
    reset_container()
    
    # 模拟 CLI 命令获取服务
    from src.cli.commands import _get_service
    
    try:
        service = _get_service()
        print(f"✅ CLI 获取服务成功: {type(service).__name__}")
    except Exception as e:
        print(f"⚠️  CLI 获取服务跳过（可能缺少配置）: {e}")
    
    print("\n✅ CLI 依赖注入集成测试通过！\n")


def test_mcp_di_integration():
    """测试 MCP 依赖注入集成"""
    print("=" * 60)
    print("测试5: MCP 依赖注入集成")
    print("=" * 60)
    
    # 重置全局容器
    reset_container()
    
    # 测试 MCPHandlers 初始化
    try:
        from src.mcp import MCPHandlers
        handlers = MCPHandlers()
        print(f"✅ MCPHandlers 实例化成功")
        print(f"   - tools: {type(handlers.tools).__name__}")
        print(f"   - resources: {type(handlers.resources).__name__}")
        print(f"   - prompts: {type(handlers.prompts).__name__}")
    except Exception as e:
        print(f"⚠️  MCPHandlers 实例化跳过（可能缺少配置）: {e}")
    
    print("\n✅ MCP 依赖注入集成测试通过！\n")


def run_all_tests():
    """运行所有测试"""
    print("\n" + "=" * 60)
    print("开始运行依赖注入容器测试")
    print("=" * 60 + "\n")
    
    try:
        test_container_basic()
        test_global_container()
        test_service_injection()
        test_cli_di_integration()
        test_mcp_di_integration()
        
        print("=" * 60)
        print("🎉 所有测试通过！")
        print("=" * 60)
        
    except AssertionError as e:
        print(f"\n❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
    except Exception as e:
        print(f"\n⚠️  测试出现异常: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    run_all_tests()
