#!/usr/bin/env python3
# -*- coding: utf-8 -*-
\"\"\"\"\"

"""
集成测试脚本 - 测试核心模块的集成
\"\"\"

import asyncio
import sys
import json
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent

async def main():
    """主测试入口"""
    print("=" * 50)
    print("集成测试")
    print()

    # 测试 1: 验证 Zai-sdk 导入
    print("[1/6] 测试 zai-sdk 导入...")
    try:
        from zai import ZhipuAiClient
        print("  ✓ zai-sdk 导入成功")
    except ImportError as e:
        print(f" ✗ zai-sdk 导入失败: {str(e)}")
        return False

    # 测试 2: 验证 Skill Manager
    print()
    print("[2/6] 测试 Skill Manager...")
    try:
        from app.core.skills.skill_manager import get_skill_manager
        sm = get_skill_manager()

        # 测试加载 skill-creator
        skill = await sm.load_skill("skill-creator")
        if skill:
            print(f"  ✓ skill-creator 加载成功")
            print(f"   名称: {skill.name}")
        else:
            print(" ✗ skill-creator 未找到")

        # 测试获取工具列表
        tools = sm.get_available_tools_for_llm()
        print(f"  工具数量: {len(tools)}")

    except Exception as e:
        print(f" ✗ Skill Manager 测试失败: {str(e)}")
        return False

    # 测试 3: 验证记忆系统
    print()
    print("[3/6] 测试 Memory Manager...")
    try:
        from app.core.memory.memory_manager import get_memory_manager
        mm = get_memory_manager()

        # 测试事件提取
        events = await mm.extract_events_from_episode(
            episode_content=\"测试 EP01 内容：李云飞与苏婉儿在江南相遇，两人决定私定终身...",
            episode_number=1,
            characters=["李云飞", "苏婉儿"]
        )
        print(f"  ✓ 提取 {len(events)} 个事件")

        # 测试伏笔检测
        foreshadowing, threads = await mm.detect_foreshadowing(
            episode_content=\"测试 EP02 内容...",
            episode_number=2,
            existing_threads=[]
        )
        print(f"  ✓ 检测到 {len(foreshadowing)} 个伏笔，新增 {len(threads)} 个待收线")

    except Exception as e:
        print(f" ✗ Memory Manager 测试失败: {str(e)}")
        return False

    # 测试 4: 验证审核系统
    print()
    print("[4/6] 测试 Review Manager...")
    try:
        from app.core.review.review_manager import get_review_manager
        rm = get_review_manager()

        # 测试维度列表
        dimensions = rm.list_all_dimensions()
        print(f"  ✓ 审核维度: {len(dimensions)}")

        except Exception as e:
        print(f" ✗ Review Manager 测试失败: {str(e)}")
        return False

    # 测试 5: 验证批次执行
    print()
    print("[5/6] 测试 Batch Executor...")
    try:
        from app.core.execution.batch_executor import get_batch_executor
        be = get_batch_executor()

        print("批次执行测试...")
        # 创建测试项目
        from app.models.project import SeriesProject
        project = SeriesProject(
            id="test-project-001",
            name="测试项目",
            type="series",
            globalContext={"worldSetting": "测试世界观"},
            characterProfiles={},
            sceneSettings={},
            overallOutline="测试大纲",
            styleGuide="测试风格",
            skills={"dialogue_writer_ancient": "dialogue-writer-ancient"}
        )

        # 模拟批次执行
        result = await be.execute_batch(
            project=project,
            start_episode=1,
            end_episode=3,
            enable_retry=False,
            max_retries=1,
            on_progress=lambda d: print(f"   进度: {d['progress_percentage']}"),
            on_episode_complete=lambda d: print(f" 集 {d['current_episode']} 完成")
        )

        print(f" ✓ 批次执行完成")
        print(f"   耗分:")
        print(f"   成功: {result['successful']}")
        print(f"  失败: {result['failed']}")
        print(f" 耗率: {result['success_rate']}")
        print(f" 质量: {result.get('quality_stats', {}).get('average', 0):.1f}")

    except Exception as e:
        print(f" ✗ Batch Executor 测试失败: {str(e)}")
        return False

    print()
    print("=" * 50)
    print("所有测试完成！")
    print()
    print("说明：")
    print("如果测试全部通过，说明核心模块可以正常协作。")
    print("如果某些测试失败，根据错误信息修复对应模块。")

    return True


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