import httpx
import json

from common import logging

logger = logging.get_logger(__name__)


class YouTubePublisher:
    @staticmethod
    async def initiate_youtube_upload(
        access_token: str, title: str, description: str, video_size: int
    ) -> str:
        """
        Step 1: Initiate a resumable upload session with YouTube and get the upload URL
        """
        url = "https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet%2Cstatus"

        headers = {
            "Authorization": f"Bearer {access_token}",
            "Content-Type": "application/json",
            "X-Upload-Content-Length": f"{video_size}",
            "Content-range": "",
        }

        payload = {
            "part": "snippet,status,recordingDetails",
            "snippet": {
                "title": title,
                "description": description,
                "tags": [
                    "tldr",
                    "clipThat",
                    "tldrClip",
                    "Gaming",
                    "Games",
                    "Streaming",
                ],
                "categoryId": "20",
                "defaultLanguage": "en",
                "defaultAudioLanguage": "en",
            },
            "status": {"privacyStatus": "public", "selfDeclaredMadeForKids": False},
        }

        async with httpx.AsyncClient() as client:
            response = await client.post(
                url, headers=headers, content=json.dumps(payload)
            )
            response.raise_for_status()
            upload_url = response.headers.get("Location")
            return upload_url

    @staticmethod
    async def upload_video_to_youtube(
        upload_url: str, video_size: int, video_bytes: bytes
    ) -> None:
        """
        Upload the actual video file to the provided resumable upload URL.
        Downloads from `video_url` and uploads to YouTube.
        """
        headers = {
            "Content-Length": str(video_size),
            "Content-Type": "video/mp4",
            "Content-Range": f"bytes 0-{video_size - 1}/{video_size}",
        }

        async with httpx.AsyncClient(timeout=None) as client:
            try:
                put_response = await client.put(
                    upload_url, headers=headers, content=video_bytes
                )
                put_response.raise_for_status()

                logger.info("[YouTube] Upload completed successfully.")

            except httpx.HTTPStatusError as e:
                logger.error(
                    f"[YouTube] Upload failed with status {e.response.status_code}: {e.response.text}"
                )
                raise
            except Exception as e:
                logger.error(f"[YouTube] Unexpected error during upload: {e}")
                raise
