"""
Chat History API Routes (Check/Debug)
- GET /api/check-history/{identity_key} - Lấy lịch sử chat (có phân trang, không giới hạn thời gian)
- DELETE /api/check-history/{identity_key} - Xóa lịch sử chat

Note: identity_key có thể là device_id (guest) hoặc user_id (đã login)
"""

import logging
from typing import Any

from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel

from common.cache import redis_cache
from common.conversation_manager import get_conversation_manager
from common.rate_limit import rate_limit_service
from common.reset_limit import reset_limit_service

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/check-history/{identity_key}", summary="Get Chat History (Check)", response_model=ChatHistoryResponse)
@rate_limit_service.limiter.limit("30/minute")
async def get_chat_history(
    request: Request,
    identity_key: str,
    limit: int | None = 50,
    before_id: int | None = None,
    date_from: str | None = None,
    date_to: str | None = None,
):
    """
    Lấy lịch sử chat theo identity_key (có phân trang).
    
    - date_from: YYYY-MM-DD (inclusive)
    - date_to: YYYY-MM-DD (inclusive)
    """
    try:
        if not identity_key or identity_key.strip() == "":
            raise HTTPException(status_code=400, detail="identity_key không được rỗng")

        logger.info(f"GET History: identity={identity_key} | limit={limit} | date={date_from}~{date_to}")

        manager = await get_conversation_manager()
        history = await manager.get_chat_history(
            identity_key,
            limit=limit,
            before_id=before_id,
            skip_date_filter=True,
            date_from=date_from,
            date_to=date_to,
        )
        next_cursor = history[-1]["id"] if history else None

        logger.info(f"✅ Fetched {len(history)} messages for {identity_key}")
        return {"data": history, "next_cursor": next_cursor}
    except Exception as e:
        logger.error(f"Error fetching chat history: {e}")
        raise HTTPException(status_code=500, detail="Failed to fetch chat history") from e

