"""
Netlify OAuth Ticket Flow - gets a Personal Access Token programmatically.
Uses the Netlify OAuth ticket endpoint to create a ticket, then polls for completion.
"""
import urllib.request
import urllib.parse
import json
import time
import sys

NETLIFY_CLIENT_ID = "5edad8f69d47ae8923d0cf0b4ab8364eae5ce968"  # Netlify CLI client ID (public)

def create_ticket():
    url = f"https://api.netlify.com/oauth/tickets?client_id={NETLIFY_CLIENT_ID}"
    req = urllib.request.Request(url, method="POST", headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req) as resp:
        return json.loads(resp.read())

def poll_ticket(ticket_id):
    url = f"https://api.netlify.com/oauth/tickets/{ticket_id}/exchange"
    req = urllib.request.Request(url, method="POST", headers={"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req) as resp:
            return json.loads(resp.read())
    except urllib.error.HTTPError as e:
        if e.code == 401:
            return None  # Not yet authorized
        raise

def main():
    print("Creating Netlify OAuth ticket...")
    ticket = create_ticket()
    ticket_id = ticket.get("id")
    auth_url = f"https://app.netlify.com/authorize?response_type=ticket&ticket={ticket_id}"
    
    print(f"TICKET_ID: {ticket_id}")
    print(f"AUTH_URL: {auth_url}")
    
    # Poll for up to 5 minutes
    print("Polling for authorization (waiting for browser to complete OAuth)...")
    for i in range(60):
        time.sleep(5)
        result = poll_ticket(ticket_id)
        if result and result.get("access_token"):
            token = result["access_token"]
            print(f"SUCCESS: Got token: {token[:8]}...")
            # Save token
            with open(r"E:\genesis-system\Credentials\netlify_token.txt", "w") as f:
                f.write(token)
            print(f"Token saved to E:\\genesis-system\\Credentials\\netlify_token.txt")
            return token
        print(f"  Attempt {i+1}/60 - waiting for user to authorize in browser...")
    
    print("TIMEOUT: Authorization not completed within 5 minutes")
    return None

if __name__ == "__main__":
    main()
