"""
Feedback API Route
Handles user feedback submission:
- Like/Dislike ratings
- Complaint forms with category selection
- Langfuse score creation
- Local feedback tracking
"""

import logging

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


from common.feedback_tracker import (
    get_all_feedbacks,
    get_feedback_stats,
    mark_processed,
    save_feedback,
)
from common.langfuse_client import async_flush_langfuse, get_langfuse_client

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


# ── Pydantic Models ──────────────────────────────────────────────────

class FeedbackRequest(BaseModel):
    trace_id: str
    rating: int  # 0=dislike, 1=like
    comment: str = ""
    category: str = ""  # user-selected category (optional)


class ProcessRequest(BaseModel):
    trace_id: str


# ── Helper: Push scores to Langfuse ─────────────────────────────────

def _push_langfuse_scores(
    trace_id: str,
    rating: int,
    comment: str = "",
    category: str = "",
):
    """
    Push feedback as 1 score to Langfuse.
    Uses score_id for idempotency (prevents duplicate scores on same trace).
    """
    client = get_langfuse_client()
    if not client:
        logger.warning("⚠️ Langfuse not available — scores not pushed")
        return

    try:
        metadata = {}
        if category:
            metadata["category"] = category

        client.create_score(
            trace_id=trace_id,
            name="user-feedback",
            value=float(rating),
            data_type="NUMERIC",
            comment=comment if comment else "",
            metadata=metadata,
            score_id=f"{trace_id}-user-feedback",
        )

        logger.info(f"📤 Langfuse score pushed for trace: {trace_id}")

    except Exception as e:
        logger.error(f"❌ Error pushing Langfuse scores: {e}")


# ── Background task: push scores ─────────────────────────────────────

async def _process_feedback_background(
    trace_id: str,
    rating: int,
    comment: str,
    user_category: str,
):
    """
    Background task:
    1. Push score to Langfuse
    2. Save to local tracker
    """
    final_category = user_category if user_category else "khac"

    # Push score to Langfuse
    _push_langfuse_scores(
        trace_id=trace_id,
        rating=rating,
        comment=comment,
        category=final_category,
    )

    # Save to local tracker
    save_feedback(
        trace_id=trace_id,
        rating=rating,
        comment=comment,
        user_category=user_category,
        ai_category=final_category,
        ai_severity="",
        ai_summary="",
    )

    # Flush Langfuse to ensure scores are sent
    await async_flush_langfuse()

    logger.info(f"✅ Feedback processed: trace={trace_id}, cat={final_category}")


# ── API Endpoints ────────────────────────────────────────────────────

@router.post("/api/feedback", summary="Submit user feedback")
async def submit_feedback(req: FeedbackRequest, background_tasks: BackgroundTasks):
    """
    Submit feedback for a chat response.

    - rating: 0 (dislike) or 1 (like)
    - comment: optional complaint text
    - category: optional user-selected category
    - trace_id: links feedback to the specific chat trace in Langfuse
    """
    if req.rating not in (0, 1):
        return JSONResponse(
            status_code=400,
            content={"status": "error", "message": "rating must be 0 or 1"},
        )

    if not req.trace_id:
        return JSONResponse(
            status_code=400,
            content={"status": "error", "message": "trace_id is required"},
        )

    # Process in background (AI classification + Langfuse + tracker)
    background_tasks.add_task(
        _process_feedback_background,
        trace_id=req.trace_id,
        rating=req.rating,
        comment=req.comment,
        user_category=req.category,
    )

    return {
        "status": "success",
        "message": "Cảm ơn bạn! Phản hồi đã được ghi nhận.",
        "trace_id": req.trace_id,
    }


@router.get("/api/feedback/stats", summary="Get feedback statistics")
async def feedback_stats():
    """Get summary statistics of all feedbacks."""
    return {"status": "success", "stats": get_feedback_stats()}


@router.get("/api/feedback/list", summary="List all feedbacks")
async def list_feedbacks(limit: int = 50, offset: int = 0):
    """List feedbacks with pagination."""
    feedbacks = get_all_feedbacks(limit=limit, offset=offset)
    return {"status": "success", "feedbacks": feedbacks, "count": len(feedbacks)}


@router.post("/api/feedback/process", summary="Mark feedback as processed")
async def process_feedback(req: ProcessRequest):
    """Mark a feedback item as processed/resolved."""
    success = mark_processed(req.trace_id)

    if not success:
        return JSONResponse(
            status_code=404,
            content={"status": "error", "message": "Feedback not found or already processed"},
        )

    # Chỉ cập nhật local storage, không push thêm score lên Langfuse
    logger.info(f"✅ Feedback {req.trace_id} marked as processed (local only)")

    return {"status": "success", "message": f"Feedback {req.trace_id} marked as processed"}
