#!/usr/bin/env python3
"""Check Assaf's Google Calendar for upcoming events and output summary."""
import json, os, sys
from datetime import datetime, timedelta, timezone
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

TOKEN_PATH = '/root/.openclaw/workspace/google-auth/token.json'

def get_service():
    with open(TOKEN_PATH) as f:
        d = json.load(f)
    creds = Credentials(
        token=d.get('access_token'),
        refresh_token=d.get('refresh_token'),
        token_uri='https://oauth2.googleapis.com/token',
        client_id=d['client_id'],
        client_secret=d['client_secret'],
    )
    return build('calendar', 'v3', credentials=creds)

def main():
    service = get_service()
    now = datetime.now(timezone.utc)
    end = now + timedelta(hours=24)
    
    events_result = service.events().list(
        calendarId='primary',
        timeMin=now.isoformat(),
        timeMax=end.isoformat(),
        maxResults=20,
        singleEvents=True,
        orderBy='startTime'
    ).execute()
    
    events = events_result.get('items', [])
    
    if not events:
        print("NO_UPCOMING_EVENTS")
        return
    
    print(f"UPCOMING_EVENTS:{len(events)}")
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        summary = event.get('summary', '(No title)')
        location = event.get('location', '')
        attendees = event.get('attendees', [])
        attendee_names = [a.get('displayName', a.get('email', '?')) for a in attendees[:5]]
        
        print(f"  📅 {summary}")
        print(f"     Time: {start}")
        if location:
            print(f"     Location: {location}")
        if attendee_names:
            print(f"     With: {', '.join(attendee_names)}")
        print()

if __name__ == '__main__':
    main()
