"""
Chat History API Routes
- GET /api/history/{identity_key} - Lấy lịch sử chat
- 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 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/history/{identity_key}", summary="Get Chat History", 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):
    """
    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:
        user_id = getattr(request.state, "user_id", None)
        device_id = getattr(request.state, "device_id", identity_key)
        is_authenticated = getattr(request.state, "is_authenticated", False)

        logger.info(f"GET History: auth={is_authenticated} | user_id={user_id} | device_id={device_id}")

        identity_key = user_id if is_authenticated else device_id
        logger.info(f"GET History: resolved_key={identity_key}")

        manager = await get_conversation_manager()
        history = await manager.get_chat_history(identity_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(f"Error fetching chat history: {e}")
        raise HTTPException(status_code=500, detail="Failed to fetch chat history") from e


@router.delete("/api/history/{identity_key}", summary="Clear Chat History", response_model=ClearHistoryResponse)
@rate_limit_service.limiter.limit("30/minute")
async def clear_chat_history(request: Request, 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") from e


class ArchiveResponse(BaseModel):
    status: str
    success: bool
    message: str
    new_key: str


@router.post("/api/history/archive", summary="Archive Chat History", response_model=ArchiveResponse)
@rate_limit_service.limiter.limit("30/minute")
async def archive_chat_history(request: Request):
    """
    Lưu trữ lịch sử chat hiện tại (đổi tên key) và reset chat mới.
    Giới hạn 5 lần/ngày.
    """
    try:
        # Resolve identity từ middleware (request.state)
        user_id = getattr(request.state, "user_id", None)
        device_id = getattr(request.state, "device_id", "")
        is_authenticated = getattr(request.state, "is_authenticated", False)

        # Chỉ dành cho User đã đăng nhập
        if not is_authenticated:
            return JSONResponse(
                status_code=401,
                content={
                    "status": "error",
                    "error_code": "LOGIN_REQUIRED",
                    "message": "Tính năng chỉ dành cho thành viên đã đăng nhập.",
                    "require_login": True,
                },
            )

        identity_key = user_id

        # Check reset limit
        can_reset, usage, remaining = await reset_limit_service.check_limit(identity_key)
        if not can_reset:
            return JSONResponse(
                status_code=429,
                content={
                    "status": "error",
                    "error_code": "RESET_LIMIT_EXCEEDED",
                    "message": f"Bạn đã hết lượt tạo đoạn chat mới hôm nay ({reset_limit_service.limit}/{reset_limit_service.limit}).",
                },
            )

        manager = await get_conversation_manager()
        new_key = await manager.archive_history(identity_key)

        # Clear user_insight in Redis for this identity key
        client = redis_cache.get_client()
        if client:
            insight_key = f"identity_key_insight:{identity_key}"
            await client.delete(insight_key)
            logger.info(f"🧹 Cleared user_insight for {identity_key}")

        # Increment usage
        await reset_limit_service.increment(identity_key)

        return {"status": "success", "success": True, "message": "History archived successfully", "new_key": new_key}
    except Exception as e:
        logger.error(f"Error archiving history: {e}")
        return JSONResponse(
            status_code=500,
            content={"status": "error", "error_code": "SYSTEM_ERROR", "message": "Failed to archive history"},
        )
