#!/usr/bin/env python3
"""Google Calendar CLI for creating events with Google Meet."""

import argparse
import json
import sys
from datetime import datetime, timedelta
from pathlib import Path

# Google API imports
try:
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
except ImportError:
    print("Error: Google API libraries not installed.")
    sys.exit(1)

# Calendar API scopes - including write permissions
SCOPES = [
    'https://www.googleapis.com/auth/calendar',
]

# Config paths - using 'cos.json' as mentioned in HEARTBEAT.md
CONFIG_DIR = Path.home() / '.clawdbot' / 'skills' / 'gmail'
TOKENS_DIR = CONFIG_DIR / 'tokens'
CREDENTIALS_FILE = CONFIG_DIR / 'credentials.json'
COS_TOKEN = TOKENS_DIR / 'cos.json'


def get_credentials():
    """Get or refresh credentials for Calendar API."""
    creds = None
    
    if COS_TOKEN.exists():
        creds = Credentials.from_authorized_user_file(str(COS_TOKEN), SCOPES)
    
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            if not CREDENTIALS_FILE.exists():
                print(f"Error: No credentials file at {CREDENTIALS_FILE}")
                sys.exit(1)
            flow = InstalledAppFlow.from_client_secrets_file(str(CREDENTIALS_FILE), SCOPES)
            creds = flow.run_local_server(port=0)
        
        with open(COS_TOKEN, 'w') as f:
            f.write(creds.to_json())
    
    return creds


def create_event(title, start_time, duration_minutes=30, attendees=None, description="", location=""):
    """Create a calendar event with Google Meet."""
    creds = get_credentials()
    service = build('calendar', 'v3', credentials=creds)
    
    # Parse start time
    if isinstance(start_time, str):
        # Assume format like "2026-01-27 11:30" in Lisbon time
        start_dt = datetime.strptime(start_time, '%Y-%m-%d %H:%M')
    else:
        start_dt = start_time
    
    end_dt = start_dt + timedelta(minutes=duration_minutes)
    
    event = {
        'summary': title,
        'description': description,
        'start': {
            'dateTime': start_dt.isoformat(),
            'timeZone': 'Europe/Lisbon',
        },
        'end': {
            'dateTime': end_dt.isoformat(),
            'timeZone': 'Europe/Lisbon',
        },
        'conferenceData': {
            'createRequest': {
                'requestId': f"meet-{int(datetime.now().timestamp())}",
                'conferenceSolutionKey': {
                    'type': 'hangoutsMeet'
                }
            }
        },
        'reminders': {
            'useDefault': False,
            'overrides': [
                {'method': 'email', 'minutes': 24 * 60},  # 1 day before
                {'method': 'popup', 'minutes': 10},       # 10 minutes before
            ],
        },
    }
    
    if attendees:
        event['attendees'] = [{'email': email} for email in attendees]
    
    if location:
        event['location'] = location
    
    try:
        event = service.events().insert(
            calendarId='primary',
            body=event,
            conferenceDataVersion=1,
            sendUpdates='all'  # Send invites to all attendees
        ).execute()
        
        print(f"✅ Event created: {event['summary']}")
        print(f"📅 Time: {start_dt.strftime('%A, %B %d at %I:%M %p')} (Lisbon)")
        
        if 'conferenceData' in event and 'entryPoints' in event['conferenceData']:
            for entry in event['conferenceData']['entryPoints']:
                if entry['entryPointType'] == 'video':
                    print(f"📞 Google Meet: {entry['uri']}")
                    break
        
        if attendees:
            print(f"👥 Attendees: {', '.join(attendees)}")
        
        print(f"🔗 Calendar link: {event['htmlLink']}")
        
        return event
        
    except HttpError as error:
        print(f'Calendar API error: {error}')
        sys.exit(1)


def main():
    parser = argparse.ArgumentParser(description='Create Google Calendar events')
    parser.add_argument('--title', required=True, help='Event title')
    parser.add_argument('--time', required=True, help='Start time (YYYY-MM-DD HH:MM)')
    parser.add_argument('--duration', type=int, default=30, help='Duration in minutes')
    parser.add_argument('--attendees', help='Comma-separated email list')
    parser.add_argument('--description', default='', help='Event description')
    parser.add_argument('--location', default='', help='Event location')
    
    args = parser.parse_args()
    
    attendees = []
    if args.attendees:
        attendees = [email.strip() for email in args.attendees.split(',')]
    
    create_event(
        title=args.title,
        start_time=args.time,
        duration_minutes=args.duration,
        attendees=attendees,
        description=args.description,
        location=args.location
    )


if __name__ == '__main__':
    main()