#!/usr/bin/env python3
"""
测试AACode Desktop API的脚本
"""
import asyncio
import json
import sys
import os
from pathlib import Path

# 添加aacode到路径
aacode_dir = Path(__file__).parent
sys.path.insert(0, str(aacode_dir.parent))

from aacode.utils.session_manager import SessionManager


async def test_session_manager():
    """测试SessionManager的基本功能"""
    print("=" * 50)
    print("测试 SessionManager")
    print("=" * 50)
    
    # 创建测试目录
    test_dir = Path("/tmp/aacode_test")
    test_dir.mkdir(exist_ok=True)
    sessions_dir = test_dir / "sessions"
    sessions_dir.mkdir(exist_ok=True)
    
    # 创建SessionManager
    sm = SessionManager(sessions_dir)
    
    # 测试1: 创建会话
    print("\n[测试1] 创建新会话...")
    task = "测试任务：创建一个Hello World程序"
    session_id = await sm.create_session(task)
    print(f"✓ 创建会话成功: {session_id}")
    
    # 测试2: 获取会话列表
    print("\n[测试2] 获取会话列表...")
    sessions = await sm.list_sessions()
    print(f"✓ 会话数量: {len(sessions)}")
    for s in sessions:
        print(f"  - {s['session_id']}: {s['title']}")
    
    # 测试3: 保存消息
    print("\n[测试3] 保存消息...")
    sm.add_message("user", "你好")
    sm.add_message("assistant", "你好，我是AI编程助手")
    await sm.save_current_session()
    print("✓ 消息保存成功")
    
    # 测试4: 加载会话
    print("\n[测试4] 加载会话...")
    success = await sm.load_session(session_id)
    print(f"✓ 加载会话: {success}")
    print(f"  消息数量: {len(sm.current_messages)}")
    for msg in sm.current_messages:
        print(f"  - {msg.role}: {msg.content[:30]}...")
    
    # 测试5: 验证会话文件
    print("\n[测试5] 验证会话文件...")
    session_file = sessions_dir / f"{session_id}.json"
    if session_file.exists():
        with open(session_file) as f:
            data = json.load(f)
        print(f"✓ 会话文件存在: {session_file}")
        print(f"  消息数量: {len(data.get('messages', []))}")
    else:
        print(f"✗ 会话文件不存在: {session_file}")
    
    # 清理
    import shutil
    shutil.rmtree(test_dir)
    print("\n✓ 测试完成，清理测试目录")
    
    return True


def test_rust_api_simulation():
    """模拟Rust后端的会话列表API"""
    print("\n" + "=" * 50)
    print("模拟 Rust get_session_list API")
    print("=" * 50)
    
    # 查找一个实际的会话目录
    projects_dir = Path("projects")
    if not projects_dir.exists():
        print("✗ projects目录不存在")
        return False
    
    # 找到最新的有会话的项目
    for project in sorted(projects_dir.iterdir(), key=lambda p: p.stat().st_mtime, reverse=True):
        sessions_dir = project / ".aacode" / "sessions"
        if sessions_dir.exists():
            index_file = sessions_dir / "sessions_index.json"
            if index_file.exists():
                print(f"\n找到会话目录: {sessions_dir}")
                
                with open(index_file) as f:
                    data = json.load(f)
                
                print(f"会话数量: {len(data)}")
                
                # 模拟Rust的Session结构
                class Session:
                    def __init__(self, session_id, info):
                        self.session_id = session_id  # Rust字段名
                        # serde rename = "sessionId" 意味着序列化后是sessionId
                        self.sessionId = session_id  # 前端期望的字段
                        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")
                
                sessions = []
                for session_id, info in data.items():
                    s = Session(session_id, info)
                    sessions.append(s)
                    print(f"  - sessionId: {s.sessionId}, title: {s.title}")
                
                # 测试获取会话消息
                if sessions:
                    session_file = sessions_dir / f"{sessions[0].sessionId}.json"
                    if session_file.exists():
                        with open(session_file) as f:
                            session_data = json.load(f)
                        messages = session_data.get("messages", [])
                        print(f"\n会话消息数量: {len(messages)}")
                        for msg in messages[:3]:
                            print(f"  - {msg.get('role')}: {msg.get('content', '')[:50]}...")
                
                return True
    
    print("✗ 未找到会话目录")
    return False


if __name__ == "__main__":
    asyncio.run(test_session_manager())
    test_rust_api_simulation()