#!/usr/bin/env python3
import json
import os
from pathlib import Path

from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/calendar']
CLIENT_FILE = os.path.expanduser('~/.openclaw/secrets/google-oauth-client.json')
TOKEN_FILE = os.path.expanduser('~/.openclaw/secrets/google-calendar-personal-token.json')


def load_creds():
    creds = None
    if os.path.exists(TOKEN_FILE):
        creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
    if creds and creds.valid:
        return creds
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
        Path(TOKEN_FILE).write_text(creds.to_json())
        return creds
    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_FILE, SCOPES)
    auth_url, _ = flow.authorization_url(prompt='consent')
    print('Open this URL in your browser:')
    print(auth_url)
    code = input('Paste the authorization code here: ').strip()
    flow.fetch_token(code=code)
    creds = flow.credentials
    Path(TOKEN_FILE).write_text(creds.to_json())
    return creds


def main():
    creds = load_creds()
    service = build('calendar', 'v3', credentials=creds, cache_discovery=False)
    profile = service.calendarList().list(maxResults=1).execute()
    print('OAuth ready')
    print('token_file:', TOKEN_FILE)
    print('calendar_count_sample:', len(profile.get('items', [])))


if __name__ == '__main__':
    main()
