from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

from app.config import YOUTUBE_CLIENT_SECRET_PATH, YOUTUBE_TOKEN_PATH

SCOPES = ["https://www.googleapis.com/auth/youtube.upload"]


def bootstrap_credentials() -> Credentials:
    flow = InstalledAppFlow.from_client_secrets_file(str(YOUTUBE_CLIENT_SECRET_PATH), SCOPES)
    creds = flow.run_local_server(port=0)
    YOUTUBE_TOKEN_PATH.parent.mkdir(parents=True, exist_ok=True)
    YOUTUBE_TOKEN_PATH.write_text(creds.to_json(), encoding="utf-8")
    return creds


def load_credentials() -> Credentials:
    if not YOUTUBE_TOKEN_PATH.exists():
        raise RuntimeError(
            "YouTube token bulunamadı. Önce 'python scripts/oauth_bootstrap.py' çalıştırılmalı."
        )
    creds = Credentials.from_authorized_user_file(str(YOUTUBE_TOKEN_PATH), SCOPES)
    if creds.expired and creds.refresh_token:
        creds.refresh(Request())
        YOUTUBE_TOKEN_PATH.write_text(creds.to_json(), encoding="utf-8")
    return creds
