import json
import os
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# Localhost OAuth callback is http://localhost for installed apps.
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

creds_data = {
  "installed": {
    "client_id": "516279688392-jepimclr1lsb9rg0aehf798s37ua0q9s.apps.googleusercontent.com",
    "project_id": "morpheus-assistant-490521",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "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",
    "redirect_uris": ["http://localhost", "http://localhost:8080/"]
  }
}

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

flow = InstalledAppFlow.from_client_config(creds_data, SCOPES)
flow.redirect_uri = 'http://localhost'
auth_url, _ = flow.authorization_url(
    prompt='consent',
    access_type='offline',
    include_granted_scopes='true'
)

print('1. Go to this URL in your browser:')
print(auth_url)
print('\n2. Sign in, grant access, then copy the full redirect URL (after "localhost?code=...").')
print('3. Paste it below when prompted.')

redirect_url = input('Paste the full redirect URL here: ')
flow.fetch_token(authorization_response=redirect_url)

creds = flow.credentials
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 or []),
}

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

print('\nToken saved to token.json. Test: Fetching recent emails...')
service = build('gmail', 'v1', credentials=creds)
results = service.users().messages().list(userId='me', maxResults=5).execute()
messages = results.get('messages', [])
print(f'Found {len(messages)} recent emails. Success!')
