#!/usr/bin/env python3

import os
import json
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# Path to your client secret file
CLIENT_SECRET_FILE = os.path.expanduser('~/.openclaw/secret/client_secret_1045917636561-fnpb5mpvpfkcte2t4ho62adt4qqubgvp.apps.googleusercontent.com.json')

# Scopes for the APIs you want to access
SCOPES = [
    'https://www.googleapis.com/auth/calendar',
    'https://www.googleapis.com/auth/gmail.readonly',
    'https://www.googleapis.com/auth/drive.readonly'
]

def setup_oauth():
    """Set up OAuth 2.0 flow for Google APIs."""
    print("Setting up Google API authentication...")
    
    # Load client secrets
    with open(CLIENT_SECRET_FILE, 'r') as f:
        client_config = json.load(f)
    
    # Create flow instance
    flow = InstalledAppFlow.from_client_config(client_config, SCOPES)
    
    # Run the flow to get credentials
    # This will open a browser window for authentication
    creds = flow.run_local_server(port=8080)
    
    print("Authentication successful!")
    print("You can now access Google services with the granted permissions.")
    
    # Test accessing a service
    try:
        # Test Gmail
        gmail_service = build('gmail', 'v1', credentials=creds)
        profile = gmail_service.users().getProfile(userId='me').execute()
        print(f"Gmail connected! Email: {profile['emailAddress']}")
    except Exception as e:
        print(f"Gmail test failed: {e}")
    
    try:
        # Test Calendar
        calendar_service = build('calendar', 'v3', credentials=creds)
        calendars = calendar_service.calendarList().list().execute()
        print(f"Calendar connected! Found {len(calendars.get('items', []))} calendars")
    except Exception as e:
        print(f"Calendar test failed: {e}")

if __name__ == "__main__":
    setup_oauth()