"""
Event Boost Test API — Test event context boost trực tiếp.
"""

from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel
from typing import Optional, Dict, Any
import logging

from agent.event_agent.event_hard import get_event_context
from agent.event_agent.product_search_engine import ProductSearchEngine, LeadSearchInput, LiteralSearch, InferredSearch

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/event-test", tags=["Event Boost Test"])

engine = ProductSearchEngine()


class EventBoostTestRequest(BaseModel):
    """Request để test event boost."""
    query: str
    product_line_vn: list[str] = []
    gender_by_product: Optional[str] = None
    master_color: Optional[str] = None
    tags: list[str] = []
    keywords: list[str] = []
    price_min: Optional[int] = None
    price_max: Optional[int] = None
    size: Optional[str] = None


class EventBoostTestResponse(BaseModel):
    """Response từ event boost test."""
    query: str
    event_context: Dict[str, Any]
    boosted_params: Dict[str, Any]
    search_result: Dict[str, Any]
    boost_applied: bool
    message: str


@router.post("/boost", response_model=EventBoostTestResponse)
async def test_event_boost(request: EventBoostTestRequest):
    """
    Test event boost — Cho query, xem event context và params được boost như thế nào.

    Example:
    ```json
    {
        "query": "tìm áo 30/4",
        "product_line_vn": ["Áo phông"],
        "tags": [],
        "keywords": []
    }
    ```
    """
    try:
        # 1. Get event context từ query
        event_context = get_event_context(request.query)
        mentioned = event_context.get("mentioned_event")

        # 2. Build inferred search với params ban đầu
        inferred = InferredSearch(
            product_line_vn=request.product_line_vn,
            gender_by_product=request.gender_by_product,
            master_color=request.master_color,
            tags=request.tags,
            keywords=request.keywords,
            price_min=request.price_min,
            price_max=request.price_max,
            size=request.size,
        )

        # 3. Build lead search input
        literal = LiteralSearch(raw_text=request.query)
        lead_input = LeadSearchInput(
            literal=literal,
            inferred=inferred,
            event_context=event_context  # Truyền event context
        )

        # 4. Apply event boost (internal method)
        engine._apply_event_context(lead_input, event_context)

        # 5. Get boosted params
        boosted = lead_input.inferred

        boost_applied = bool(mentioned)
        message = f"Event '{mentioned.get('name')}' boost applied" if boost_applied else "No event detected"

        # 6. Optional: Run actual search (comment out nếu chỉ muốn test boost)
        # search_result = await engine.search(lead_input)

        return EventBoostTestResponse(
            query=request.query,
            event_context=event_context,
            boosted_params={
                "product_line_vn": boosted.product_line_vn,
                "master_color": boosted.master_color,
                "tags": boosted.tags,
                "keywords": boosted.keywords,
            },
            search_result={"status": "ok", "note": "Search not executed in test mode"},
            boost_applied=boost_applied,
            message=message
        )

    except Exception as e:
        logger.error(f"Event boost test error: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/events")
async def list_events():
    """
    List tất cả events có sẵn trong event_hard.py
    """
    from agent.event_agent.event_hard import _EVENTS

    events = []
    for ev in _EVENTS:
        events.append({
            "name": ev.name,
            "date": f"{ev.day:02d}/{ev.month:02d}",
            "tags": ev.tags,
            "keywords": ev.keywords,
            "master_color": ev.master_color,
            "product_line_vn": ev.product_line_vn,
        })

    return {
        "total": len(events),
        "events": events
    }


@router.get("/test-sample")
async def test_sample_queries():
    """
    Run sample test queries và trả về kết quả.
    """
    test_queries = [
        "tìm áo 30/4",
        "váy Valentine",
        "áo Tết",
        "quần jean nam",
    ]

    results = []
    for query in test_queries:
        try:
            req = EventBoostTestRequest(query=query)
            resp = await test_event_boost(req)
            results.append({
                "query": query,
                "event_detected": resp.boost_applied,
                "event_name": resp.event_context.get("mentioned_event", {}).get("name") if resp.boost_applied else None,
                "boosted_params": resp.boosted_params,
            })
        except Exception as e:
            results.append({
                "query": query,
                "error": str(e)
            })

    return {
        "total": len(results),
        "results": results
    }
