#!/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 simulate_frontend_backend_flow():
    """模拟完整的前后端交互流程"""
    print("=" * 70)
    print("完整流程模拟：New Session -> 发送任务 -> 查看结果")
    print("=" * 70)
    
    test_dir = Path("/tmp/test_full_integration")
    test_dir.mkdir(exist_ok=True)
    
    async def run():
        # ========== 步骤1: 用户点击New Session按钮 ==========
        print("\n" + "=" * 50)
        print("步骤1: 用户点击New Session按钮")
        print("=" * 50)
        
        sm = SessionManager(test_dir)
        
        # 前端调用 create_session API
        task = "新会话"
        session_id = await sm.create_session(task)
        
        print(f"后端返回: sessionId = {session_id}")
        print(f"会话索引数量: {len(sm.sessions_index)}")
        
        # 前端收到响应，设置 state.currentSession
        current_session = {
            "sessionId": session_id,
            "session_id": session_id,
            "title": sm.sessions_index[session_id].title
        }
        print(f"前端 state.currentSession = {current_session}")
        
        # 前端刷新会话列表
        sessions = await sm.list_sessions()
        print(f"前端会话列表: {len(sessions)} 个会话")
        
        # ========== 步骤2: 用户选择会话并发送任务 ==========
        print("\n" + "=" * 50)
        print("步骤2: 用户选择会话并发送任务")
        print("=" * 50)
        
        # 模拟用户选择会话
        selected_session_id = current_session["sessionId"]
        print(f"用户选择的会话: {selected_session_id}")
        
        # 模拟前端调用 run_task，传递 sessionId
        session_id_for_task = selected_session_id
        print(f"前端传递给run_task的sessionId: {session_id_for_task}")
        
        # 后端处理
        print("\n后端处理:")
        
        # 检查session_id是否有值
        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"  switch_session结果: {success}")
        else:
            print(f"  session_id为空 -> 调用 create_session")
            session_id_for_task = await sm.create_session("新任务")
            print(f"  创建了新会话: {session_id_for_task}")
        
        # 验证当前会话
        print(f"\n验证: 当前会话 = {sm.current_session_id}")
        
        # 检查会话数量
        print(f"会话索引数量: {len(sm.sessions_index)}")
        
        # 列出所有会话
        for sid, info in sm.sessions_index.items():
            marker = " <- 当前" if sid == sm.current_session_id else ""
            print(f"  - {sid}: {info.title}{marker}")
        
        # ========== 步骤3: 检查是否有重复创建 ==========
        print("\n" + "=" * 50)
        print("步骤3: 验证结果")
        print("=" * 50)
        
        if len(sm.sessions_index) == 1:
            print("✓ 正常：只创建了1个会话")
        else:
            print(f"❌ 问题：创建了 {len(sm.sessions_index)} 个会话（应该只有1个）")
        
        # 清理
        import shutil
        shutil.rmtree(test_dir)
    
    asyncio.run(run())


def test_get_session_list_format():
    """测试get_session_list返回的数据格式"""
    print("\n" + "=" * 70)
    print("测试: get_session_list返回格式")
    print("=" * 70)
    
    test_dir = Path("/tmp/test_list_format")
    test_dir.mkdir(exist_ok=True)
    
    async def run():
        sm = SessionManager(test_dir)
        
        # 创建几个会话
        await sm.create_session("任务1")
        await sm.create_session("任务2")
        
        # 模拟Rust get_session_list
        index_file = sm.sessions_dir / "sessions_index.json"
        with open(index_file) as f:
            data = json.load(f)
        
        print("\n[原始sessions_index.json]:")
        print(json.dumps(data, indent=2, ensure_ascii=False)[:300])
        
        # 模拟Rust Session结构体（带serde rename）
        class Session:
            def __init__(self, session_id, info):
                # Rust: #[serde(rename = "sessionId")]
                # 这意味着序列化时key是"sessionId"
                self.sessionId = session_id
                self.title = info.get("title", "")
                self.lastActivity = info.get("last_activity", 0)
                self.createdAt = info.get("created_at", 0)
                self.status = info.get("status", "active")
            
            def to_dict(self):
                # 模拟Rust的serde序列化
                return {
                    "sessionId": self.sessionId,
                    "title": self.title,
                    "lastActivity": self.lastActivity,
                    "createdAt": self.createdAt,
                    "status": self.status
                }
        
        sessions = []
        for sid, info in data.items():
            s = Session(sid, info)
            sessions.append(s)
        
        print("\n[模拟Rust序列化后的JSON]:")
        result = [s.to_dict() for s in sessions]
        print(json.dumps(result, indent=2, ensure_ascii=False))
        
        # 模拟前端解析
        print("\n[前端解析]:")
        for s in sessions:
            # 前端: session.sessionId || session.session_id
            session_id = s.sessionId
            print(f"  解析sessionId: {session_id}")
        
        # 清理
        import shutil
        shutil.rmtree(test_dir)
    
    asyncio.run(run())


def test_session_message_loading():
    """测试会话消息加载"""
    print("\n" + "=" * 70)
    print("测试: 会话消息加载")
    print("=" * 70)
    
    test_dir = Path("/tmp/test_message_loading")
    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", "你好，我是AI")
        await sm._save_session()
        
        # 模拟Rust 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)}]")
        for msg in messages:
            print(f"  {msg['role']}: {msg['content'][:30]}...")
        
        # 模拟前端过滤system消息
        print("\n[前端过滤system消息后]:")
        for msg in messages:
            if msg["role"] != "system":
                event_type = "user" if msg["role"] == "user" else "assistant"
                print(f"  eventType: {event_type}, content: {msg['content'][:30]}...")
        
        # 清理
        import shutil
        shutil.rmtree(test_dir)
    
    asyncio.run(run())


if __name__ == "__main__":
    simulate_frontend_backend_flow()
    test_get_session_list_format()
    test_session_message_loading()
    print("\n" + "=" * 70)
    print("所有测试完成")
    print("=" * 70)