"""
Google APIs for Eden - Simplified and Working
"""
import os
import pickle
from pathlib import Path

# Try to import Google libraries
try:
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from googleapiclient.discovery import build
    GOOGLE_AVAILABLE = True
except:
    GOOGLE_AVAILABLE = False

class EdenGoogleAPIs:
    def __init__(self):
        self.gmail = None
        self.drive = None
        self.calendar = None
        
        if not GOOGLE_AVAILABLE:
            print("🔍 Google APIs (libraries not installed)")
            return
        
        token_path = Path("/Eden/CORE/phi_fractal/token.pickle")
        
        if not token_path.exists():
            print("🔍 Google APIs (no token found)")
            return
        
        try:
            # Load token
            with open(token_path, 'rb') as f:
                creds = pickle.load(f)
            
            # Refresh if needed
            if creds.expired and creds.refresh_token:
                creds.refresh(Request())
                # Save refreshed
                with open(token_path, 'wb') as f:
                    pickle.dump(creds, f)
            
            # Build services
            if creds.valid:
                self.gmail = build('gmail', 'v1', credentials=creds)
                self.drive = build('drive', 'v3', credentials=creds)
                self.calendar = build('calendar', 'v3', credentials=creds)
                print("🔍 Google APIs (Gmail, Drive, Calendar active)")
            else:
                print("🔍 Google APIs (credentials invalid)")
                
        except Exception as e:
            print(f"🔍 Google APIs (error: {str(e)[:50]})")

# Global instance
eden_google = EdenGoogleAPIs()
