import aiohttp
from flask import current_app
from . import BasePlatform


class TikTokPlatform(BasePlatform):
    OAUTH_URL = "https://www.tiktok.com/v2/auth/authorize"
    TOKEN_URL = "https://open.tiktokapis.com/v2/oauth/token/"

    async def publish(self, video_url: str, caption: str, access_token: str, **kwargs) -> dict:
        init_url = "https://open.tiktokapis.com/v2/post/publish/video/init/"
        headers = {"Authorization": f"Bearer {access_token}", "Content-Type": "application/json"}
        payload = {
            "post_info": {"title": caption[:150], "privacy_level": "PUBLIC_TO_EVERYONE"},
            "source_info": {"source": "PULL_FROM_URL", "video_url": video_url},
        }
        async with aiohttp.ClientSession() as session:
            async with session.post(init_url, json=payload, headers=headers) as resp:
                data = await resp.json()
                if data.get("data", {}).get("publish_id"):
                    return {"status": "published", "post_id": data["data"]["publish_id"]}
                return {"status": "error", "error": str(data)}

    async def get_metrics(self, post_id: str, access_token: str) -> dict:
        return {"views": 0, "likes": 0, "comments": 0, "shares": 0}

    def get_oauth_url(self, redirect_uri: str) -> str:
        client_key = current_app.config.get("TIKTOK_CLIENT_KEY", "")
        return f"{self.OAUTH_URL}?client_key={client_key}&redirect_uri={redirect_uri}&scope=user.info.basic,video.publish&response_type=code"

    async def handle_oauth_callback(self, code: str, redirect_uri: str) -> dict:
        client_key = current_app.config.get("TIKTOK_CLIENT_KEY", "")
        client_secret = current_app.config.get("TIKTOK_CLIENT_SECRET", "")
        async with aiohttp.ClientSession() as session:
            async with session.post(self.TOKEN_URL, data={"client_key": client_key, "client_secret": client_secret, "code": code, "grant_type": "authorization_code", "redirect_uri": redirect_uri}) as resp:
                return await resp.json()
