#!/usr/bin/env python3
"""
完整的端到端测试 - 模拟Tauri Desktop的完整流程
"""
import json
import asyncio
from pathlib import Path
import sys

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

from aacode.utils.session_manager import SessionManager
from aacode.core.main_agent import MainAgent
from aacode.utils.context_manager import ContextManager
from aacode.utils.safety import SafetyGuard
from aacode.config import settings


async def test_full_flow():
    """测试完整的会话流程"""
    print("=" * 60)
    print("完整流程测试：创建会话 -> 执行任务 -> 保存 -> 加载")
    print("=" * 60)
    
    # 创建测试目录
    test_dir = Path("/tmp/aacode_full_test")
    test_dir.mkdir(exist_ok=True)
    
    # 1. 创建SessionManager并创建会话
    print("\n[步骤1] 创建会话...")
    sm = SessionManager(test_dir)
    task = "创建一个简单的Hello World程序"
    session_id = await sm.create_session(task)
    print(f"✓ 会话创建成功: {session_id}")
    
    # 2. 验证会话文件
    print("\n[步骤2] 验证会话文件...")
    session_file = sm.sessions_dir / f"{session_id}.json"
    with open(session_file) as f:
        data = json.load(f)
    print(f"✓ 会话文件存在: {len(data.get('messages', []))} 条消息")
    
    # 3. 模拟Rust get_session_list返回
    print("\n[步骤3] 模拟Rust get_session_list...")
    index_file = sm.sessions_dir / "sessions_index.json"
    with open(index_file) as f:
        index_data = json.load(f)
    
    # 模拟Rust的Session结构（关键：sessionId字段）
    sessions = []
    for sid, info in index_data.items():
        sessions.append({
            "sessionId": sid,  # 前端期望的字段
            "session_id": sid,  # Rust字段名
            "title": info.get("title", ""),
            "lastActivity": info.get("last_activity", 0),
            "createdAt": info.get("created_at", 0),
            "status": info.get("status", "active")
        })
    print(f"✓ 返回 {len(sessions)} 个会话")
    for s in sessions:
        print(f"  - sessionId: {s['sessionId']}, title: {s['title']}")
    
    # 4. 模拟Rust get_session_messages返回
    print("\n[步骤4] 模拟Rust get_session_messages...")
    with open(session_file) as f:
        session_data = json.load(f)
    messages = session_data.get("messages", [])
    print(f"✓ 返回 {len(messages)} 条消息")
    for msg in messages:
        print(f"  - {msg['role']}: {msg['content'][:50]}...")
    
    # 5. 验证前端能否正确解析
    print("\n[步骤5] 验证前端解析...")
    # 模拟前端selectSession逻辑
    for session in sessions:
        sessionId = session.get("sessionId") or session.get("session_id")
        print(f"  前端解析sessionId: {sessionId}")
    
    # 模拟前端加载消息
    for msg in messages:
        if msg["role"] != "system":
            eventType = "user" if msg["role"] == "user" else "assistant"
            content = msg["content"]
            print(f"  前端事件: {eventType} - {content[:30]}...")
    
    # 清理
    import shutil
    shutil.rmtree(test_dir)
    print("\n✓ 测试完成")


async def test_error_handling():
    """测试错误处理"""
    print("\n" + "=" * 60)
    print("测试：错误处理")
    print("=" * 60)
    
    # 测试1: 不存在的会话
    print("\n[测试1] 加载不存在的会话...")
    test_dir = Path("/tmp/aacode_error_test")
    test_dir.mkdir(exist_ok=True)
    
    sm = SessionManager(test_dir)
    success = await sm.load_session("nonexistent_session")
    print(f"  结果: {success} (应该是False)")
    
    # 测试2: 空任务
    print("\n[测试2] 空任务...")
    session_id = await sm.create_session("")
    print(f"  会话ID: {session_id}")
    print(f"  标题: {sm.sessions_index[session_id].title}")
    
    # 清理
    import shutil
    shutil.rmtree(test_dir)
    print("\n✓ 错误处理测试完成")


if __name__ == "__main__":
    asyncio.run(test_full_flow())
    asyncio.run(test_error_handling())