"""
Reaction Simulator Route — BettaFish-Inspired Community Reaction Simulator
===========================================================================
API layer for the reaction_agent package.

Endpoints:
  GET  /segments             → List persona segments
  GET  /campaign-types       → List campaign types
  POST /simulate             → Run full reaction simulation
  POST /simulate-mock        → Return mock data (no LLM needed)
"""

import logging
from typing import Any

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

from agent.reaction_agent import CAMPAIGN_TYPES, PERSONA_SEGMENTS, run_reaction_simulation

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


# ═══ REQUEST MODELS ═══
class SimulateRequest(BaseModel):
    campaign_type: str = "product_launch"
    campaign_content: str
    persona_weights: dict[str, float] | None = None
    model_name: str | None = None


# ═══ ENDPOINTS ═══

@router.get("/segments")
async def get_segments():
    """List all available persona segments."""
    return JSONResponse(content={
        "segments": [
            {"id": s["id"], "name": s["name"], "desc": s["desc"], "weight": s["weight"]}
            for s in PERSONA_SEGMENTS
        ]
    })


@router.get("/campaign-types")
async def get_campaign_types():
    """List all campaign types."""
    return JSONResponse(content={"types": CAMPAIGN_TYPES})


@router.post("/simulate")
async def simulate_reactions(req: SimulateRequest):
    """Run full LLM-powered reaction simulation."""
    logger.info(f"🔮 Reaction simulation: type={req.campaign_type}")
    try:
        from api.reaction_simulator.reaction_db import save_reaction_run
        result = await run_reaction_simulation(
            campaign_type=req.campaign_type,
            campaign_content=req.campaign_content,
            persona_weights=req.persona_weights,
            model_name=req.model_name,
        )
        result["campaign_content"] = req.campaign_content
        run_id = save_reaction_run(result, is_mock=False)
        result["run_id"] = run_id
        return JSONResponse(content=result)
    except Exception as e:
        logger.error(f"❌ Simulation failed: {e}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={"status": "error", "message": str(e)},
        )


@router.post("/simulate-mock")
async def simulate_mock(req: SimulateRequest):
    """Return mock reaction data (no LLM required)."""
    from api.reaction_simulator.reaction_db import save_reaction_run
    mock_reactions = _get_mock_reactions(req.campaign_type)
    pos = sum(1 for r in mock_reactions if r["sentiment"] == "positive")
    neu = sum(1 for r in mock_reactions if r["sentiment"] == "neutral")
    neg = sum(1 for r in mock_reactions if r["sentiment"] == "negative")
    total = len(mock_reactions)

    result = {
        "status": "success",
        "mode": "mock",
        "campaign_type": req.campaign_type,
        "campaign_content": req.campaign_content,
        "reactions": mock_reactions,
        "sentiment": {
            "positive": round(pos / total * 100),
            "neutral": round(neu / total * 100),
            "negative": round(neg / total * 100),
            "total_reactions": total,
        },
        "recommendations": [
            {"icon": "📊", "severity": "info", "text": "Mock mode — kết nối LLM để có phản ứng realistic hơn."},
        ],
    }
    
    run_id = save_reaction_run(result, is_mock=True)
    result["run_id"] = run_id
    return JSONResponse(content=result)


@router.get("/history")
async def api_history(limit: int = 50):
    try:
        from api.reaction_simulator.reaction_db import get_reaction_runs
        runs = get_reaction_runs(limit)
        return {"status": "success", "runs": runs}
    except Exception as e:
        logger.error(f"History error: {e}", exc_info=True)
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})


@router.get("/history/{run_id}")
async def api_history_detail(run_id: str):
    try:
        from api.reaction_simulator.reaction_db import get_reaction_run
        run = get_reaction_run(run_id)
        if not run:
            return JSONResponse(status_code=404, content={"status": "error", "message": "Run not found"})
        return {"status": "success", "run": run}
    except Exception as e:
        logger.error(f"History detail error: {e}", exc_info=True)
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})


@router.get("/compare")
async def api_compare(run1: str, run2: str):
    try:
        from api.reaction_simulator.reaction_db import compare_reaction_runs
        comparison = compare_reaction_runs(run1, run2)
        if "error" in comparison:
            return JSONResponse(status_code=404, content={"status": "error", "message": comparison["error"]})
        return {"status": "success", "comparison": comparison}
    except Exception as e:
        logger.error(f"Compare error: {e}", exc_info=True)
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})


def _get_mock_reactions(campaign_type: str) -> list[dict[str, Any]]:
    """Static mock reactions for demo."""
    base = [
        {"persona_id": "mom_shopper", "persona_name": "Nguyễn Thị Mai", "segment": "Mom Shopper",
         "comment": "Sản phẩm này phù hợp cho gia đình quá!", "sentiment": "positive",
         "likes_estimate": 38, "shares_estimate": 6, "key_concern": None},
        {"persona_id": "young_professional", "persona_name": "Trần Văn Hùng", "segment": "Young Professional",
         "comment": "Thiết kế ổn, cần xem thực tế.", "sentiment": "neutral",
         "likes_estimate": 21, "shares_estimate": 3, "key_concern": "thiết kế thực tế"},
        {"persona_id": "fashion_enthusiast", "persona_name": "Lê Phương Anh", "segment": "Fashion Enthusiast",
         "comment": "Đúng trend luôn! Must have!", "sentiment": "positive",
         "likes_estimate": 54, "shares_estimate": 14, "key_concern": None},
        {"persona_id": "budget_conscious", "persona_name": "Phạm Minh Tuấn", "segment": "Budget Conscious",
         "comment": "Giá hơi cao, cần cân nhắc.", "sentiment": "neutral",
         "likes_estimate": 16, "shares_estimate": 1, "key_concern": "giá cả"},
        {"persona_id": "gen_z", "persona_name": "Hoàng Thúy Linh", "segment": "Gen Z Trendy",
         "comment": "Vibe chill ghê 🔥 sắm ngay!", "sentiment": "positive",
         "likes_estimate": 62, "shares_estimate": 19, "key_concern": None},
        {"persona_id": "kol", "persona_name": "Fashion Blogger", "segment": "KOL / Blogger",
         "comment": "Canifa đang đi đúng hướng. Waiting full review.", "sentiment": "positive",
         "likes_estimate": 102, "shares_estimate": 28, "key_concern": None},
        {"persona_id": "troll", "persona_name": "Random Commenter", "segment": "Social Media Troll",
         "comment": "Lại marketing, scroll qua thôi 🥱", "sentiment": "negative",
         "likes_estimate": 11, "shares_estimate": 1, "key_concern": "marketing fatigue"},
    ]
    return base
