"""
Google Calendar Tools
MCP tools for Google Calendar operations
"""

import logging
from typing import List, Dict, Any, Optional
from datetime import datetime, timedelta
from src.providers.google_calendar.mcp_instance import tool
from src.providers.google_calendar.api.calendar import GoogleCalendarAPI

logger = logging.getLogger(__name__)

# Initialize the API
calendar_api = GoogleCalendarAPI()

@tool
def list_calendars() -> List[Dict[str, Any]]:
    """
    List all calendars accessible to the user
    
    Returns:
        List of calendar objects with id, summary, description, etc.
    """
    try:
        calendars = calendar_api.list_calendars()
        logger.info(f"Successfully listed {len(calendars)} calendars")
        return calendars
    except Exception as e:
        logger.error(f"Error listing calendars: {e}")
        return {"error": str(e)}

@tool
def get_calendar(calendar_id: str = 'primary') -> Dict[str, Any]:
    """
    Get details of a specific calendar
    
    Args:
        calendar_id: The ID of the calendar (default: 'primary')
    
    Returns:
        Calendar object with details
    """
    try:
        calendar = calendar_api.get_calendar(calendar_id)
        logger.info(f"Successfully retrieved calendar: {calendar_id}")
        return calendar
    except Exception as e:
        logger.error(f"Error getting calendar {calendar_id}: {e}")
        return {"error": str(e)}

@tool
def create_calendar(summary: str, description: str = "", timezone: str = "UTC") -> Dict[str, Any]:
    """
    Create a new calendar
    
    Args:
        summary: The name/title of the calendar
        description: Optional description of the calendar
        timezone: Timezone for the calendar (default: UTC)
    
    Returns:
        Created calendar object
    """
    try:
        calendar = calendar_api.create_calendar(summary, description, timezone)
        logger.info(f"Successfully created calendar: {summary}")
        return calendar
    except Exception as e:
        logger.error(f"Error creating calendar: {e}")
        return {"error": str(e)}

@tool
def delete_calendar(calendar_id: str) -> Dict[str, Any]:
    """
    Delete a calendar
    
    Args:
        calendar_id: The ID of the calendar to delete
    
    Returns:
        Success/error message
    """
    try:
        result = calendar_api.delete_calendar(calendar_id)
        logger.info(f"Successfully deleted calendar: {calendar_id}")
        return result
    except Exception as e:
        logger.error(f"Error deleting calendar {calendar_id}: {e}")
        return {"error": str(e)}

@tool
def list_events(calendar_id: str = 'primary', max_results: int = 10, 
               time_min: str = None, time_max: str = None) -> List[Dict[str, Any]]:
    """
    List events from a calendar
    
    Args:
        calendar_id: The ID of the calendar (default: 'primary')
        max_results: Maximum number of events to return (default: 10)
        time_min: Start time for events (ISO format, default: now)
        time_max: End time for events (ISO format, default: 7 days from now)
    
    Returns:
        List of event objects
    """
    try:
        events = calendar_api.list_events(calendar_id, max_results, time_min, time_max)
        logger.info(f"Successfully listed {len(events)} events from calendar: {calendar_id}")
        return events
    except Exception as e:
        logger.error(f"Error listing events: {e}")
        return {"error": str(e)}

@tool
def get_event(calendar_id: str, event_id: str) -> Dict[str, Any]:
    """
    Get details of a specific event
    
    Args:
        calendar_id: The ID of the calendar
        event_id: The ID of the event
    
    Returns:
        Event object with details
    """
    try:
        event = calendar_api.get_event(calendar_id, event_id)
        logger.info(f"Successfully retrieved event: {event_id}")
        return event
    except Exception as e:
        logger.error(f"Error getting event {event_id}: {e}")
        return {"error": str(e)}

@tool
def create_event(calendar_id: str = 'primary', summary: str = "", 
                description: str = "", start_time: str = None, end_time: str = None,
                attendees: List[str] = None, location: str = "") -> Dict[str, Any]:
    """
    Create a new event
    
    Args:
        calendar_id: The ID of the calendar (default: 'primary')
        summary: Title/summary of the event
        description: Optional description of the event
        start_time: Start time in ISO format (e.g., '2025-07-30T10:00:00Z')
        end_time: End time in ISO format (e.g., '2025-07-30T11:00:00Z')
        attendees: List of email addresses to invite
        location: Location of the event
    
    Returns:
        Created event object
    """
    try:
        event = calendar_api.create_event(calendar_id, summary, description, 
                                        start_time, end_time, attendees, location)
        logger.info(f"Successfully created event: {summary}")
        return event
    except Exception as e:
        logger.error(f"Error creating event: {e}")
        return {"error": str(e)}

@tool
def update_event(calendar_id: str, event_id: str, 
                summary: str = None, description: str = None,
                start_time: str = None, end_time: str = None,
                attendees: List[str] = None, location: str = None) -> Dict[str, Any]:
    """
    Update an existing event
    
    Args:
        calendar_id: The ID of the calendar
        event_id: The ID of the event to update
        summary: New title/summary (optional)
        description: New description (optional)
        start_time: New start time in ISO format (optional)
        end_time: New end time in ISO format (optional)
        attendees: New list of email addresses (optional)
        location: New location (optional)
    
    Returns:
        Updated event object
    """
    try:
        event = calendar_api.update_event(calendar_id, event_id, summary, description,
                                        start_time, end_time, attendees, location)
        logger.info(f"Successfully updated event: {event_id}")
        return event
    except Exception as e:
        logger.error(f"Error updating event {event_id}: {e}")
        return {"error": str(e)}

@tool
def delete_event(calendar_id: str, event_id: str) -> Dict[str, Any]:
    """
    Delete an event
    
    Args:
        calendar_id: The ID of the calendar
        event_id: The ID of the event to delete
    
    Returns:
        Success/error message
    """
    try:
        result = calendar_api.delete_event(calendar_id, event_id)
        logger.info(f"Successfully deleted event: {event_id}")
        return result
    except Exception as e:
        logger.error(f"Error deleting event {event_id}: {e}")
        return {"error": str(e)}

@tool
def search_events(calendar_id: str = 'primary', query: str = "", 
                max_results: int = 10) -> List[Dict[str, Any]]:
    """
    Search for events in a calendar
    
    Args:
        calendar_id: The ID of the calendar (default: 'primary')
        query: Search query string
        max_results: Maximum number of events to return (default: 10)
    
    Returns:
        List of matching event objects
    """
    try:
        events = calendar_api.search_events(calendar_id, query, max_results)
        logger.info(f"Successfully searched for events with query: {query}")
        return events
    except Exception as e:
        logger.error(f"Error searching events: {e}")
        return {"error": str(e)}

@tool
def get_free_busy(calendar_ids: List[str], time_min: str, time_max: str) -> Dict[str, Any]:
    """
    Get free/busy information for calendars
    
    Args:
        calendar_ids: List of calendar IDs to check
        time_min: Start time in ISO format
        time_max: End time in ISO format
    
    Returns:
        Free/busy information for the specified calendars
    """
    try:
        free_busy = calendar_api.get_free_busy(calendar_ids, time_min, time_max)
        logger.info(f"Successfully retrieved free/busy info for {len(calendar_ids)} calendars")
        return free_busy
    except Exception as e:
        logger.error(f"Error getting free/busy info: {e}")
        return {"error": str(e)} 