"""
Chatbot API Route
-----------------
`POST /api/agent/chat` - chính là endpoint chat cho CiCi Assistant.
Logic xử lý nằm ở `agent.controller.chat_controller`.
"""

import logging
from dataclasses import dataclass

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 config import DEFAULT_MODEL

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


@dataclass
class Identity:
  """Định danh đơn giản dựa trên middleware (user_id / device_id)."""
  primary_id: str
  history_key: str
  rate_limit_key: str
  is_authenticated: bool


def _get_identity(request: Request) -> Identity:
  """Derive identity info từ request.state (do middleware set)."""
  user_id = getattr(request.state, "user_id", None)
  device_id = getattr(request.state, "device_id", "") or ""
  is_authenticated = bool(getattr(request.state, "is_authenticated", False))

  if is_authenticated and user_id:
    primary_id = str(user_id)
    history_key = primary_id
    rate_limit_key = primary_id
  else:
    # Guest: dùng device_id, fallback 'anonymous'
    primary_id = device_id or "anonymous"
    history_key = device_id or "anonymous"
    rate_limit_key = device_id or "anonymous"

  return Identity(
    primary_id=primary_id,
    history_key=history_key,
    rate_limit_key=rate_limit_key,
    is_authenticated=is_authenticated,
  )


@router.post("/api/agent/chat", summary="Chat with CiCi Assistant")
async def cici_chat(request: Request, req: QueryRequest, background_tasks: BackgroundTasks):
  """
  Endpoint chat không stream - trả về response JSON đầy đủ một lần.

  - Tự lấy user/device từ middleware (`get_user_identity`)
  - Gọi `chat_controller` để xử lý toàn bộ logic LLM + tools
  - Tự tăng counter rate limit sau khi trả lời xong
  """
  # 1. Xác định identity
  identity = _get_identity(request)
  user_id = identity.primary_id

  logger.info("📥 [Incoming Chat] User=%s | Query=%s", user_id, req.user_query)

  # Span cho tracing (optional)
  span = trace.get_current_span()
  span.set_attribute("user.id", user_id)
  span.set_attribute("chat.user_query", req.user_query)

  try:
    # 2. Gọi controller xử lý
    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
    )

    # 3. Tăng usage info (rate limit) sau khi thành công
    usage_info = await message_limit_service.increment(
      identity_key=identity.rate_limit_key,
      is_authenticated=identity.is_authenticated,
    )

    logger.info("📤 [Outgoing Chat] User=%s", user_id)

    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("Error in cici_chat: %s", e, exc_info=True)
    raise HTTPException(status_code=500, detail=str(e)) from e


