"""
Chat History API Routes
- GET /api/history/{identity_key} - Lấy lịch sử chat (có product_ids)
- DELETE /api/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 pydantic import BaseModel
from common.conversation_manager import get_conversation_manager
from common.user_identity import get_user_identity

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_key.
    
    Logic: Middleware đã parse token -> Nếu user đã login thì dùng user_id, không thì dùng device_id.
    (identity_key trong URL chỉ là fallback)
    """
    try:
        # Tự động resolve identity từ middleware
        identity = get_user_identity(request)
        resolved_key = identity.history_key  # user_id nếu login, device_id nếu không
        
        logger.info(f"GET History: URL key={identity_key} -> Resolved key={resolved_key}")
        
        manager = await get_conversation_manager()
        history = await manager.get_chat_history(resolved_key, limit=limit, before_id=before_id)

        next_cursor = None
        if history and len(history) > 0:
            next_cursor = history[-1]["id"]

        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")


@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. 
    Logic: Middleware đã parse token -> Nếu user đã login thì dùng user_id, không thì dùng device_id.
    """
    try:
        manager = await get_conversation_manager()
        await manager.clear_history(identity_key)
        logger.info(f"✅ Cleared chat history for {identity_key}")
        return {"success": True, "message": f"Đã xóa lịch sử chat của {identity_key}"}
    except Exception as e:
        logger.error(f"Error clearing chat history for {identity_key}: {e}")
        raise HTTPException(status_code=500, detail="Failed to clear chat history")

