import aiohttp
from flask import current_app
from . import BasePlatform


class FacebookPlatform(BasePlatform):
    GRAPH_URL = "https://graph.facebook.com/v18.0"

    async def publish(self, video_url: str, caption: str, access_token: str, **kwargs) -> dict:
        page_id = kwargs.get("page_id", "me")
        url = f"{self.GRAPH_URL}/{page_id}/videos"
        async with aiohttp.ClientSession() as session:
            async with session.post(url, data={"file_url": video_url, "description": caption, "access_token": access_token}) as resp:
                data = await resp.json()
                if data.get("id"):
                    return {"status": "published", "post_id": data["id"], "post_url": f"https://facebook.com/{data['id']}"}
                return {"status": "error", "error": str(data)}

    async def get_metrics(self, post_id: str, access_token: str) -> dict:
        url = f"{self.GRAPH_URL}/{post_id}/insights?metric=post_video_views,post_reactions_by_type_total&access_token={access_token}"
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as resp:
                data = await resp.json()
                return {"views": 0, "likes": 0, "comments": 0, "shares": 0}

    def get_oauth_url(self, redirect_uri: str) -> str:
        app_id = current_app.config.get("FACEBOOK_APP_ID", "")
        return f"https://www.facebook.com/v18.0/dialog/oauth?client_id={app_id}&redirect_uri={redirect_uri}&scope=pages_manage_posts,pages_read_engagement"

    async def handle_oauth_callback(self, code: str, redirect_uri: str) -> dict:
        app_id = current_app.config.get("FACEBOOK_APP_ID", "")
        app_secret = current_app.config.get("FACEBOOK_APP_SECRET", "")
        url = f"{self.GRAPH_URL}/oauth/access_token?client_id={app_id}&client_secret={app_secret}&redirect_uri={redirect_uri}&code={code}"
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as resp:
                return await resp.json()


class InstagramPlatform(BasePlatform):
    GRAPH_URL = "https://graph.facebook.com/v18.0"

    async def publish(self, video_url: str, caption: str, access_token: str, **kwargs) -> dict:
        ig_user_id = kwargs.get("ig_user_id", "")
        container_url = f"{self.GRAPH_URL}/{ig_user_id}/media"
        async with aiohttp.ClientSession() as session:
            async with session.post(container_url, data={"video_url": video_url, "caption": caption, "media_type": "REELS", "access_token": access_token}) as resp:
                data = await resp.json()
                container_id = data.get("id")
                if not container_id:
                    return {"status": "error", "error": str(data)}
            publish_url = f"{self.GRAPH_URL}/{ig_user_id}/media_publish"
            async with session.post(publish_url, data={"creation_id": container_id, "access_token": access_token}) as resp:
                data = await resp.json()
                if data.get("id"):
                    return {"status": "published", "post_id": data["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}

    def get_oauth_url(self, redirect_uri: str) -> str:
        return FacebookPlatform().get_oauth_url(redirect_uri)

    async def handle_oauth_callback(self, code: str, redirect_uri: str) -> dict:
        return await FacebookPlatform().handle_oauth_callback(code, redirect_uri)
