#!/usr/bin/env python3
from playwright.sync_api import sync_playwright
import json, subprocess, sys, time

def get_auth_code():
    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=False,
            args=['--no-sandbox','--disable-dev-shm-usage',
                  f'--user-data-dir=/home/claw/.config/google-chrome-lola',
                  '--profile-directory=Default']
        )
        context = browser.contexts[0]
        page = context.new_page()
        
        oauth_url = (
            "https://accounts.google.com/o/oauth2/v2/auth"
            "?client_id=202264815644.apps.googleusercontent.com"
            "&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob"
            "&response_type=code"
            "&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.file"
            "&access_type=offline"
            "&prompt=consent"
        )
        page.goto(oauth_url)
        page.wait_for_timeout(5000)
        
        # Wait for user to interact
        print("Waiting for OAuth consent page...", flush=True)
        page.wait_for_url("**/oauth2approval**", timeout=120000)
        url = page.url
        print(f"Got code URL: {url}", flush=True)
        
        # Extract the code from the URL fragment
        code = None
        if "code=" in url:
            code = url.split("code=")[1].split("&")[0]
        elif "#code=" in url:
            code = url.split("#code=")[1].split("&")[0]
        
        browser.close()
        return code

def exchange_code(code):
    """Exchange the code for tokens using curl"""
    cmd = [
        "curl", "-s", "-X", "POST",
        "https://oauth2.googleapis.com/token",
        "-H", "Content-Type: application/x-www-form-urlencoded",
        "-d", f"code={code}&client_id=202264815644.apps.googleusercontent.com&client_secret=GOCSPX-xxx&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&grant_type=authorization_code"
    ]
    result = subprocess.run(cmd, capture_output=True, text=True)
    print(f"Token response: {result.stdout[:200]}", flush=True)
    return json.loads(result.stdout)

if __name__ == "__main__":
    code = get_auth_code()
    print(f"Authorization code: {code[:30]}...", flush=True)