"""
Social Inbox Webhook Parser
Ported & adapted từ BrightBean Studio apps/inbox/webhooks.py
Chuyển từ Django → FastAPI/asyncio, bỏ ORM dependency, thuần Python

Hỗ trợ: Facebook/Instagram webhook, TikTok comment webhook
Output: Chuẩn hóa thành SocialMessage dict → feed vào Canifa feedback_tracker
"""

import hashlib
import hmac
import logging
import os
from datetime import datetime, timezone

from .sentiment_vi import analyze_sentiment

logger = logging.getLogger(__name__)

# Lấy từ env (set trong .env của Canifa backend)
FACEBOOK_APP_SECRET = os.getenv("FACEBOOK_APP_SECRET", "")
FACEBOOK_WEBHOOK_VERIFY_TOKEN = os.getenv("FACEBOOK_WEBHOOK_VERIFY_TOKEN", "canifa_verify_token")


# ─────────────────────────────────────────────
# Data Model (simple dict — không cần ORM)
# ─────────────────────────────────────────────

async def _build_social_message(
    platform: str,         # "facebook" | "instagram" | "tiktok"
    message_type: str,     # "comment" | "dm" | "mention"
    sender_name: str,
    sender_id: str,
    body: str,
    post_id: str = "",
    raw: dict | None = None,
) -> dict:
    """Tạo chuẩn hóa SocialMessage dict để feed vào feedback_tracker."""
    sentiment = await analyze_sentiment(body)
    return {
        "source": "social",
        "platform": platform,
        "message_type": message_type,
        "sender_name": sender_name,
        "sender_id": sender_id,
        "body": body,
        "post_id": post_id,
        "sentiment": sentiment,           # "positive" | "negative" | "neutral"
        "received_at": datetime.now(timezone.utc).isoformat(),
        "raw": raw or {},
    }


# ─────────────────────────────────────────────
# Facebook / Instagram Webhook Handler
# (Adapted từ BrightBean webhooks.py)
# ─────────────────────────────────────────────

def verify_facebook_signature(body: bytes, signature_header: str) -> bool:
    """Verify HMAC-SHA256 signature từ Facebook. Bảo vệ khỏi webhook giả."""
    if not FACEBOOK_APP_SECRET:
        logger.warning("⚠️  FACEBOOK_APP_SECRET chưa set — bỏ qua verify (dev mode)")
        return True  # Dev mode: không verify

    expected = "sha256=" + hmac.new(
        FACEBOOK_APP_SECRET.encode(),
        body,
        hashlib.sha256,
    ).hexdigest()
    return hmac.compare_digest(expected, signature_header)


async def parse_facebook_webhook(payload: dict) -> list[dict]:
    """
    Parse Facebook/Instagram webhook payload → list[SocialMessage].
    Hỗ trợ: comments, mentions, DM (messaging events).
    """
    messages = []

    for entry in payload.get("entry", []):
        # Facebook Page comments & mentions
        for change in entry.get("changes", []):
            field = change.get("field", "")
            value = change.get("value", {})

            if field == "feed":
                msg = await _parse_fb_feed_change(value)
                if msg:
                    messages.append(msg)

            elif field == "mention":
                msg = await _parse_fb_mention(value)
                if msg:
                    messages.append(msg)

        # Instagram / Facebook DM (messaging events)
        for messaging in entry.get("messaging", []):
            msg = await _parse_fb_messaging(messaging)
            if msg:
                messages.append(msg)

    return messages


async def _parse_fb_feed_change(value: dict) -> dict | None:
    """Parse một Facebook comment từ feed change event."""
    comment_id = value.get("comment_id") or value.get("id")
    if not comment_id:
        return None

    from_data = value.get("from", {})
    body = value.get("message", "").strip()
    if not body:
        return None

    post_id = value.get("post_id", "")
    platform = "instagram" if value.get("item") == "comment" and "instagram" in str(value).lower() else "facebook"

    return await _build_social_message(
        platform=platform,
        message_type="comment",
        sender_name=from_data.get("name", "Unknown"),
        sender_id=from_data.get("id", ""),
        body=body,
        post_id=post_id,
        raw=value,
    )


async def _parse_fb_mention(value: dict) -> dict | None:
    """Parse Facebook mention event."""
    mention_id = value.get("post_id") or value.get("id")
    if not mention_id:
        return None

    from_data = value.get("from", {})
    body = value.get("message", "").strip()
    if not body:
        return None

    return await _build_social_message(
        platform="facebook",
        message_type="mention",
        sender_name=from_data.get("name", "Unknown"),
        sender_id=from_data.get("id", ""),
        body=body,
        post_id=mention_id,
        raw=value,
    )


async def _parse_fb_messaging(messaging: dict) -> dict | None:
    """Parse Facebook/Instagram DM message."""
    message_data = messaging.get("message", {})
    mid = message_data.get("mid")
    if not mid:
        return None

    sender = messaging.get("sender", {})
    body = message_data.get("text", "").strip()
    if not body:
        return None  # Bỏ qua message ảnh/sticker không có text

    return await _build_social_message(
        platform="instagram",
        message_type="dm",
        sender_name=sender.get("name", sender.get("id", "Unknown")),
        sender_id=sender.get("id", ""),
        body=body,
        post_id="",
        raw=messaging,
    )


# ─────────────────────────────────────────────
# TikTok Webhook Handler
# TikTok gửi comment events qua webhook
# ─────────────────────────────────────────────

async def parse_tiktok_webhook(payload: dict) -> list[dict]:
    """
    Parse TikTok comment webhook payload → list[SocialMessage].
    TikTok webhook format khác Facebook.
    """
    messages = []

    # TikTok comment notification
    comments = payload.get("data", {}).get("comments", [])
    for comment in comments:
        body = comment.get("text", "").strip()
        if not body:
            continue

        user = comment.get("user", {})
        msg = await _build_social_message(
            platform="tiktok",
            message_type="comment",
            sender_name=user.get("display_name", user.get("unique_id", "Unknown")),
            sender_id=user.get("open_id", ""),
            body=body,
            post_id=comment.get("video_id", ""),
            raw=comment,
        )
        messages.append(msg)

    return messages


# ─────────────────────────────────────────────
# Facebook Webhook Verification (for GET requests)
# ─────────────────────────────────────────────

def handle_facebook_verify(mode: str, token: str, challenge: str) -> str | None:
    """
    Xử lý Facebook webhook verification handshake (GET request).
    Returns challenge string nếu valid, None nếu invalid.
    """
    if mode == "subscribe" and token == FACEBOOK_WEBHOOK_VERIFY_TOKEN:
        logger.info("✅ Facebook webhook verified!")
        return challenge
    logger.warning("❌ Facebook webhook verification failed. Token mismatch.")
    return None
