import aiohttp
from flask import current_app
from . import BasePlatform


class YouTubePlatform(BasePlatform):
    OAUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"
    TOKEN_URL = "https://oauth2.googleapis.com/token"
    UPLOAD_URL = "https://www.googleapis.com/upload/youtube/v3/videos"
    
    async def publish(self, video_url: str, caption: str, access_token: str, **kwargs) -> dict:
        title = kwargs.get("title", "Promotional Video")
        async with aiohttp.ClientSession() as session:
            async with session.get(video_url) as vresp:
                video_data = await vresp.read()
            
            headers = {
                "Authorization": f"Bearer {access_token}",
                "Content-Type": "application/octet-stream",
            }
            params = {
                "uploadType": "media",
                "part": "snippet,status",
            }
            metadata = {
                "snippet": {"title": title, "description": caption, "categoryId": "22"},
                "status": {"privacyStatus": "public"},
            }
            async with session.post(self.UPLOAD_URL, params=params, headers=headers, data=video_data) as resp:
                if resp.status in (200, 201):
                    data = await resp.json()
                    return {"status": "published", "post_id": data.get("id"), "post_url": f"https://youtube.com/watch?v={data.get('id')}"}
                return {"status": "error", "error": await resp.text()}

    async def get_metrics(self, post_id: str, access_token: str) -> dict:
        url = f"https://www.googleapis.com/youtube/v3/videos?part=statistics&id={post_id}"
        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers={"Authorization": f"Bearer {access_token}"}) as resp:
                data = await resp.json()
                stats = data.get("items", [{}])[0].get("statistics", {})
                return {"views": int(stats.get("viewCount", 0)), "likes": int(stats.get("likeCount", 0)), "comments": int(stats.get("commentCount", 0))}

    def get_oauth_url(self, redirect_uri: str) -> str:
        client_id = current_app.config.get("YOUTUBE_CLIENT_ID", "")
        return f"{self.OAUTH_URL}?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code&scope=https://www.googleapis.com/auth/youtube.upload&access_type=offline"

    async def handle_oauth_callback(self, code: str, redirect_uri: str) -> dict:
        client_id = current_app.config.get("YOUTUBE_CLIENT_ID", "")
        client_secret = current_app.config.get("YOUTUBE_CLIENT_SECRET", "")
        async with aiohttp.ClientSession() as session:
            async with session.post(self.TOKEN_URL, data={"code": code, "client_id": client_id, "client_secret": client_secret, "redirect_uri": redirect_uri, "grant_type": "authorization_code"}) as resp:
                return await resp.json()
