"""
AI 对话历史服务 — 持久化 + 查询
"""
from __future__ import annotations

import uuid
from sqlalchemy import select, desc
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.ai import AiChatSession


async def save_message(
    db: AsyncSession,
    user_id: uuid.UUID,
    role: str,
    content: str,
    msg_type: str = "text",
) -> AiChatSession:
    """保存一条对话消息"""
    msg = AiChatSession(
        user_id=user_id,
        role=role,
        content=content,
        msg_type=msg_type,
    )
    db.add(msg)
    await db.commit()
    await db.refresh(msg)
    return msg


async def load_history(
    db: AsyncSession,
    user_id: uuid.UUID,
    limit: int = 50,
) -> list[dict]:
    """加载用户最近 N 条对话（时间正序返回，方便前端渲染）"""
    stmt = (
        select(AiChatSession)
        .where(AiChatSession.user_id == user_id)
        .order_by(desc(AiChatSession.created_at))
        .limit(limit)
    )
    result = await db.execute(stmt)
    rows = result.scalars().all()
    # 反转为时间正序
    rows = list(reversed(rows))
    return [
        {
            "id": str(r.id),
            "role": r.role,
            "content": r.content,
            "type": r.msg_type,
            "created_at": r.created_at.isoformat() if r.created_at else None,
        }
        for r in rows
    ]
