"""
Social Inbox API Route
Nhận webhook từ Facebook/Instagram/TikTok → phân tích sentiment → feed vào Canifa learning loop.
Cũng expose REST API để FE dashboard đọc messages.
"""

import json
import logging
import os
from datetime import datetime, timezone
from typing import Optional

from fastapi import APIRouter, BackgroundTasks, Header, HTTPException, Query, Request
from fastapi.responses import JSONResponse, PlainTextResponse

from common.social.inbox_webhook import (
    handle_facebook_verify,
    parse_facebook_webhook,
    parse_tiktok_webhook,
    verify_facebook_signature,
)
from common.social.sentiment_vi import analyze_sentiment_detail
from common.feedback_tracker import save_feedback

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/social", tags=["Social Inbox"])

# File lưu social messages (lightweight, tương tự feedback_tracker)
SOCIAL_MESSAGES_FILE = os.path.join(
    os.path.dirname(os.path.abspath(__file__)), "..", "data", "social_messages.json"
)


# ─────────────────────────────────────────────
# Storage helpers
# ─────────────────────────────────────────────

def _ensure_dir():
    os.makedirs(os.path.dirname(SOCIAL_MESSAGES_FILE), exist_ok=True)


def _load_messages() -> list[dict]:
    _ensure_dir()
    if not os.path.exists(SOCIAL_MESSAGES_FILE):
        return []
    try:
        with open(SOCIAL_MESSAGES_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return []


def _save_messages(messages: list[dict]):
    _ensure_dir()
    with open(SOCIAL_MESSAGES_FILE, "w", encoding="utf-8") as f:
        json.dump(messages, f, ensure_ascii=False, indent=2, default=str)


def _append_messages(new_messages: list[dict]):
    """Append new messages, dedup by platform + body."""
    existing = _load_messages()
    existing_keys = {(m.get("platform"), m.get("body")) for m in existing}
    added = 0
    for msg in new_messages:
        key = (msg.get("platform"), msg.get("body"))
        if key not in existing_keys:
            existing.insert(0, msg)  # newest first
            existing_keys.add(key)
            added += 1
    # Giữ tối đa 500 messages
    _save_messages(existing[:500])
    return added


# ─────────────────────────────────────────────
# Background: Feed message vào learning loop
# ─────────────────────────────────────────────

def _feed_to_feedback_tracker(messages: list[dict]):
    """
    Feed social messages vào Canifa feedback_tracker.
    Negative messages → learning loop để AI cải thiện.
    """
    for msg in messages:
        if msg.get("sentiment") == "negative":
            try:
                save_feedback(
                    trace_id=f"social_{msg.get('platform')}_{datetime.now(timezone.utc).timestamp()}",
                    rating=0,  # 0 = dislike (negative feedback)
                    comment=msg.get("body", ""),
                    user_category="social_feedback",
                    ai_category="social_negative_comment",
                    ai_severity="low",
                    ai_summary=f"[{msg.get('platform', '').upper()}] Negative comment từ @{msg.get('sender_name', 'Unknown')}: {msg.get('body', '')[:100]}",
                )
                logger.info(f"📥 Social negative feedback fed to learning loop: {msg.get('platform')} / {msg.get('body', '')[:50]}")
            except Exception as e:
                logger.error(f"Failed to feed to feedback tracker: {e}")


# ─────────────────────────────────────────────
# Facebook/Instagram Webhook
# ─────────────────────────────────────────────

@router.get("/webhook/facebook")
async def facebook_webhook_verify(
    hub_mode: str = Query(None, alias="hub.mode"),
    hub_verify_token: str = Query(None, alias="hub.verify_token"),
    hub_challenge: str = Query("", alias="hub.challenge"),
):
    """Facebook webhook verification (GET handshake)."""
    challenge = handle_facebook_verify(hub_mode or "", hub_verify_token or "", hub_challenge)
    if challenge is None:
        raise HTTPException(status_code=403, detail="Webhook verification failed")
    return PlainTextResponse(challenge)


@router.post("/webhook/facebook")
async def facebook_webhook_receive(
    request: Request,
    background_tasks: BackgroundTasks,
    x_hub_signature_256: Optional[str] = Header(None, alias="X-Hub-Signature-256"),
):
    """Nhận Facebook/Instagram comment/DM webhook events."""
    body = await request.body()

    # Verify signature
    if not verify_facebook_signature(body, x_hub_signature_256 or ""):
        raise HTTPException(status_code=403, detail="Invalid webhook signature")

    try:
        payload = await request.json()
    except Exception:
        raise HTTPException(status_code=400, detail="Invalid JSON")

    messages = parse_facebook_webhook(payload)
    if messages:
        added = _append_messages(messages)
        background_tasks.add_task(_feed_to_feedback_tracker, messages)
        logger.info(f"📬 Facebook/IG webhook: {len(messages)} events, {added} mới")

    return JSONResponse({"ok": True, "received": len(messages)})


# ─────────────────────────────────────────────
# TikTok Webhook
# ─────────────────────────────────────────────

@router.post("/webhook/tiktok")
async def tiktok_webhook_receive(
    request: Request,
    background_tasks: BackgroundTasks,
):
    """Nhận TikTok comment webhook events."""
    try:
        payload = await request.json()
    except Exception:
        raise HTTPException(status_code=400, detail="Invalid JSON")

    messages = parse_tiktok_webhook(payload)
    if messages:
        added = _append_messages(messages)
        background_tasks.add_task(_feed_to_feedback_tracker, messages)
        logger.info(f"📬 TikTok webhook: {len(messages)} comments, {added} mới")

    return JSONResponse({"ok": True, "received": len(messages)})


# ─────────────────────────────────────────────
# REST API cho FE Dashboard
# ─────────────────────────────────────────────

@router.get("/messages")
async def get_social_messages(
    platform: Optional[str] = Query(None, description="facebook | instagram | tiktok"),
    sentiment: Optional[str] = Query(None, description="positive | negative | neutral"),
    limit: int = Query(50, ge=1, le=200),
    offset: int = Query(0, ge=0),
):
    """
    Lấy danh sách social messages cho dashboard.
    Filter theo platform và/hoặc sentiment.
    """
    messages = _load_messages()

    if platform:
        messages = [m for m in messages if m.get("platform") == platform]
    if sentiment:
        messages = [m for m in messages if m.get("sentiment") == sentiment]

    total = len(messages)
    paginated = messages[offset: offset + limit]

    return {
        "total": total,
        "limit": limit,
        "offset": offset,
        "messages": paginated,
    }


@router.get("/messages/stats")
async def get_social_stats():
    """Thống kê tổng hợp social messages theo platform + sentiment."""
    messages = _load_messages()
    total = len(messages)

    stats: dict = {
        "total": total,
        "by_platform": {},
        "by_sentiment": {"positive": 0, "negative": 0, "neutral": 0},
        "negative_rate": 0.0,
    }

    for msg in messages:
        platform = msg.get("platform", "unknown")
        sentiment = msg.get("sentiment", "neutral")

        if platform not in stats["by_platform"]:
            stats["by_platform"][platform] = {"total": 0, "positive": 0, "negative": 0, "neutral": 0}
        stats["by_platform"][platform]["total"] += 1
        stats["by_platform"][platform][sentiment] = stats["by_platform"][platform].get(sentiment, 0) + 1
        stats["by_sentiment"][sentiment] = stats["by_sentiment"].get(sentiment, 0) + 1

    if total > 0:
        stats["negative_rate"] = round(stats["by_sentiment"]["negative"] / total * 100, 1)

    return stats


@router.post("/messages/analyze")
async def analyze_text_sentiment(request: Request):
    """
    Test sentiment analysis — nhập text, trả về phân tích.
    Dùng cho debug / demo trên dashboard.
    """
    body = await request.json()
    text = body.get("text", "")
    if not text:
        raise HTTPException(status_code=400, detail="text is required")

    result = analyze_sentiment_detail(text)
    return result


@router.delete("/messages/clear")
async def clear_social_messages():
    """Xóa toàn bộ messages (dùng khi debug)."""
    _save_messages([])
    return {"ok": True, "message": "Đã xóa tất cả social messages"}
