"""
Fashion Q&A Agent Router
FastAPI endpoints cho Fashion Q&A Agent service.
Router chỉ chứa định nghĩa API, logic nằm ở controller.

Note: Rate limit check đã được xử lý trong middleware (CanifaAuthMiddleware)
"""

import logging

from fastapi import APIRouter, BackgroundTasks, Request
from fastapi.responses import JSONResponse

from agent.controller import chat_controller
from agent.models import QueryRequest
from common.cache import redis_cache
from common.message_limit import message_limit_service
from common.rate_limit import rate_limit_service
from config import DEFAULT_MODEL

logger = logging.getLogger(__name__)
router = APIRouter()


@router.post("/api/agent/chat", summary="Fashion Q&A Chat (Non-streaming)")
@rate_limit_service.limiter.limit("20/minute")
async def fashion_qa_chat(request: Request, req: QueryRequest, background_tasks: BackgroundTasks):
    """
    Endpoint chat không stream - trả về response JSON đầy đủ một lần.

    Note: Rate limit đã được check trong middleware.
    """
    user_id = getattr(request.state, "user_id", None)
    device_id = getattr(request.state, "device_id", "unknown")
    is_authenticated = getattr(request.state, "is_authenticated", False)

    identity_id = user_id if is_authenticated else device_id
    logger.info(f"📥 [Incoming Query - NonStream] User: {identity_id} | Query: {req.user_query}")

    try:
        # Call controller để xử lý chat
        result = await chat_controller(
            query=req.user_query,
            background_tasks=background_tasks,
            model_name=DEFAULT_MODEL,
            images=req.images,
            identity_key=str(identity_id),  # Key lưu history
            is_authenticated=is_authenticated,  # Pass auth status for Langfuse metadata
            device_id=device_id,  # Luôn truyền device_id để lưu vào Langfuse metadata
        )

        logger.info(f"💬 AI Response: {result['ai_response']}")
        logger.info(f"🛍️ Product IDs: {result.get('product_ids', [])}")

        # Increment message count SAU KHI chat thành công
        usage_info = await message_limit_service.increment(
            identity_key=identity_id,
            is_authenticated=is_authenticated,
        )

        return {
            "status": "success",
            "ai_response": result["ai_response"],
            "product_ids": result.get("product_ids", []),
            "question_recommend": result.get("question_recommend", []),
            "trace_id": result.get("trace_id", ""),
            "limit_info": {
                "limit": usage_info["limit"],
                "used": usage_info["used"],
                "remaining": usage_info["remaining"],
                "reset_seconds": usage_info.get("reset_seconds"),
            },
        }
    except Exception as e:
        logger.error(f"Error in fashion_qa_chat: {e}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={
                "status": "error",
                "error_code": "SYSTEM_ERROR",
                "message": "Oops 😥 Hiện Canifa-AI chưa thể xử lý yêu cầu của bạn ngay lúc này, vui lòng quay lại trong giây lát.",
            },
        )


@router.post("/api/agent/chat-dev", summary="Fashion Q&A Chat (Dev - includes user_insight)")
async def fashion_qa_chat_dev(request: Request, req: QueryRequest, background_tasks: BackgroundTasks):
    """
    Endpoint chat dành cho DEV - không rate limit, không cache, không message limit.
    """
    user_id = getattr(request.state, "user_id", None)
    device_id = getattr(request.state, "device_id", "unknown")
    is_authenticated = getattr(request.state, "is_authenticated", False)
    identity_id = user_id if is_authenticated else device_id

    logger.info(f"📥 [Incoming Query - Dev] User: {identity_id} | Query: {req.user_query}")

    # Clear stale user_insight from Redis so polling only finds NEW data
    try:
        client = redis_cache.get_client()
        if client:
            await client.delete(f"identity_key_insight:{identity_id}")
    except Exception:
        pass  # Non-critical, continue with chat

    try:
        # DEV MODE: Return ai_response + products immediately
        result = await chat_controller(
            query=req.user_query,
            background_tasks=background_tasks,
            model_name=DEFAULT_MODEL,
            images=req.images,
            identity_key=str(identity_id),
            return_user_insight=False,
            is_authenticated=is_authenticated,
            device_id=device_id,
            skip_cache=True,
        )

        return {
            "status": "success",
            "ai_response": result["ai_response"],
            "product_ids": result.get("product_ids", []),
            "question_recommend": result.get("question_recommend", []),
            "trace_id": result.get("trace_id", ""),
            "insight_status": "success" if result.get("user_insight") else "pending",
            "user_insight": result.get("user_insight"),
        }
    except Exception as e:
        logger.error(f"Error in fashion_qa_chat_dev: {e}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={
                "status": "error",
                "error_code": "SYSTEM_ERROR",
                "message": "Oops 😥 Hiện Canifa-AI chưa thể xử lý yêu cầu của bạn ngay lúc này, vui lòng quay lại trong giây lát.",
            },
        )


@router.get("/api/agent/user-insight", summary="Get latest user_insight (Dev)")
@rate_limit_service.limiter.limit("120/minute")
async def get_user_insight(request: Request):
    """
    Polling endpoint for dev UI to fetch latest user_insight from Redis.
    """
    user_id = getattr(request.state, "user_id", None)
    device_id = getattr(request.state, "device_id", "unknown")
    is_authenticated = getattr(request.state, "is_authenticated", False)
    identity_id = user_id if is_authenticated else device_id

    try:
        client = redis_cache.get_client()
        if not client:
            return {"status": "pending", "user_insight": None}

        insight_key = f"identity_key_insight:{identity_id}"
        user_insight = await client.get(insight_key)

        if user_insight:
            return {"status": "success", "user_insight": user_insight}

        return {"status": "pending", "user_insight": None}
    except Exception as e:
        logger.error(f"Error in get_user_insight: {e}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={
                "status": "error",
                "error_code": "SYSTEM_ERROR",
                "message": "Không thể tải user_insight lúc này.",
            },
        )
