import os
import json
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from agent.oauth_store import get_credentials

def execute(inputs: dict) -> dict:
    user_id = os.environ.get("USER_ID")
    if not user_id:
        return {"error": "Authentication required. No user_id found in environment."}

    creds_dict = get_credentials(user_id)
    if not creds_dict:
        return {"error": "Google Calendar is not connected. Please ask the user to click 'Connect Google Calendar' in the sidebar."}

    try:
        creds = Credentials(
            token=creds_dict.get('token'),
            refresh_token=creds_dict.get('refresh_token'),
            token_uri=creds_dict.get('token_uri'),
            client_id=creds_dict.get('client_id'),
            client_secret=creds_dict.get('client_secret'),
            scopes=creds_dict.get('scopes')
        )
        
        service = build('calendar', 'v3', credentials=creds)
        action = inputs.get('action')
        
        if action == "create":
            if not inputs.get('summary') or not inputs.get('start_time') or not inputs.get('end_time'):
                return {"error": "Missing required fields for create: summary, start_time, end_time"}
                
            event = {
                'summary': inputs['summary'],
                'description': inputs.get('description', ''),
                'start': {
                    'dateTime': inputs['start_time'],
                },
                'end': {
                    'dateTime': inputs['end_time'],
                },
            }
            
            event_res = service.events().insert(calendarId='primary', body=event).execute()
            return {"message": "Event created successfully.", "event_id": event_res.get('id'), "link": event_res.get('htmlLink')}
            
        elif action == "update":
            event_id = inputs.get('event_id')
            if not event_id:
                return {"error": "Missing required field: event_id"}
                
            # Fetch existing to patch it
            event = service.events().get(calendarId='primary', eventId=event_id).execute()
            
            if inputs.get('summary'): event['summary'] = inputs['summary']
            if inputs.get('description'): event['description'] = inputs['description']
            if inputs.get('start_time'): event['start']['dateTime'] = inputs['start_time']
            if inputs.get('end_time'): event['end']['dateTime'] = inputs['end_time']
            
            event_res = service.events().update(calendarId='primary', eventId=event_id, body=event).execute()
            return {"message": "Event updated successfully.", "event_id": event_res.get('id'), "link": event_res.get('htmlLink')}
            
        elif action == "delete":
            event_id = inputs.get('event_id')
            if not event_id:
                return {"error": "Missing required field: event_id"}
                
            service.events().delete(calendarId='primary', eventId=event_id).execute()
            return {"message": f"Event {event_id} deleted successfully."}
            
        else:
            return {"error": f"Unknown action: {action}"}
            
    except Exception as e:
        return {"error": f"Failed to manage calendar event: {str(e)}"}
