#!/usr/bin/env python3
"""
Google Calendar OAuth2 Authorization.
Run this once to generate token.json for calendar access.
"""

import os
from pathlib import Path
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

# Scopes needed for calendar access (read + write events)
SCOPES = ['https://www.googleapis.com/auth/calendar.events']

CREDENTIALS_FILE = Path(__file__).parent.parent / 'credentials' / 'google-calendar.json'
TOKEN_FILE = Path(__file__).parent.parent / 'credentials' / 'google-calendar-token.json'

def main():
    creds = None
    
    # Check if token already exists
    if TOKEN_FILE.exists():
        creds = Credentials.from_authorized_user_file(str(TOKEN_FILE), SCOPES)
    
    # If no valid credentials, do the OAuth flow
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            print("Refreshing expired token...")
            creds.refresh(Request())
        else:
            print(f"Starting OAuth flow...")
            print(f"Using credentials: {CREDENTIALS_FILE}\n")
            
            flow = InstalledAppFlow.from_client_secrets_file(
                str(CREDENTIALS_FILE),
                scopes=SCOPES
            )
            creds = flow.run_local_server(port=0, open_browser=False)
        
        # Save the credentials for next run
        TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True)
        with open(TOKEN_FILE, 'w') as token:
            token.write(creds.to_json())
        print(f"\nToken saved to: {TOKEN_FILE}")
    
    print("\n✅ Authorization successful!")
    print("You can now use the calendar tools.")

if __name__ == '__main__':
    main()
