#!/usr/bin/env python3
"""
直接测试Rust后端API的模拟 - 验证会话数据格式
"""
import json
from pathlib import Path


def test_session_data_format():
    """测试会话数据格式是否正确"""
    print("=" * 60)
    print("测试: 验证Rust后端读取会话数据的格式")
    print("=" * 60)
    
    # 查找一个实际的会话目录
    projects_dir = Path("projects")
    if not projects_dir.exists():
        print("✗ projects目录不存在")
        return
    
    # 找到最新的有会话的项目
    found_session = 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找到项目: {project.name}")
                print(f"会话目录: {sessions_dir}")
                
                # 读取sessions_index.json
                with open(index_file) as f:
                    data = json.load(f)
                
                print(f"\n[1] sessions_index.json 内容:")
                print(json.dumps(data, indent=2, ensure_ascii=False)[:500])
                
                # 模拟Rust的get_session_list
                print("\n[2] 模拟Rust get_session_list返回:")
                
                class Session:
                    pass
                
                sessions = []
                for session_id, info in data.items():
                    s = Session()
                    s.session_id = session_id  # Rust字段名
                    # serde rename = "sessionId" 意味着序列化后是sessionId
                    # 但Python对象没有serde，所以我们需要手动添加sessionId
                    s.sessionId = session_id   # 前端期望的字段
                    s.title = info.get("title", "")
                    s.createdAt = info.get("created_at", 0)
                    s.lastActivity = info.get("last_activity", 0)
                    s.status = info.get("status", "active")
                    sessions.append(s)
                    print(f"  Session:")
                    print(f"    session_id = {s.session_id}")
                    print(f"    sessionId = {s.sessionId}")  
                    print(f"    title = {s.title}")
                
                # 测试获取会话消息
                if sessions:
                    session_id = sessions[0].sessionId
                    session_file = sessions_dir / f"{session_id}.json"
                    print(f"\n[3] 读取会话文件: {session_file.name}")
                    
                    if session_file.exists():
                        with open(session_file) as f:
                            session_data = json.load(f)
                        
                        print(f"  messages数组存在: {'messages' in session_data}")
                        messages = session_data.get("messages", [])
                        print(f"  消息数量: {len(messages)}")
                        
                        if messages:
                            print(f"\n[4] 第一条消息:")
                            msg = messages[0]
                            print(f"  role: {msg.get('role')}")
                            print(f"  content: {msg.get('content', '')[:100]}...")
                    else:
                        print(f"  ✗ 会话文件不存在!")
                
                found_session = True
                break
    
    if not found_session:
        print("✗ 未找到任何会话数据")


def test_create_session_via_cli():
    """测试通过CLI创建会话"""
    print("\n" + "=" * 60)
    print("测试: 通过Python直接调用SessionManager创建会话")
    print("=" * 60)
    
    import sys
    sys.path.insert(0, str(Path(__file__).parent.parent))
    
    import asyncio
    from aacode.utils.session_manager import SessionManager
    
    # 创建测试目录 - SessionManager会自动添加.aacode/sessions
    test_dir = Path("/tmp/aacode_rust_test")
    test_dir.mkdir(exist_ok=True)
    
    async def test():
        # 传入项目目录，SessionManager会自动添加.aacode/sessions
        sm = SessionManager(test_dir)
        sessions_dir = sm.sessions_dir  # 获取实际的sessions目录
        
        # 创建会话
        session_id = await sm.create_session("测试任务")
        print(f"✓ 创建会话: {session_id}")
        
        # 添加消息
        await sm.add_message("user", "你好")
        await sm.add_message("assistant", "你好，我是AI")
        
        # 保存 - 注意_save_session是async，需要await
        print(f"  current_session_id: {sm.current_session_id}")
        print(f"  sessions_dir: {sm.sessions_dir}")
        await sm._save_session()
        # 索引已经在create_session时保存了，但再保存一次确保
        sm._save_sessions_index()
        
        # 列出目录内容
        print(f"  目录内容: {list(sessions_dir.iterdir())}")
        
        # 验证文件 - 使用正确的路径
        session_file = sessions_dir / f"{session_id}.json"
        print(f"✓ 会话文件: {session_file}")
        
        with open(session_file) as f:
            data = json.load(f)
        print(f"✓ 消息数量: {len(data.get('messages', []))}")
        
        # 验证索引文件
        index_file = sessions_dir / "sessions_index.json"
        with open(index_file) as f:
            index_data = json.load(f)
        print(f"✓ 索引中的会话数: {len(index_data)}")
        
        return session_id, test_dir
    
    session_id, _ = asyncio.run(test())
    
    # 现在模拟Rust后端读取
    print("\n[模拟Rust get_session_list]:")
    sessions_dir = test_dir / ".aacode" / "sessions"
    index_file = sessions_dir / "sessions_index.json"
    with open(index_file) as f:
        data = json.load(f)
    
    for sid, info in data.items():
        print(f"  sessionId: {sid}")
        print(f"  title: {info.get('title')}")
        print(f"  lastActivity: {info.get('last_activity')}")
    
    print("\n[模拟Rust get_session_messages]:")
    session_file = test_dir / ".aacode" / "sessions" / f"{session_id}.json"
    with open(session_file) as f:
        session_data = json.load(f)
    
    messages = session_data.get("messages", [])
    for msg in messages:
        print(f"  {msg.get('role')}: {msg.get('content')[:50]}...")
    
    # 清理
    import shutil
    shutil.rmtree(test_dir)
    print("\n✓ 测试完成")


if __name__ == "__main__":
    test_session_data_format()
    test_create_session_via_cli()