#!/usr/bin/env python3
"""OAuth flow for Gmail API — console-based for headless/remote setups."""

import json
import os
from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = [
    'https://www.googleapis.com/auth/gmail.readonly',
    'https://www.googleapis.com/auth/gmail.send',
    'https://www.googleapis.com/auth/gmail.modify',
]

DIR = os.path.dirname(os.path.abspath(__file__))
CLIENT_SECRET = os.path.join(DIR, 'gmail_oauth_client.json')
TOKEN_FILE = os.path.join(DIR, 'gmail_token.json')

flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET, SCOPES)

# Run local server on localhost — Khaleb needs to open URL in Mac mini's browser
creds = flow.run_local_server(
    host='localhost',
    port=8089,
    open_browser=True,
)

token_data = {
    'token': creds.token,
    'refresh_token': creds.refresh_token,
    'token_uri': creds.token_uri,
    'client_id': creds.client_id,
    'client_secret': creds.client_secret,
    'scopes': list(creds.scopes),
}

with open(TOKEN_FILE, 'w') as f:
    json.dump(token_data, f, indent=2)

print(f'✅ Token saved to {TOKEN_FILE}')
print(f'Scopes: {", ".join(creds.scopes)}')
