#!/usr/bin/env python3
"""
端到端测试 - 验证整个Tauri Desktop流程
"""
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_complete_flow():
    """测试完整的前后端交互流程"""
    print("=" * 70)
    print("端到端测试：完整流程")
    print("=" * 70)
    
    test_dir = Path("/tmp/test_e2e")
    test_dir.mkdir(exist_ok=True)
    
    async def run():
        # ========== 模拟步骤 ==========
        
        # 步骤1: 用户点击New Session
        print("\n[步骤1] 用户点击New Session")
        sm = SessionManager(test_dir)
        session_id = await sm.create_session("新会话")
        print(f"  创建会话: {session_id}")
        
        # 模拟后端返回给前端的Session对象
        # Rust的Session结构体有 #[serde(rename = "sessionId")]
        # 所以序列化后是 sessionId
        session_data = {
            "sessionId": session_id,
            "title": "新会话",
            "createdAt": sm.sessions_index[session_id].created_at,
            "lastActivity": sm.sessions_index[session_id].last_activity,
            "status": "active"
        }
        print(f"  后端返回: {json.dumps(session_data)}")
        
        # 步骤2: 前端设置currentSession
        print("\n[步骤2] 前端设置currentSession")
        current_session = session_data
        print(f"  state.currentSession = {current_session}")
        
        # 步骤3: 用户发送任务
        print("\n[步骤3] 用户发送任务")
        task = "创建一个Hello World程序"
        
        # 前端检查是否有currentSession
        has_session = bool(current_session)
        print(f"  has currentSession: {has_session}")
        
        # 前端调用run_task，传递sessionId
        session_id_for_task = current_session.get("sessionId")
        print(f"  传递给run_task的sessionId: {session_id_for_task}")
        
        # 步骤4: 后端处理
        print("\n[步骤4] 后端处理")
        
        # 模拟run_task中的逻辑
        if session_id_for_task:
            print(f"  session_id有值 -> switch_session({session_id_for_task})")
            success = await sm.switch_session(session_id_for_task)
            print(f"  结果: {success}")
        else:
            print(f"  session_id为空 -> create_session")
            new_id = await sm.create_session(task)
            print(f"  新会话: {new_id}")
        
        # 步骤5: 验证结果
        print("\n[步骤5] 验证结果")
        print(f"  会话总数: {len(sm.sessions_index)}")
        
        if len(sm.sessions_index) == 1:
            print("  ✓ 正常：只创建了1个会话")
        else:
            print(f"  ❌ 错误：创建了{len(sm.sessions_index)}个会话")
        
        # 清理
        import shutil
        shutil.rmtree(test_dir)
    
    asyncio.run(run())


def test_session_message_loading_issue():
    """测试会话消息加载问题"""
    print("\n" + "=" * 70)
    print("测试：会话消息加载")
    print("=" * 70)
    
    test_dir = Path("/tmp/test_messages")
    test_dir.mkdir(exist_ok=True)
    
    async def run():
        sm = SessionManager(test_dir)
        
        # 创建会话并添加消息
        session_id = await sm.create_session("测试任务")
        await sm.add_message("user", "第一个问题")
        await sm.add_message("assistant", "第一个回答")
        await sm.add_message("user", "第二个问题")
        await sm.add_message("assistant", "第二个回答")
        await sm._save_session()
        
        # 模拟后端get_session_messages
        session_file = sm.sessions_dir / f"{session_id}.json"
        with open(session_file) as f:
            data = json.load(f)
        
        messages = data.get("messages", [])
        
        print(f"\n[会话消息总数: {len(messages)}]")
        
        # 模拟前端过滤system消息
        filtered = [m for m in messages if m["role"] != "system"]
        print(f"[过滤system后: {len(filtered)}条]")
        
        for msg in filtered:
            role = msg["role"]
            content = msg["content"][:30]
            print(f"  {role}: {content}...")
        
        # 清理
        import shutil
        shutil.rmtree(test_dir)
    
    asyncio.run(run())


async def test_error_handling_async():
    """测试错误处理"""
    print("\n" + "=" * 70)
    print("测试：错误处理")
    print("=" * 70)
    
    # 测试1: 项目路径不存在
    print("\n[测试1] 项目路径不存在")
    fake_dir = Path("/fake/path")
    sm = SessionManager(fake_dir)
    sessions = await sm.list_sessions()
    print(f"  结果: {len(sessions)} 个会话")
    
    # 测试2: 会话文件不存在
    print("\n[测试2] 会话文件不存在")
    test_dir = Path("/tmp/test_error")
    test_dir.mkdir(exist_ok=True)
    sm2 = SessionManager(test_dir)
    success = await sm2.load_session("nonexistent")
    print(f"  结果: {success}")
    
    import shutil
    shutil.rmtree(test_dir)


def test_error_handling():
    asyncio.run(test_error_handling_async())


if __name__ == "__main__":
    test_complete_flow()
    test_session_message_loading_issue()
    test_error_handling()
    print("\n" + "=" * 70)
    print("测试完成")
    print("=" * 70)