"""Calendar event tools — list, get, create, update, delete events."""

from gmeet_mcp_server.client import GMeetClient, CalendarAPIError, CalendarAuthError
from gmeet_mcp_server.config import GMeetConfig


def register_event_tools(app, config: GMeetConfig):
    """Register calendar event tools with the FastMCP app."""

    @app.tool()
    async def gmeet_list_events(max_results: int = 10, time_min: str = "") -> dict:
        """List upcoming events from Google Calendar.

        Returns events from the primary calendar, ordered by start time.
        Events with Google Meet links will include the meet_url field.

        Args:
            max_results: Maximum number of events to return (1-50, default 10).
            time_min: Only show events after this time (ISO 8601 format).
                      Defaults to the current time.
        """
        try:
            max_results = min(max(max_results, 1), 50)
            client = GMeetClient(
                client_id=config.client_id,
                client_secret=config.client_secret,
                refresh_token=config.refresh_token,
            )
            events = client.list_events(
                max_results=max_results,
                time_min=time_min or None,
            )
            return {"success": True, "count": len(events), "events": events}
        except CalendarAuthError as exc:
            return {"error": f"Authentication failed: {exc}"}
        except CalendarAPIError as exc:
            return {"error": f"Calendar API error: {exc}"}
        except Exception as exc:
            return {"error": f"Unexpected error: {exc}"}

    @app.tool()
    async def gmeet_create_event(
        title: str,
        start_time: str,
        duration_minutes: int = 30,
        attendees: str = "",
        description: str = "",
    ) -> dict:
        """Create a Google Calendar event (without a Meet link).

        For creating events WITH a Google Meet link, use gmeet_create_meeting instead.

        Args:
            title: Event title / summary.
            start_time: Start time in ISO 8601 format (e.g., '2025-06-20T10:00:00-07:00').
            duration_minutes: Event duration in minutes (default 30).
            attendees: Comma-separated email addresses. Optional.
            description: Optional event description.
        """
        try:
            client = GMeetClient(
                client_id=config.client_id,
                client_secret=config.client_secret,
                refresh_token=config.refresh_token,
            )
            attendee_list = (
                [e.strip() for e in attendees.split(",") if e.strip()]
                if attendees
                else None
            )
            result = client.create_event(
                title=title,
                start_time=start_time,
                duration_minutes=duration_minutes,
                attendees=attendee_list,
                description=description,
                add_meet_link=False,
            )
            return {"success": True, **result}
        except CalendarAuthError as exc:
            return {"error": f"Authentication failed: {exc}"}
        except CalendarAPIError as exc:
            return {"error": f"Calendar API error: {exc}"}
        except Exception as exc:
            return {"error": f"Unexpected error: {exc}"}

    @app.tool()
    async def gmeet_update_event(event_id: str, updates_json: str) -> dict:
        """Update an existing calendar event.

        Args:
            event_id: Google Calendar event ID.
            updates_json: JSON string of fields to update.
                          Supported fields:
                            - title: New event title
                            - description: New description
                            - start_time: New start time (ISO 8601)
                            - end_time: New end time (ISO 8601)
                            - attendees: List of email addresses (replaces existing)
                          Example: '{"title": "New Title", "description": "Updated"}'
        """
        import json

        try:
            if not updates_json:
                return {"error": "No updates provided. Pass a JSON string with fields to update."}
            update_dict = json.loads(updates_json)
            client = GMeetClient(
                client_id=config.client_id,
                client_secret=config.client_secret,
                refresh_token=config.refresh_token,
            )
            result = client.update_event(event_id=event_id, updates=update_dict)
            return {"success": True, "action": "updated", **result}
        except json.JSONDecodeError as exc:
            return {"error": f"Invalid JSON in updates_json: {exc}"}
        except CalendarAuthError as exc:
            return {"error": f"Authentication failed: {exc}"}
        except CalendarAPIError as exc:
            return {"error": f"Calendar API error: {exc}"}
        except Exception as exc:
            return {"error": f"Unexpected error: {exc}"}

    @app.tool()
    async def gmeet_delete_event(event_id: str) -> dict:
        """Delete a calendar event.

        Args:
            event_id: Google Calendar event ID to delete.
        """
        try:
            client = GMeetClient(
                client_id=config.client_id,
                client_secret=config.client_secret,
                refresh_token=config.refresh_token,
            )
            result = client.delete_event(event_id=event_id)
            return {"success": True, "action": "deleted", **result}
        except CalendarAuthError as exc:
            return {"error": f"Authentication failed: {exc}"}
        except CalendarAPIError as exc:
            return {"error": f"Calendar API error: {exc}"}
        except Exception as exc:
            return {"error": f"Unexpected error: {exc}"}

    @app.tool()
    async def gmeet_get_event(event_id: str) -> dict:
        """Get details of a specific calendar event including its Google Meet link.

        Args:
            event_id: Google Calendar event ID.
        """
        try:
            client = GMeetClient(
                client_id=config.client_id,
                client_secret=config.client_secret,
                refresh_token=config.refresh_token,
            )
            result = client.get_event(event_id=event_id)
            return {"success": True, **result}
        except CalendarAuthError as exc:
            return {"error": f"Authentication failed: {exc}"}
        except CalendarAPIError as exc:
            return {"error": f"Calendar API error: {exc}"}
        except Exception as exc:
            return {"error": f"Unexpected error: {exc}"}
