"""
TikTok Provider  
Ported & adapted từ BrightBean Studio providers/tiktok.py
Simplified cho Canifa use case: publish fashion video + đọc comments
"""

from __future__ import annotations

import logging
import os

from .base import SocialProvider, APIError

logger = logging.getLogger(__name__)

TIKTOK_API_BASE = "https://open.tiktokapis.com/v2"

TIKTOK_CLIENT_KEY = os.getenv("TIKTOK_CLIENT_KEY", "")
TIKTOK_CLIENT_SECRET = os.getenv("TIKTOK_CLIENT_SECRET", "")


class TikTokProvider(SocialProvider):
    """
    TikTok provider — publish video + đọc comments.
    Dùng cho: Canifa auto-post fashion reels/videos lên TikTok.
    """

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

    def get_profile(self, access_token: str) -> dict:
        """Lấy thông tin TikTok user."""
        response = self._request(
            "GET",
            f"{TIKTOK_API_BASE}/user/info/",
            access_token=access_token,
            params={
                "fields": "open_id,union_id,display_name,avatar_url,follower_count,following_count,likes_count",
            },
        )
        return response.json().get("data", {}).get("user", {})

    def publish_post(self, access_token: str, content: dict) -> dict:
        """
        Publish TikTok video.
        TikTok cần video_url và dùng Content Posting API.
        content = {
            "title": str,          ← caption/title
            "video_url": str,      ← direct link tới video file
            "privacy": str,        ← "PUBLIC" | "FRIENDS" | "PRIVATE"
        }
        """
        # TikTok direct post via URL
        payload = {
            "post_info": {
                "title": content.get("title", ""),
                "privacy_level": content.get("privacy", "PUBLIC_TO_EVERYONE"),
                "disable_duet": False,
                "disable_comment": False,
                "disable_stitch": False,
            },
            "source_info": {
                "source": "PULL_FROM_URL",
                "video_url": content.get("video_url", ""),
            },
        }
        response = self._request(
            "POST",
            f"{TIKTOK_API_BASE}/post/publish/video/init/",
            access_token=access_token,
            json=payload,
        )
        data = response.json().get("data", {})
        return {
            "post_id": data.get("publish_id", ""),
            "success": True,
            "platform": "tiktok",
        }

    def get_comments(self, access_token: str, post_id: str) -> list[dict]:
        """Lấy comments của một TikTok video."""
        response = self._request(
            "POST",
            f"{TIKTOK_API_BASE}/video/comment/list/",
            access_token=access_token,
            json={
                "video_id": post_id,
                "max_count": 100,
            },
        )
        data = response.json().get("data", {})
        comments = []
        for item in data.get("comments", []):
            comments.append({
                "platform_comment_id": item.get("id", ""),
                "body": item.get("text", ""),
                "sender_name": item.get("display_name", "Unknown"),
                "sender_id": item.get("open_id", ""),
                "created_at": str(item.get("create_time", "")),
                "like_count": item.get("like_count", 0),
            })
        return comments
