#!/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_all_fixes():
    """测试所有修复"""
    print("=" * 70)
    print("全面测试：验证所有修复")
    print("=" * 70)
    
    test_dir = Path("/tmp/test_all_fixes")
    test_dir.mkdir(exist_ok=True)
    
    async def run():
        # ========== 修复1: New Session按钮创建会话 ==========
        print("\n[修复1] New Session按钮创建会话")
        print("-" * 50)
        
        sm = SessionManager(test_dir)
        
        # 模拟前端调用create_session API
        session = await sm.create_session("新会话")
        print(f"  创建会话: {session}")
        
        # 验证返回的数据格式
        session_data = {
            "sessionId": session,
            "title": sm.sessions_index[session].title,
            "createdAt": sm.sessions_index[session].created_at,
            "lastActivity": sm.sessions_index[session].last_activity,
            "status": sm.sessions_index[session].status
        }
        print(f"  返回数据: {json.dumps(session_data)}")
        
        # 验证前端能正确解析
        current_session = session_data
        session_id = current_session.get("sessionId")
        print(f"  前端解析sessionId: {session_id}")
        
        if session_id:
            print("  ✓ 修复1成功")
        else:
            print("  ✗ 修复1失败")
        
        # ========== 修复2: sendMessage不重复创建会话 ==========
        print("\n[修复2] sendMessage不重复创建会话")
        print("-" * 50)
        
        # 模拟用户发送任务
        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}")
        
        # 模拟后端处理
        if session_id_for_task:
            success = await sm.switch_session(session_id_for_task)
            print(f"  后端switch_session: {success}")
        
        # 验证没有创建新会话
        session_count = len(sm.sessions_index)
        print(f"  会话总数: {session_count}")
        
        if session_count == 1:
            print("  ✓ 修复2成功：没有重复创建会话")
        else:
            print(f"  ✗ 修复2失败：创建了{session_count}个会话")
        
        # ========== 修复3: 会话历史加载 ==========
        print("\n[修复3] 会话历史加载")
        print("-" * 50)
        
        # 添加一些消息
        await sm.add_message("user", "你好")
        await sm.add_message("assistant", "你好，我是AI")
        await sm._save_session()
        
        # 模拟后端get_session_messages
        session_file = sm.sessions_dir / f"{session}.json"
        with open(session_file) as f:
            data = json.load(f)
        
        messages = data.get("messages", [])
        print(f"  消息总数: {len(messages)}")
        
        # 模拟前端过滤system消息
        filtered = [m for m in messages if m["role"] != "system"]
        print(f"  过滤后消息: {len(filtered)}")
        
        for msg in filtered:
            print(f"    {msg['role']}: {msg['content'][:20]}...")
        
        if len(filtered) > 0:
            print("  ✓ 修复3成功")
        else:
            print("  ✗ 修复3失败")
        
        # ========== 修复4: get_session_list返回正确格式 ==========
        print("\n[修复4] get_session_list返回正确格式")
        print("-" * 50)
        
        # 模拟Rust get_session_list
        index_file = sm.sessions_dir / "sessions_index.json"
        with open(index_file) as f:
            data = json.load(f)
        
        # 模拟Rust Session结构体序列化
        class Session:
            def __init__(self, sid, info):
                self.session_id = sid  # Rust字段
                # serde rename = "sessionId" 会让这个字段在JSON中变成sessionId
                self.sessionId = sid   # 序列化后的key
                self.title = info.get("title", "")
                self.createdAt = info.get("created_at", 0)
                self.lastActivity = info.get("last_activity", 0)
                self.status = info.get("status", "active")
            
            def to_json(self):
                return {
                    "sessionId": self.sessionId,
                    "title": self.title,
                    "createdAt": self.createdAt,
                    "lastActivity": self.lastActivity,
                    "status": self.status
                }
        
        sessions = [Session(sid, info) for sid, info in data.items()]
        result = [s.to_json() for s in sessions]
        
        print(f"  返回{len(result)}个会话")
        for s in result:
            print(f"    sessionId: {s['sessionId']}, title: {s['title']}")
        
        # 验证前端能解析
        for s in result:
            parsed_id = s.get("sessionId")
            if parsed_id:
                print(f"  ✓ 修复4成功：前端能解析sessionId")
                break
        
        # 清理
        import shutil
        shutil.rmtree(test_dir)
        
        print("\n" + "=" * 70)
        print("所有测试完成")
        print("=" * 70)
    
    asyncio.run(run())


if __name__ == "__main__":
    test_all_fixes()