import { z } from "zod";
import { tool } from "@anthropic-ai/claude-agent-sdk";
import { GoogleCalendarClient } from "../calendar/google-calendar.js";
import { getAgentState } from "../agent/state.js";
export const manageCalendarTool = tool("manage_calendar", "Manage your Google Calendar. Create, update, delete, and list calendar events. Use this to schedule tasks, set reminders, and manage your time.", {
    action: z
        .enum([
        "create_event",
        "update_event",
        "delete_event",
        "list_events",
        "find_free_time",
    ])
        .describe("Calendar action to perform"),
    summary: z
        .string()
        .optional()
        .describe("Event title/summary (for create_event, update_event)"),
    description: z
        .string()
        .optional()
        .describe("Event description (for create_event, update_event)"),
    start: z
        .string()
        .optional()
        .describe("Start date/time in ISO 8601 format (for create_event, update_event, list_events, find_free_time)"),
    end: z
        .string()
        .optional()
        .describe("End date/time in ISO 8601 format (for create_event, update_event, list_events, find_free_time)"),
    event_id: z
        .string()
        .optional()
        .describe("Event ID (for update_event, delete_event)"),
    recurrence: z
        .string()
        .optional()
        .describe("RRULE recurrence string (for create_event, e.g. 'RRULE:FREQ=WEEKLY;BYDAY=MO')"),
    max_results: z
        .number()
        .optional()
        .describe("Maximum number of events to return (for list_events)"),
    attendees: z
        .array(z.string())
        .optional()
        .describe("List of attendee email addresses to invite (for create_event, update_event). Invitation emails are sent automatically."),
}, async (args) => {
    try {
        const state = getAgentState();
        const client = new GoogleCalendarClient(state.config);
        switch (args.action) {
            case "create_event": {
                if (!args.summary || !args.start || !args.end) {
                    return {
                        content: [
                            {
                                type: "text",
                                text: "Error: summary, start, and end are required for create_event",
                            },
                        ],
                        isError: true,
                    };
                }
                const event = await client.createEvent({
                    summary: args.summary,
                    description: args.description,
                    start: new Date(args.start),
                    end: new Date(args.end),
                    recurrence: args.recurrence ? [args.recurrence] : undefined,
                    attendees: args.attendees,
                });
                const attendeeInfo = event.attendees?.length
                    ? `\nAttendees: ${event.attendees.map((a) => a.email).join(", ")}`
                    : "";
                const meetLink = event.hangoutLink
                    ? `\nGoogle Meet: ${event.hangoutLink}`
                    : "";
                return {
                    content: [
                        {
                            type: "text",
                            text: `Event created: "${event.summary}" (ID: ${event.id})\nStart: ${event.start?.dateTime ?? event.start?.date}\nEnd: ${event.end?.dateTime ?? event.end?.date}${event.recurrence ? `\nRecurrence: ${event.recurrence.join(", ")}` : ""}${attendeeInfo}${meetLink}`,
                        },
                    ],
                };
            }
            case "update_event": {
                if (!args.event_id) {
                    return {
                        content: [
                            {
                                type: "text",
                                text: "Error: event_id is required for update_event",
                            },
                        ],
                        isError: true,
                    };
                }
                const updates = {};
                if (args.summary)
                    updates.summary = args.summary;
                if (args.description)
                    updates.description = args.description;
                if (args.start)
                    updates.start = new Date(args.start);
                if (args.end)
                    updates.end = new Date(args.end);
                if (args.attendees)
                    updates.attendees = args.attendees;
                const updated = await client.updateEvent(args.event_id, updates);
                return {
                    content: [
                        {
                            type: "text",
                            text: `Event updated: "${updated.summary}" (ID: ${updated.id})`,
                        },
                    ],
                };
            }
            case "delete_event": {
                if (!args.event_id) {
                    return {
                        content: [
                            {
                                type: "text",
                                text: "Error: event_id is required for delete_event",
                            },
                        ],
                        isError: true,
                    };
                }
                await client.deleteEvent(args.event_id);
                return {
                    content: [
                        {
                            type: "text",
                            text: `Event deleted: ${args.event_id}`,
                        },
                    ],
                };
            }
            case "list_events": {
                const timeMin = args.start
                    ? new Date(args.start)
                    : new Date();
                const timeMax = args.end
                    ? new Date(args.end)
                    : new Date(timeMin.getTime() + 7 * 24 * 60 * 60 * 1000); // Default: next 7 days
                const events = await client.listUpcomingEvents(timeMin, timeMax, args.max_results ?? 20);
                if (events.length === 0) {
                    return {
                        content: [
                            {
                                type: "text",
                                text: `No events found between ${timeMin.toISOString()} and ${timeMax.toISOString()}.`,
                            },
                        ],
                    };
                }
                const lines = events.map((e) => {
                    const start = e.start?.dateTime ?? e.start?.date ?? "?";
                    const end = e.end?.dateTime ?? e.end?.date ?? "";
                    return `- [${e.id}] ${start}${end ? ` to ${end}` : ""}: ${e.summary ?? "(no title)"}${e.description ? ` - ${e.description.substring(0, 80)}` : ""}`;
                });
                return {
                    content: [
                        {
                            type: "text",
                            text: `Found ${events.length} event(s):\n${lines.join("\n")}`,
                        },
                    ],
                };
            }
            case "find_free_time": {
                const timeMin = args.start
                    ? new Date(args.start)
                    : new Date();
                const timeMax = args.end
                    ? new Date(args.end)
                    : new Date(timeMin.getTime() + 24 * 60 * 60 * 1000); // Default: next 24h
                const freeSlots = await client.findFreeTime(timeMin, timeMax);
                if (freeSlots.length === 0) {
                    return {
                        content: [
                            {
                                type: "text",
                                text: "No free time found in the specified range (all day is busy).",
                            },
                        ],
                    };
                }
                const lines = freeSlots.map((s) => `- ${s.start} to ${s.end}`);
                return {
                    content: [
                        {
                            type: "text",
                            text: `Free time slots:\n${lines.join("\n")}`,
                        },
                    ],
                };
            }
            default: {
                const action = args.action;
                return {
                    content: [{ type: "text", text: `Unknown action: ${action}` }],
                    isError: true,
                };
            }
        }
    }
    catch (err) {
        return {
            content: [
                {
                    type: "text",
                    text: `Calendar operation failed: ${err instanceof Error ? err.message : String(err)}`,
                },
            ],
            isError: true,
        };
    }
});
//# sourceMappingURL=calendar.js.map