"""
Facebook & Instagram Provider
Ported & adapted từ BrightBean Studio providers/facebook.py + providers/instagram.py
Simplified: chỉ giữ phần publish post + get comments (Canifa use case)
"""

from __future__ import annotations

import logging
import os

from .base import APIError, SocialProvider

logger = logging.getLogger(__name__)

FACEBOOK_GRAPH_API = "https://graph.facebook.com/v19.0"

# App credentials từ env
FACEBOOK_APP_ID = os.getenv("FACEBOOK_APP_ID", "")
FACEBOOK_APP_SECRET = os.getenv("FACEBOOK_APP_SECRET", "")


class FacebookProvider(SocialProvider):
    """
    Facebook Page provider — publish posts + đọc comments.
    Dùng cho: Canifa auto-post outfit suggestions lên Facebook Page.
    """

    @property
    def platform_name(self) -> str:
        return "Facebook"

    def get_profile(self, access_token: str) -> dict:
        """Lấy thông tin Facebook Page."""
        response = self._request(
            "GET",
            f"{FACEBOOK_GRAPH_API}/me",
            access_token=access_token,
            params={"fields": "id,name,fan_count,picture"},
        )
        return response.json()

    def publish_post(self, access_token: str, content: dict) -> dict:
        """
        Publish một post lên Facebook Page.
        content = {"text": str, "link": str | None, "image_url": str | None}
        """
        page_id = content.get("page_id", "me")
        payload: dict = {"message": content.get("text", "")}

        if content.get("link"):
            payload["link"] = content["link"]

        # Nếu có ảnh → dùng photos endpoint
        if content.get("image_url"):
            return self._publish_with_photo(access_token, page_id, content)

        response = self._request(
            "POST",
            f"{FACEBOOK_GRAPH_API}/{page_id}/feed",
            access_token=access_token,
            json=payload,
        )
        data = response.json()
        return {
            "post_id": data.get("id", ""),
            "success": True,
            "platform": "facebook",
        }

    def _publish_with_photo(self, access_token: str, page_id: str, content: dict) -> dict:
        """Upload ảnh + publish caption lên Facebook."""
        payload = {
            "url": content["image_url"],
            "caption": content.get("text", ""),
            "published": True,
        }
        response = self._request(
            "POST",
            f"{FACEBOOK_GRAPH_API}/{page_id}/photos",
            access_token=access_token,
            json=payload,
        )
        data = response.json()
        return {
            "post_id": data.get("id", ""),
            "success": True,
            "platform": "facebook",
        }

    def get_comments(self, access_token: str, post_id: str) -> list[dict]:
        """Lấy comments của một Facebook post để phân tích feedback."""
        response = self._request(
            "GET",
            f"{FACEBOOK_GRAPH_API}/{post_id}/comments",
            access_token=access_token,
            params={
                "fields": "id,message,from,created_time,like_count",
                "order": "chronological",
                "limit": 100,
            },
        )
        data = response.json()
        comments = []
        for item in data.get("data", []):
            comments.append({
                "platform_comment_id": item.get("id", ""),
                "body": item.get("message", ""),
                "sender_name": item.get("from", {}).get("name", "Unknown"),
                "sender_id": item.get("from", {}).get("id", ""),
                "created_at": item.get("created_time", ""),
                "like_count": item.get("like_count", 0),
            })
        return comments

    def reply_comment(self, access_token: str, comment_id: str, text: str) -> dict:
        """Reply vào một Facebook comment."""
        response = self._request(
            "POST",
            f"{FACEBOOK_GRAPH_API}/{comment_id}/comments",
            access_token=access_token,
            json={"message": text},
        )
        data = response.json()
        return {"reply_id": data.get("id", ""), "success": True}


class InstagramProvider(SocialProvider):
    """
    Instagram Business Account provider.
    Dùng cho: Canifa auto-post outfit / fashion content lên Instagram.
    """

    @property
    def platform_name(self) -> str:
        return "Instagram"

    def get_profile(self, access_token: str) -> dict:
        """Lấy thông tin Instagram Business Account."""
        response = self._request(
            "GET",
            f"{FACEBOOK_GRAPH_API}/me",
            access_token=access_token,
            params={
                "fields": "id,name,username,biography,followers_count,media_count,profile_picture_url",
            },
        )
        return response.json()

    def publish_post(self, access_token: str, content: dict) -> dict:
        """
        Publish Instagram post (ảnh + caption).
        Instagram requires media — must have image_url.
        content = {"text": str, "image_url": str (required), "ig_user_id": str}
        """
        ig_user_id = content.get("ig_user_id", "me")
        image_url = content.get("image_url")

        if not image_url:
            raise ValueError("Instagram publish requires image_url")

        # Step 1: Tạo media container
        container_response = self._request(
            "POST",
            f"{FACEBOOK_GRAPH_API}/{ig_user_id}/media",
            access_token=access_token,
            json={
                "image_url": image_url,
                "caption": content.get("text", ""),
            },
        )
        container_id = container_response.json().get("id")
        if not container_id:
            raise APIError("Không tạo được Instagram media container", platform="Instagram")

        # Step 2: Publish container
        publish_response = self._request(
            "POST",
            f"{FACEBOOK_GRAPH_API}/{ig_user_id}/media_publish",
            access_token=access_token,
            json={"creation_id": container_id},
        )
        data = publish_response.json()
        return {
            "post_id": data.get("id", ""),
            "success": True,
            "platform": "instagram",
        }

    def get_comments(self, access_token: str, post_id: str) -> list[dict]:
        """Lấy comments của một Instagram post."""
        response = self._request(
            "GET",
            f"{FACEBOOK_GRAPH_API}/{post_id}/comments",
            access_token=access_token,
            params={
                "fields": "id,text,username,timestamp,like_count",
                "limit": 100,
            },
        )
        data = response.json()
        comments = []
        for item in data.get("data", []):
            comments.append({
                "platform_comment_id": item.get("id", ""),
                "body": item.get("text", ""),
                "sender_name": item.get("username", "Unknown"),
                "sender_id": item.get("username", ""),
                "created_at": item.get("timestamp", ""),
                "like_count": item.get("like_count", 0),
            })
        return comments
