"""
User Simulator Route — MiroFish-Inspired Conversion Testing
============================================================
Thin API layer that delegates to agent/simulate_agent/ package.

Endpoints:
  GET  /archetypes         → List available archetypes
  POST /generate-personas  → Generate N personas
  POST /generate-message   → Persona generates 1 message
  POST /chat-with-bot      → Forward to chatbot API
  POST /evaluate           → Evaluate + conversion
  POST /synthesize         → Cross-persona report
  POST /run-simulation     → 🔥 Full automated loop
"""

import logging
from typing import Any

from fastapi import APIRouter
from fastapi.responses import JSONResponse
from pydantic import BaseModel

from agent.simulate_agent import (
    CANIFA_ARCHETYPES,
    evaluate_conversation,
    generate_personas,
    run_simulation,
    synthesize_results,
)
from agent.simulate_agent.simulation_runner import _generate_persona_message, _send_to_chatbot
from agent.simulate_agent.persona_generator import CanifaPersona

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/user-simulator", tags=["User Simulator"])

DEFAULT_CHATBOT_URL = "http://172.16.2.207:5000/api/agent/chat-dev"


# ═══════════════════════════════════════════════════════════════
# REQUEST MODELS
# ═══════════════════════════════════════════════════════════════
class GeneratePersonasRequest(BaseModel):
    count: int = 5
    archetypes: list[str] | None = None


class GenerateMessageRequest(BaseModel):
    persona_system: str
    persona_name: str
    turn: int = 0
    history: list[dict[str, str]] = []
    last_bot_reply: str = ""


class ChatWithBotRequest(BaseModel):
    message: str
    device_id: str = "simulator-test"


class EvaluateRequest(BaseModel):
    persona_name: str
    persona_age: int
    persona_archetype: str
    persona_trait: str
    conversation: list[dict[str, str]]
    conversion_trigger: str = ""
    drop_trigger: str = ""
    budget: str = ""
    shopping_for: str = ""


class SynthesizeRequest(BaseModel):
    chatbot_prompt: str
    results: list[dict[str, Any]]


class RunSimulationRequest(BaseModel):
    persona_count: int = 3
    turns_per_persona: int = 5
    archetypes: list[str] | None = None
    chatbot_url: str = ""


# ═══════════════════════════════════════════════════════════════
# ENDPOINTS
# ═══════════════════════════════════════════════════════════════
@router.get("/archetypes", summary="List available customer archetypes")
async def list_archetypes():
    return {"archetypes": CANIFA_ARCHETYPES}


@router.post("/generate-personas", summary="Generate realistic customer personas")
async def api_generate_personas(req: GeneratePersonasRequest):
    try:
        personas = await generate_personas(count=req.count, archetypes=req.archetypes)
        return {
            "status": "success",
            "count": len(personas),
            "personas": [p.to_dict() for p in personas],
        }
    except Exception as e:
        logger.error(f"Generate personas error: {e}", exc_info=True)
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})


@router.post("/generate-message", summary="Persona AI generates a message")
async def api_generate_message(req: GenerateMessageRequest):
    try:
        persona = CanifaPersona(
            name=req.persona_name, age=0, gender="", job="", income_range="",
            mbti="", shopping_for="", budget="", occasion="", style_preference="",
            chat_style="", system_prompt=req.persona_system,
            conversion_trigger="", drop_trigger="",
        )
        msg = await _generate_persona_message(persona, req.turn, req.history)
        return {"status": "success", "message": msg}
    except Exception as e:
        logger.error(f"Generate message error: {e}", exc_info=True)
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})


@router.post("/chat-with-bot", summary="Send message to chatbot API")
async def api_chat_with_bot(req: ChatWithBotRequest):
    try:
        result = await _send_to_chatbot(req.message, req.device_id, DEFAULT_CHATBOT_URL)
        return {"status": "success", **result}
    except Exception as e:
        logger.error(f"Chat with bot error: {e}", exc_info=True)
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})


@router.post("/evaluate", summary="Evaluate conversation + measure conversion")
async def api_evaluate(req: EvaluateRequest):
    try:
        result = await evaluate_conversation(
            persona_name=req.persona_name,
            persona_age=req.persona_age,
            persona_archetype=req.persona_archetype,
            chat_style=req.persona_trait,
            budget=req.budget,
            shopping_for=req.shopping_for,
            style_preference="",
            conversion_trigger=req.conversion_trigger,
            drop_trigger=req.drop_trigger,
            conversation=req.conversation,
        )
        return {"status": "success", **result}
    except Exception as e:
        logger.error(f"Evaluate error: {e}", exc_info=True)
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})


@router.post("/synthesize", summary="Cross-persona conversion report")
async def api_synthesize(req: SynthesizeRequest):
    try:
        result = await synthesize_results(
            results=req.results,
            chatbot_prompt=req.chatbot_prompt,
        )
        return {"status": "success", **result}
    except Exception as e:
        logger.error(f"Synthesize error: {e}", exc_info=True)
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})


@router.post("/run-simulation", summary="🔥 Run full automated simulation")
async def api_run_simulation(req: RunSimulationRequest):
    """
    Chạy FULL LOOP tự động:
    1. Generate personas (gpt-5.4-nano)
    2. Mỗi persona chat N turns với chatbot
    3. Evaluate + đo conversion
    4. Return conversion summary

    ⚠️ Có thể mất 2-5 phút tùy số persona.
    """
    try:
        result = await run_simulation(
            persona_count=req.persona_count,
            turns_per_persona=req.turns_per_persona,
            archetypes=req.archetypes,
            chatbot_url=req.chatbot_url or None,
        )
        return result
    except Exception as e:
        logger.error(f"Simulation error: {e}", exc_info=True)
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})
