"""
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, HTTPException, Request
from opentelemetry import trace

from agent.controller import chat_controller
from agent.models import QueryRequest
from common.message_limit import message_limit_service
from common.user_identity import get_user_identity
from config import DEFAULT_MODEL

logger = logging.getLogger(__name__)
tracer = trace.get_tracer(__name__)
router = APIRouter()


@router.post("/api/agent/chat", summary="Fashion Q&A Chat (Non-streaming)")
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.
    """
    # 1. Xác định user identity
    identity = get_user_identity(request)
    user_id = identity.primary_id
    
    # Rate limit đã check trong middleware, lấy limit_info từ request.state
    limit_info = getattr(request.state, 'limit_info', None)

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

    # Get current span để add logs VÀO JAEGER UI
    span = trace.get_current_span()
    span.set_attribute("user.id", user_id)
    span.set_attribute("chat.user_query", req.user_query)
    span.add_event(
        "📥 User query received", attributes={"user_id": user_id, "query": req.user_query, "timestamp": "incoming"}
    )

    try:
        # Gọi controller để xử lý logic (Non-streaming)
        result = await chat_controller(
            query=req.user_query,
            user_id=user_id,
            background_tasks=background_tasks,
            model_name=DEFAULT_MODEL,
            images=req.images,
            identity_key=identity.history_key,  # Guest: device_id, User: user_id
        )

        # Log chi tiết response
        logger.info(f"📤 [Outgoing Response - NonStream] User: {user_id}")
        logger.info(f"💬 AI Response: {result['ai_response']}")
        logger.info(f"🛍️ Product IDs: {result.get('product_ids', [])}")

        # Add to span (hiển thị trong Jaeger UI)
        span.set_attribute("chat.ai_response", result["ai_response"][:200])  # Giới hạn 200 ký tự
        span.set_attribute("chat.product_count", len(result.get("product_ids", [])))
        span.add_event(
            "💬 AI response generated",
            attributes={
                "ai_response_preview": result["ai_response"][:100],
                "product_count": len(result.get("product_ids", [])),
                "product_ids": str(result.get("product_ids", [])[:5]),  # First 5 IDs
            },
        )

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

        return {
            "status": "success",
            "ai_response": result["ai_response"],
            "product_ids": result.get("product_ids", []),
            "limit_info": {
                "limit": usage_info["limit"],
                "used": usage_info["used"],
                "remaining": usage_info["remaining"],
            },
        }
    except Exception as e:
        logger.error(f"Error in fashion_qa_chat: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e)) from e

