import aiohttp
from flask import current_app
from . import BasePlatform


class TwitterPlatform(BasePlatform):
    API_URL = "https://api.twitter.com/2"
    UPLOAD_URL = "https://upload.twitter.com/1.1/media/upload.json"

    async def publish(self, video_url: str, caption: str, access_token: str, **kwargs) -> dict:
        async with aiohttp.ClientSession() as session:
            headers = {"Authorization": f"Bearer {access_token}", "Content-Type": "application/json"}
            payload = {"text": caption[:280]}
            async with session.post(f"{self.API_URL}/tweets", json=payload, headers=headers) as resp:
                data = await resp.json()
                tweet_id = data.get("data", {}).get("id")
                if tweet_id:
                    return {"status": "published", "post_id": tweet_id, "post_url": f"https://x.com/i/status/{tweet_id}"}
                return {"status": "error", "error": str(data)}

    async def get_metrics(self, post_id: str, access_token: str) -> dict:
        url = f"{self.API_URL}/tweets/{post_id}?tweet.fields=public_metrics"
        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers={"Authorization": f"Bearer {access_token}"}) as resp:
                data = await resp.json()
                metrics = data.get("data", {}).get("public_metrics", {})
                return {"views": metrics.get("impression_count", 0), "likes": metrics.get("like_count", 0), "comments": metrics.get("reply_count", 0), "shares": metrics.get("retweet_count", 0)}

    def get_oauth_url(self, redirect_uri: str) -> str:
        client_id = current_app.config.get("X_API_KEY", "")
        return f"https://twitter.com/i/oauth2/authorize?response_type=code&client_id={client_id}&redirect_uri={redirect_uri}&scope=tweet.read%20tweet.write%20users.read%20offline.access&state=state&code_challenge=challenge&code_challenge_method=plain"

    async def handle_oauth_callback(self, code: str, redirect_uri: str) -> dict:
        client_id = current_app.config.get("X_API_KEY", "")
        client_secret = current_app.config.get("X_API_SECRET", "")
        async with aiohttp.ClientSession() as session:
            async with session.post("https://api.twitter.com/2/oauth2/token", data={"code": code, "grant_type": "authorization_code", "client_id": client_id, "redirect_uri": redirect_uri, "code_verifier": "challenge"}, auth=aiohttp.BasicAuth(client_id, client_secret)) as resp:
                return await resp.json()
