#!/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 Flow
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 = Flow.from_client_secrets_file(
                str(CREDENTIALS_FILE),
                scopes=SCOPES,
                redirect_uri='urn:ietf:wg:oauth:2.0:oob'
            )
            
            auth_url, _ = flow.authorization_url(prompt='consent')
            
            print("="*60)
            print("AUTHORIZATION REQUIRED")
            print("="*60)
            print("\n1. Open this URL in your browser:\n")
            print(auth_url)
            print("\n2. Sign in and authorize access")
            print("3. Copy the authorization code and paste it below\n")
            
            code = input("Enter authorization code: ").strip()
            
            flow.fetch_token(code=code)
            creds = flow.credentials
        
        # 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()
