"""
Lead Flow Route — Endpoint thí nghiệm cho Lead Stage AI.

Flow: AI #1 (Classifier + Tools) → AI #2 (Stylist) → response
All traced via Langfuse through lead_stage_agent.controller.

Endpoint: POST /api/agent/chat-lead-flow
Endpoint: POST /api/agent/lead-stage (classifier only — for debug)
"""

import logging

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

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


class LeadFlowRequest(BaseModel):
    """Request model cho lead flow endpoint."""
    user_query: str
    images: list[str] | None = None
    conversation_id: str | None = None
    device_id: str | None = None  # persistent device ID từ frontend


class LeadStageTestRequest(BaseModel):
    """Request model cho standalone classifier test."""
    user_query: str
    user_insight: str | None = None
    chat_history_summary: str | None = None


@router.post("/api/agent/chat-lead-flow", summary="Lead Stage AI Chat (Experimental)")
async def chat_lead_flow(request: Request, req: LeadFlowRequest, background_tasks: BackgroundTasks):
    """
    Endpoint thí nghiệm Lead Stage AI.
    
    Flow:
    1. Delegate to lead_stage_agent.controller (Langfuse-traced)
    2. Controller runs: Load insight → Load history → Classifier ⇄ Tools → Stylist
    3. Return response + pipeline + lead_stage metadata
    """
    user_id = getattr(request.state, "user_id", None)
    middleware_device_id = getattr(request.state, "device_id", None)
    is_authenticated = getattr(request.state, "is_authenticated", False)

    # Ưu tiên device_id từ request body (chắc chắn có) nếu middleware không parse được
    device_id = middleware_device_id or req.device_id or "unknown"
    identity_id = user_id if is_authenticated else device_id

    logger.info(f"📥 [Lead Flow] identity={identity_id} | middleware_device={middleware_device_id} | req_device={req.device_id} | query={req.user_query[:60]}")

    try:
        from agent.lead_stage_agent.controller import lead_stage_chat_controller

        result = await lead_stage_chat_controller(
            query=req.user_query,
            identity_key=str(identity_id),
            background_tasks=background_tasks,
            conversation_id=req.conversation_id,
            is_authenticated=is_authenticated,
            device_id=str(device_id),
        )

        return result

    except Exception as e:
        logger.error(f"❌ [Lead Flow] Error: {e}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={
                "status": "error",
                "error_code": "LEAD_FLOW_ERROR",
                "message": f"Lead Flow Error: {str(e)[:200]}",
            },
        )


@router.post("/api/agent/lead-stage", summary="Lead Stage Classifier Only (Debug)")
async def classify_only(req: LeadStageTestRequest):
    """
    Debug endpoint — chỉ chạy AI #1 classifier, không gọi AI #2.
    Dùng để test/tune classifier prompt.
    """
    try:
        from agent.lead_stage_agent.graph import run_lead_stage_classifier

        result = await run_lead_stage_classifier(
            user_query=req.user_query,
            user_insight=req.user_insight,
            chat_history_summary=req.chat_history_summary,
        )
        return {
            "status": "success",
            **result,
        }
    except Exception as e:
        logger.error(f"❌ [Lead Stage Debug] Error: {e}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={"status": "error", "message": str(e)[:200]},
        )


@router.get("/api/lead/history", summary="Lead Flow History từ Postgres")
async def get_lead_history(request: Request, conv_id: str, limit: int = 50):
    """
    Load toàn bộ history của 1 conversation từ Postgres.
    Persistent — không bị TTL như Redis.
    
    Query params:
        conv_id: conversation ID
        limit: số messages tối đa (default 50)
    """
    from common.lead_flow_postgres import get_lead_history as _get

    middleware_device_id = getattr(request.state, "device_id", None)
    device_id = middleware_device_id or request.headers.get("device_id") or "unknown"

    history = await _get(device_id=device_id, conv_id=conv_id, limit=limit)
    return {"status": "success", "data": history, "conv_id": conv_id, "device_id": device_id}


@router.get("/api/lead/conversations", summary="Danh sách session Lead Flow")
async def list_lead_conversations(request: Request, limit: int = 20):
    """
    Trả về danh sách conversation của device hiện tại.
    Dùng cho dropdown chọn session trong dashboard.
    """
    from common.lead_flow_postgres import list_lead_conversations as _list

    middleware_device_id = getattr(request.state, "device_id", None)
    device_id = middleware_device_id or request.headers.get("device_id") or "unknown"

    conversations = await _list(device_id=device_id, limit=limit)
    return {"status": "success", "data": conversations, "device_id": device_id}


@router.get("/api/lead/dashboard", summary="Admin: Toàn bộ Lead Flow History")
async def lead_dashboard_all(limit: int = 200):
    """
    Admin dashboard — lấy toàn bộ history gần nhất (mọi device) từ Postgres.
    Dùng để monitor và test lead flow conversations.
    """
    from common.lead_flow_postgres import get_all_history_for_dashboard as _all

    rows = await _all(limit=limit)
    return {"status": "success", "data": rows, "count": len(rows)}
