#!/usr/bin/env python3
"""
测试完整的会话流程 - 找出问题所在
"""
import json
import asyncio
from pathlib import Path
import sys
import os

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

from aacode.utils.session_manager import SessionManager


def test_session_creation_and_usage():
    """测试：创建会话后使用该会话"""
    print("=" * 70)
    print("测试：创建会话 -> 使用会话 -> 验证会话未被重复创建")
    print("=" * 70)
    
    test_dir = Path("/tmp/test_session_flow")
    test_dir.mkdir(exist_ok=True)
    
    async def run():
        sm = SessionManager(test_dir)
        
        # 1. 创建会话
        print("\n[步骤1] 创建会话...")
        task1 = "第一个任务"
        session_id_1 = await sm.create_session(task1)
        print(f"  创建的会话ID: {session_id_1}")
        
        # 检查会话索引
        print(f"  当前会话索引数量: {len(sm.sessions_index)}")
        
        # 2. 模拟前端调用run_task，传递session_id
        print("\n[步骤2] 模拟run_task调用（传递session_id）...")
        session_id = session_id_1
        
        # 检查session_id是否有值
        has_session_id = bool(session_id)
        print(f"  session_id有值: {has_session_id}")
        print(f"  session_id值: {session_id}")
        
        # 模拟后端的逻辑
        if has_session_id:
            print("  -> 调用 switch_session")
            success = await sm.switch_session(session_id)
            print(f"  -> switch_session结果: {success}")
        else:
            print("  -> 调用 create_session（这是问题！）")
            new_session_id = await sm.create_session("新任务")
            print(f"  -> 创建了新会话: {new_session_id}")
        
        # 3. 检查会话数量
        print("\n[步骤3] 验证会话数量...")
        print(f"  会话索引数量: {len(sm.sessions_index)}")
        
        # 列出所有会话
        for sid, info in sm.sessions_index.items():
            print(f"    - {sid}: {info.title}")
        
        # 4. 验证当前会话
        print(f"\n[步骤4] 当前会话: {sm.current_session_id}")
        
        # 清理
        import shutil
        shutil.rmtree(test_dir)
        
        # 结论
        if len(sm.sessions_index) > 1:
            print("\n❌ 问题确认：创建了重复的会话！")
        else:
            print("\n✓ 正常：只创建了一个会话")
    
    asyncio.run(run())


def test_switch_session():
    """测试switch_session是否正常工作"""
    print("\n" + "=" * 70)
    print("测试：switch_session功能")
    print("=" * 70)
    
    test_dir = Path("/tmp/test_switch")
    test_dir.mkdir(exist_ok=True)
    
    async def run():
        sm = SessionManager(test_dir)
        
        # 创建两个会话
        sid1 = await sm.create_session("任务1")
        sid2 = await sm.create_session("任务2")
        
        print(f"创建会话1: {sid1}")
        print(f"创建会话2: {sid2}")
        print(f"当前会话: {sm.current_session_id}")
        
        # 切换到第一个会话
        print(f"\n切换到会话1: {sid1}")
        success = await sm.switch_session(sid1)
        print(f"  结果: {success}")
        print(f"  当前会话: {sm.current_session_id}")
        
        # 切换到第二个会话
        print(f"\n切换到会话2: {sid2}")
        success = await sm.switch_session(sid2)
        print(f"  结果: {success}")
        print(f"  当前会话: {sm.current_session_id}")
        
        # 尝试切换到不存在的会话
        print(f"\n切换到不存在的会话: fake_session")
        success = await sm.switch_session("fake_session")
        print(f"  结果: {success} (应该是False)")
        
        # 清理
        import shutil
        shutil.rmtree(test_dir)
    
    asyncio.run(run())


def analyze_frontend_code():
    """分析前端代码问题"""
    print("\n" + "=" * 70)
    print("分析：前端代码")
    print("=" * 70)
    
    main_js = Path(__file__).parent / "desktop" / "src" / "main.js"
    with open(main_js) as f:
        content = f.read()
    
    # 查找sendMessage函数
    import re
    match = re.search(r'async function sendMessage\(\) \{.*?\n    \}', content, re.MULTILINE | re.DOTALL)
    if match:
        print("\n[sendMessage函数]:")
        print(match.group(0))
    
    # 查找run_task调用
    matches = re.findall(r"invoke\('run_task'.*?\}", content, re.MULTILINE | re.DOTALL)
    print(f"\n[run_task调用次数: {len(matches)}]")
    for i, m in enumerate(matches):
        print(f"\n--- 调用 {i+1} ---")
        print(m[:300])


def analyze_backend_code():
    """分析后端代码问题"""
    print("\n" + "=" * 70)
    print("分析：后端代码")
    print("=" * 70)
    
    commands_rs = Path(__file__).parent / "desktop" / "src-tauri" / "src" / "commands.rs"
    with open(commands_rs) as f:
        content = f.read()
    
    # 查找run_task中的session处理
    import re
    match = re.search(r"if '\{.*?session_id\.as_ref\(\).*?else:.*?create_session", content, re.MULTILINE | re.DOTALL)
    if match:
        print("\n[run_task中的会话处理逻辑]:")
        print(match.group(0))


if __name__ == "__main__":
    test_session_creation_and_usage()
    test_switch_session()
    analyze_frontend_code()
    analyze_backend_code()