"""
User Insight API Routes
- POST /api/insight/reset - Xóa user_insight trong Redis (khi tạo phiên chat mới)
"""

import logging

from fastapi import APIRouter, Request
from pydantic import BaseModel

from common.cache import redis_cache

router = APIRouter(prefix="/api/insight", tags=["User Insight"])
logger = logging.getLogger(__name__)


class ResetInsightResponse(BaseModel):
    status: str
    message: str


@router.post("/reset", summary="Reset User Insight", response_model=ResetInsightResponse)
async def reset_user_insight(request: Request):
    """
    Xóa user_insight khỏi Redis khi user bấm "New Chat".
    Hoạt động cho cả Guest (device_id) và User đã login (user_id).
    """
    try:
        user_id = getattr(request.state, "user_id", None)
        device_id = getattr(request.state, "device_id", None) or request.headers.get("device_id")
        is_authenticated = getattr(request.state, "is_authenticated", False)

        identity_key = user_id if is_authenticated else device_id

        if not identity_key:
            return {"status": "error", "message": "Missing identity_key (device_id or user_id)"}

        client = redis_cache.get_client()
        if client:
            insight_key = f"identity_key_insight:{identity_key}"
            deleted = await client.delete(insight_key)
            logger.info(f"🧹 Reset user_insight for {identity_key} | deleted={deleted}")
            return {"status": "success", "message": f"User insight cleared for {identity_key}"}

        return {"status": "error", "message": "Redis not available"}
    except Exception as e:
        logger.error(f"❌ Error resetting user insight: {e}")
        return {"status": "error", "message": str(e)}
