#!/usr/bin/env python3
"""
Direct Google Calendar API integration
Requires: pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client
"""
import json
import os
import sys
from pathlib import Path

try:
    from google.oauth2.credentials import Credentials
    from google.auth.transport.requests import Request
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
except ImportError:
    print("❌ Missing dependencies. Install with:")
    print("   pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client")
    sys.exit(1)

# Configuration
SCOPES = ['https://www.googleapis.com/auth/calendar']
EVENTS_FILE = '/home/serhii/stack/scrum/repo/docs/calendar_events_s1.json'
TOKEN_FILE = '/home/serhii/.config/google_calendar_token.json'
CREDENTIALS_FILE = '/home/serhii/.config/google_calendar_credentials.json'

def get_credentials():
    """Get valid user credentials from storage or OAuth flow"""
    creds = None
    
    # Check if token file exists
    if os.path.exists(TOKEN_FILE):
        creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
    
    # If no valid credentials, need to authenticate
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            print("❌ No valid credentials found.")
            print("\n📌 To authenticate:")
            print("1. Go to https://console.cloud.google.com/")
            print("2. Create OAuth 2.0 credentials")
            print("3. Download credentials.json")
            print(f"4. Save it to: {CREDENTIALS_FILE}")
            print("5. Run this script again")
            return None
        
        # Save credentials for next run
        with open(TOKEN_FILE, 'w') as token:
            token.write(creds.to_json())
    
    return creds

def create_events(service, events):
    """Create calendar events"""
    created_count = 0
    
    for event in events:
        try:
            created_event = service.events().insert(
                calendarId='primary',
                body=event
            ).execute()
            
            print(f"✅ Created: {event['summary']}")
            print(f"   🔗 {created_event.get('htmlLink')}")
            created_count += 1
            
        except HttpError as error:
            print(f"❌ Error creating event: {error}")
    
    return created_count

def main():
    print("📅 Google Calendar Direct Push")
    print("="*60)
    
    # Load events
    if not os.path.exists(EVENTS_FILE):
        print(f"❌ Events file not found: {EVENTS_FILE}")
        return
    
    with open(EVENTS_FILE, 'r') as f:
        events = json.load(f)
    
    print(f"📋 Loaded {len(events)} events")
    
    # Get credentials
    creds = get_credentials()
    if not creds:
        return
    
    # Build service
    try:
        service = build('calendar', 'v3', credentials=creds)
        print("✅ Connected to Google Calendar API")
    except Exception as e:
        print(f"❌ Failed to connect: {e}")
        return
    
    # Create events
    print("\n🚀 Creating events...")
    created = create_events(service, events)
    
    print("\n" + "="*60)
    print(f"✅ Successfully created {created}/{len(events)} events")
    print("="*60)

if __name__ == '__main__':
    main()
