#!/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
from aacode.config import settings


def test_rust_backend_logic():
    """测试Rust后端的逻辑（用Python模拟）"""
    print("=" * 70)
    print("测试1: 模拟Rust后端的get_session_list")
    print("=" * 70)
    
    # 创建测试数据
    test_dir = Path("/tmp/tauri_test_1")
    test_dir.mkdir(exist_ok=True)
    
    async def run():
        sm = SessionManager(test_dir)
        
        # 创建3个会话
        for i in range(3):
            await sm.create_session(f"测试任务{i}")
            await sm._save_session()
        
        # 模拟Rust读取sessions_index.json
        index_file = sm.sessions_dir / "sessions_index.json"
        with open(index_file) as f:
            data = json.load(f)
        
        print(f"\n[原始sessions_index.json]:")
        print(json.dumps(data, indent=2, ensure_ascii=False)[:500])
        
        # 模拟Rust的Session结构体
        class Session:
            pass
        
        sessions = []
        for session_id, info in data.items():
            s = Session()
            # Rust结构体: session_id: String, 但serde rename = "sessionId"
            # 这意味着序列化后的JSON key是"sessionId"
            s.session_id = session_id
            # 这里的问题是：Python直接序列化时不会自动添加sessionId
            # 需要手动处理
            sessions.append(s)
        
        print(f"\n[Python对象直接序列化]:")
        for s in sessions:
            print(f"  session_id = {s.session_id}")
            # 模拟json.dumps
            d = {"session_id": s.session_id}
            print(f"    JSON: {json.dumps(d)}")
        
        # 正确的做法：手动添加sessionId
        print(f"\n[正确的做法：手动添加sessionId]:")
        sessions_with_sessionId = []
        for session_id, info in data.items():
            sessions_with_sessionId.append({
                "sessionId": session_id,  # 前端期望的
                "session_id": session_id,  # Rust字段
                "title": info.get("title", ""),
                "lastActivity": info.get("last_activity", 0),
                "createdAt": info.get("created_at", 0),
                "status": info.get("status", "active")
            })
        
        for s in sessions_with_sessionId:
            print(f"  sessionId = {s['sessionId']}, title = {s['title']}")
        
        # 清理
        import shutil
        shutil.rmtree(test_dir)
    
    asyncio.run(run())


def test_frontend_session_parsing():
    """测试前端解析会话的逻辑"""
    print("\n" + "=" * 70)
    print("测试2: 模拟前端解析会话")
    print("=" * 70)
    
    # 模拟后端返回的会话数据
    backend_sessions = [
        {
            "sessionId": "session_20260412_091000_0",  # Rust serde rename
            "title": "测试任务0",
            "lastActivity": 1234567890.0,
            "createdAt": 1234567890.0,
            "status": "active"
        },
        {
            "sessionId": "session_20260412_091001_1",
            "title": "测试任务1", 
            "lastActivity": 1234567891.0,
            "createdAt": 1234567891.0,
            "status": "active"
        }
    ]
    
    print("\n[后端返回的数据]:")
    for s in backend_sessions:
        print(f"  {json.dumps(s)}")
    
    print("\n[前端解析逻辑]:")
    for session in backend_sessions:
        # 前端代码: session.sessionId || session.session_id || session.sessionID
        sessionId = session.get("sessionId") or session.get("session_id") or session.get("sessionID")
        print(f"  解析结果: sessionId = {sessionId}")
        
        # 前端模板: :key="session.sessionId"
        # 这应该能正常工作，因为sessionId存在


def test_get_session_messages():
    """测试获取会话消息"""
    print("\n" + "=" * 70)
    print("测试3: 模拟get_session_messages")
    print("=" * 70)
    
    test_dir = Path("/tmp/tauri_test_3")
    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读取会话文件
        session_file = sm.sessions_dir / f"{session_id}.json"
        with open(session_file) as f:
            data = json.load(f)
        
        print(f"\n[会话文件内容]:")
        print(json.dumps(data, indent=2, ensure_ascii=False)[:500])
        
        # 模拟Rust返回messages数组
        messages = data.get("messages", [])
        print(f"\n[后端返回的messages数组]:")
        for msg in messages:
            print(f"  role: {msg['role']}, content: {msg['content'][:30]}...")
        
        # 前端解析
        print(f"\n[前端解析]:")
        for msg in messages:
            if msg["role"] != "system":
                eventType = "user" if msg["role"] == "user" else "assistant"
                content = msg["content"]
                print(f"  eventType: {eventType}, content: {content[:30]}...")
        
        # 清理
        import shutil
        shutil.rmtree(test_dir)
    
    asyncio.run(run())


def test_create_session_flow():
    """测试创建会话流程"""
    print("\n" + "=" * 70)
    print("测试4: 创建会话流程")
    print("=" * 70)
    
    test_dir = Path("/tmp/tauri_test_4")
    test_dir.mkdir(exist_ok=True)
    
    async def run():
        sm = SessionManager(test_dir)
        
        # 场景1: 用户点击New Session（不发送任务）
        print("\n[场景1: 点击New Session按钮]")
        print("  前端: 清空currentSession, 刷新会话列表")
        print("  后端: 无API调用（这是问题所在！）")
        print("  结果: 会话列表不会增加新会话")
        
        # 场景2: 用户输入任务并发送
        print("\n[场景2: 用户发送任务]")
        task = "创建一个Hello World程序"
        
        # 检查当前会话状态
        print(f"  当前会话: {sm.current_session_id}")
        
        # 模拟run_task中的逻辑
        if not sm.current_session_id:
            print("  前端: 没有会话，调用run_task")
            session_id = await sm.create_session(task)
            print(f"  后端: 创建会话 {session_id}")
            print(f"  前端: 收到session_created事件，更新currentSession")
        
        # 验证
        index_file = sm.sessions_dir / "sessions_index.json"
        with open(index_file) as f:
            data = json.load(f)
        print(f"\n[验证: 会话索引中有{len(data)}个会话]")
        
        # 清理
        import shutil
        shutil.rmtree(test_dir)
    
    asyncio.run(run())


def test_error_scenario():
    """测试错误场景"""
    print("\n" + "=" * 70)
    print("测试5: 错误场景")
    print("=" * 70)
    
    # 场景1: 项目路径不存在
    print("\n[场景1: 项目路径不存在]")
    fake_path = Path("/nonexistent/path")
    print(f"  路径: {fake_path}")
    print(f"  存在: {fake_path.exists()}")
    print(f"  Rust会返回空数组")
    
    # 场景2: 会话文件不存在
    print("\n[场景2: 会话文件不存在]")
    print(f"  Rust会返回空数组")
    
    # 场景3: JSON解析错误
    print("\n[场景3: JSON解析错误]")
    print(f"  Rust会返回错误")


def analyze_frontend_code():
    """分析前端代码问题"""
    print("\n" + "=" * 70)
    print("分析: 前端代码问题")
    print("=" * 70)
    
    # 读取main.js
    main_js = Path(__file__).parent / "desktop" / "src" / "main.js"
    with open(main_js) as f:
        content = f.read()
    
    # 查找关键函数
    print("\n[createNewSession函数]:")
    import re
    match = re.search(r'async function createNewSession\(\).*?^\s*}', content, re.MULTILINE | re.DOTALL)
    if match:
        print(match.group(0)[:300])
    
    print("\n[sendMessage函数]:")
    match = re.search(r'async function sendMessage\(\).*?^\s*}', content, re.MULTILINE | re.DOTALL)
    if match:
        print(match.group(0)[:500])
    
    print("\n[selectSession函数]:")
    match = re.search(r'async function selectSession\(session\).*?^\s*}', content, re.MULTILINE | re.DOTALL)
    if match:
        print(match.group(0)[:500])


def analyze_backend_code():
    """分析后端代码问题"""
    print("\n" + "=" * 70)
    print("分析: 后端代码问题")
    print("=" * 70)
    
    # 读取commands.rs
    commands_rs = Path(__file__).parent / "desktop" / "src-tauri" / "src" / "commands.rs"
    with open(commands_rs) as f:
        content = f.read()
    
    # 查找关键函数
    import re
    
    print("\n[get_session_list函数]:")
    match = re.search(r'pub async fn get_session_list.*?^}', content, re.MULTILINE | re.DOTALL)
    if match:
        print(match.group(0)[:600])
    
    print("\n[get_session_messages函数]:")
    match = re.search(r'pub async fn get_session_messages.*?^}', content, re.MULTILINE | re.DOTALL)
    if match:
        print(match.group(0)[:400])


if __name__ == "__main__":
    test_rust_backend_logic()
    test_frontend_session_parsing()
    test_get_session_messages()
    test_create_session_flow()
    test_error_scenario()
    analyze_frontend_code()
    analyze_backend_code()
    print("\n" + "=" * 70)
    print("测试完成")
    print("=" * 70)