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

Flow: AI #1 (classify) → inject stage → AI #2 (stylist) → response

Endpoint: POST /api/agent/chat-lead-flow
Endpoint: GET /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

from agent.controller_helpers import load_user_insight_from_redis
from agent.lead_stage_agent.graph import run_lead_stage_classifier

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


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. Load user_insight từ Redis
    2. Gọi LeadStageGraph (Classifier -> Stylist)
    3. Trả về response + pipeline + lead_stage metadata
    """
    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"📥 [Lead Flow] User: {identity_id} | Query: {req.user_query}")

    try:
        # ── Step 1: Load user_insight từ Redis ──
        user_insight = None
        if identity_id:
            user_insight = await load_user_insight_from_redis(str(identity_id))

        # ── Step 2: Lấy history ──
        from common.conversation_manager import get_conversation_manager
        from langchain_core.messages import AIMessage, HumanMessage
        
        memory = await get_conversation_manager()
        history_dicts = await memory.get_chat_history(
            str(identity_id), 
            limit=10, 
            include_product_ids=False, 
            conversation_id=req.conversation_id
        )
        history_msgs = [
            HumanMessage(content=m["message"]) if m["is_human"] else AIMessage(content=m["message"]) for m in history_dicts
        ][::-1]

        # ── Step 2.5: Build Langfuse Config ──
        from common.langfuse_client import get_callback_handler
        from langchain_core.runnables import RunnableConfig
        import uuid
        
        run_id = str(uuid.uuid4())
        session_id = req.conversation_id or f"{identity_id}-{run_id[:8]}"
        tags = ["lead_flow", "user:authenticated" if is_authenticated else "user:anonymous"]
        
        langfuse_handler = get_callback_handler()
        
        config_run = RunnableConfig(
            callbacks=[langfuse_handler] if langfuse_handler else [],
            run_name="lead_turn",
            metadata={
                "langfuse_session_id": session_id,
                "langfuse_user_id": str(identity_id),
                "langfuse_tags": tags,
                "conversation_id": session_id,
                "customer_id": identity_id if is_authenticated else None,
                "device_id": device_id,
            },
        )

        # ── Step 3: Giao việc cho 2-Agent LangGraph (LeadStageGraph) ──
        from agent.lead_stage_agent.graph import get_lead_stage_agent
        agent = get_lead_stage_agent()
        
        chat_result = await agent.chat(
            user_message=req.user_query,
            user_insight=user_insight,
            history=history_msgs,
            config=config_run
        )

        ai_response = chat_result.get("response", "")
        lead_stage = chat_result.get("lead_stage") or {}
        pipeline = chat_result.get("pipeline", [])
        total_elapsed = chat_result.get("elapsed_ms", 0)

        # Tính timing từ pipeline
        classifier_ms = 0
        stylist_ms = 0
        for p in pipeline:
            if p.get("step") == "classifier":
                classifier_ms = p.get("elapsed_ms", 0)
            elif p.get("step") in ("responder", "stylist"):
                stylist_ms += p.get("elapsed_ms", 0)

        logger.info(
            f"✅ [Lead Flow] Complete | "
            f"Stage: {lead_stage.get('stage_name')} | "
            f"Total: {total_elapsed:.0f}ms"
        )

        # Set response_payload cho background tasks
        response_payload = {
            "ai_response": ai_response,
            "product_ids": chat_result.get("products", []),
            "lead_stage": lead_stage,
        }

        # Lưu conversation background
        from agent.helper import handle_post_chat_async
        background_tasks.add_task(
            handle_post_chat_async,
            memory=memory,
            identity_key=str(identity_id),
            human_query=req.user_query,
            ai_response=response_payload,
            conversation_id=req.conversation_id,
        )

        return {
            "status": "success",
            "ai_response": ai_response,
            "products": chat_result.get("products", []),
            "trace_id": "",
            "lead_stage": lead_stage,
            "pipeline": pipeline,
            "timing": {
                "classifier_ms": classifier_ms,
                "stylist_ms": stylist_ms,
                "total_ms": total_elapsed,
            },
        }

    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:
        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]},
        )
