import { logger } from "../logger.js";
import { sanitizeJsonString } from "../utils/json-sanitize.js";
import { GoogleCalendarClient } from "./google-calendar.js";
let cachedCalendarClient = null;
/**
 * Get a summary of upcoming calendar events for context injection.
 * Called on each agent wake to inform the agent of due/upcoming tasks.
 *
 * Uses an execution window around "now" so that events only appear in the
 * agent's context when they are imminent or just-passed, instead of showing
 * every event in the next 24 hours.
 *
 * Window size = 1.2× the heartbeat interval in each direction:
 *   - Lookback:  recently-passed events still visible (heartbeat may have missed them)
 *   - Lookahead: upcoming events appear only when they're about to start
 *
 * @param heartbeatIntervalMs – the owner's configured heartbeat interval
 */
export async function getCalendarSummary(config, heartbeatIntervalMs) {
    try {
        cachedCalendarClient ??= new GoogleCalendarClient(config);
        const client = cachedCalendarClient;
        const now = new Date();
        const windowMs = Math.round(heartbeatIntervalMs * 1.2);
        const windowStart = new Date(now.getTime() - windowMs);
        const windowEnd = new Date(now.getTime() + windowMs);
        const events = await client.listUpcomingEvents(windowStart, windowEnd);
        if (events.length === 0) {
            return "";
        }
        const lines = events.map((event) => {
            const start = sanitizeJsonString(event.start?.dateTime ?? event.start?.date ?? "unknown");
            const end = sanitizeJsonString(event.end?.dateTime ?? event.end?.date ?? "");
            const summary = sanitizeJsonString(event.summary ?? "(no title)");
            const description = event.description
                ? ` - ${sanitizeJsonString(event.description.substring(0, 100))}`
                : "";
            return `- ${start}${end ? ` to ${end}` : ""}: ${summary}${description}`;
        });
        return lines.join("\n");
    }
    catch (err) {
        logger.warn(`Calendar summary failed: ${err instanceof Error ? err.message : String(err)}`);
        return "";
    }
}
//# sourceMappingURL=scheduler.js.map