#!/usr/bin/env python3
"""
SWAPA Video Analytics — One-time YouTube OAuth Authorization
Run this once to grant read-only YouTube Analytics access for the SWAPA channel.
Opens a browser window for you to sign in and approve access, then prints a
refresh token to paste into fetch_video_stats.py.

Usage:
  python3 get_youtube_oauth_token.py
"""

import json
import urllib.parse
import urllib.request
import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer

CLIENT_ID     = "1057465255011-947k71f2ijnlb1uehabc1ckqu2u4mbnq.apps.googleusercontent.com"
CLIENT_SECRET = "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"
SCOPE         = "https://www.googleapis.com/auth/yt-analytics.readonly"
PORT          = 8090
REDIRECT_URI  = f"http://localhost:{PORT}/"

received_code = {}

class CallbackHandler(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass  # quiet

    def do_GET(self):
        parsed = urllib.parse.urlparse(self.path)
        params = urllib.parse.parse_qs(parsed.query)
        self.send_response(200)
        self.send_header("Content-Type", "text/html")
        self.end_headers()
        if "code" in params:
            received_code["code"] = params["code"][0]
            self.wfile.write(b"<html><body><h2>Authorized. You can close this tab and return to the terminal.</h2></body></html>")
        else:
            error = params.get("error", ["unknown error"])[0]
            self.wfile.write(f"<html><body><h2>Authorization failed: {error}</h2></body></html>".encode())

def get_authorization_code():
    params = urllib.parse.urlencode({
        "client_id":     CLIENT_ID,
        "redirect_uri":  REDIRECT_URI,
        "response_type": "code",
        "scope":         SCOPE,
        "access_type":   "offline",
        "prompt":        "consent",
    })
    auth_url = f"https://accounts.google.com/o/oauth2/v2/auth?{params}"
    print(f"Opening browser for authorization:\n  {auth_url}\n")
    webbrowser.open(auth_url)

    server = HTTPServer(("localhost", PORT), CallbackHandler)
    print(f"Waiting for you to sign in and approve access (listening on {REDIRECT_URI})...")
    while "code" not in received_code:
        server.handle_request()
    server.server_close()
    return received_code["code"]

def exchange_code_for_tokens(code):
    data = urllib.parse.urlencode({
        "code":          code,
        "client_id":     CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "redirect_uri":  REDIRECT_URI,
        "grant_type":    "authorization_code",
    }).encode()
    req = urllib.request.Request("https://oauth2.googleapis.com/token", data=data)
    req.add_header("Content-Type", "application/x-www-form-urlencoded")
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.loads(r.read())

def main():
    code = get_authorization_code()
    print("\nAuthorization code received. Exchanging for tokens...")
    tokens = exchange_code_for_tokens(code)

    if "refresh_token" not in tokens:
        print("\n⚠ No refresh_token in response:", tokens)
        print("This usually means you've authorized before without revoking access.")
        print("Fix: go to https://myaccount.google.com/permissions, remove access for")
        print("'SWAPA Video Analytics', then run this script again.")
        return

    print("\n✓ Success. Here is your refresh token:\n")
    print(f"  {tokens['refresh_token']}\n")
    print("Send this back so it can be added to fetch_video_stats.py.")
    print("(This token does not expire and should be kept private, like the other API keys in this project.)")

if __name__ == "__main__":
    main()
