# -*- coding: utf-8 -*-
"""
会话管理接口 —— 聊天历史查询、会话列表、删除会话
"""

from fastapi import APIRouter

from db.chat_store import get_messages, get_sessions, delete_session

router = APIRouter()


@router.get("/chat/history/{session_id}")
async def get_chat_history(session_id: str, limit: int = 100, offset: int = 0):
    """查询指定会话的聊天历史

    Args:
        session_id: 会话ID
        limit: 返回条数上限，默认100
        offset: 偏移量，默认0

    Returns:
        { "session_id": "...", "messages": [...], "total": N }
    """
    messages = get_messages(session_id, limit=limit, offset=offset)

    # 计算总数
    all_msgs = get_messages(session_id, limit=10000)
    total = len(all_msgs)

    return {
        "session_id": session_id,
        "messages": messages,
        "total": total,
    }


@router.get("/sessions")
async def list_sessions(limit: int = 20, offset: int = 0):
    """查询会话列表

    Returns:
        [{ "session_id": "...", "title": "...", "message_count": N, ... }, ...]
    """
    sessions = get_sessions(limit=limit, offset=offset)
    return {"sessions": sessions, "total": len(sessions)}


@router.delete("/sessions/{session_id}")
async def remove_session(session_id: str):
    """删除指定会话及其所有消息"""
    delete_session(session_id)
    return {"status": "ok", "message": f"会话 {session_id} 已删除"}
