"""
Chat History API Routes (Chatbot)
---------------------------------
- `GET /api/history/{identity_key}`  - Lấy lịch sử chat (có cursor để load-more)
- `DELETE /api/history/{identity_key}` - Xóa lịch sử chat

`identity_key` trong URL chỉ là placeholder, backend luôn dùng
`identity.history_key` từ middleware (user_id nếu login, device_id nếu guest).
"""

import logging
from typing import Any

from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel

from common.conversation_manager import get_conversation_manager

router = APIRouter(tags=["Chat History"])
logger = logging.getLogger(__name__)


class ChatHistoryResponse(BaseModel):
  data: list[dict[str, Any]]
  next_cursor: int | None = None


class ClearHistoryResponse(BaseModel):
  success: bool
  message: str


@router.get("/api/history/{identity_key}", summary="Get Chat History", response_model=ChatHistoryResponse)
async def get_chat_history(request: Request, identity_key: str, limit: int | None = 50, before_id: int | None = None):
  """
  Lấy lịch sử chat theo identity (user hoặc guest) với cursor `before_id` để load-more.
  """
  try:
    # Dùng thông tin từ middleware: user_id / device_id
    user_id = getattr(request.state, "user_id", None)
    device_id = getattr(request.state, "device_id", "") or ""
    is_authenticated = bool(getattr(request.state, "is_authenticated", False))

    if is_authenticated and user_id:
      resolved_key = str(user_id)
    else:
      resolved_key = device_id or "anonymous"

    logger.info("GET History: URL key=%s -> Resolved key=%s", identity_key, resolved_key)

    manager = await get_conversation_manager()
    history = await manager.get_chat_history(resolved_key, limit=limit, before_id=before_id)

    next_cursor = history[-1]["id"] if history else None

    return {"data": history, "next_cursor": next_cursor}
  except Exception as e:
    logger.error("Error fetching chat history: %s", e, exc_info=True)
    raise HTTPException(status_code=500, detail="Failed to fetch chat history")


@router.delete("/api/history/{identity_key}", summary="Clear Chat History", response_model=ClearHistoryResponse)
async def clear_chat_history(identity_key: str):
  """
  Xóa toàn bộ lịch sử chat theo identity_key (user_id hoặc device_id).
  """
  try:
    manager = await get_conversation_manager()
    await manager.clear_history(identity_key)
    logger.info("✅ Cleared chat history for %s", identity_key)
    return {"success": True, "message": f"Đã xóa lịch sử chat của {identity_key}"}
  except Exception as e:
    logger.error("Error clearing chat history for %s: %s", identity_key, e, exc_info=True)
    raise HTTPException(status_code=500, detail="Failed to clear chat history")


