import { resolve } from "node:path";
import { mkdir, writeFile } from "node:fs/promises";
import { scheduleGet } from "./schedule-get.js";
import { generateICS, cronToRRule } from "../lib/ics.js";
export async function scheduleExportIcs(eventIds, accountId) {
    const found = [];
    const notFound = [];
    for (const id of eventIds) {
        const event = await scheduleGet(id, accountId);
        if (event) {
            found.push(event);
        }
        else {
            console.error(`[schedule-export-ics] eventId=${id} not found`);
            notFound.push(id);
        }
    }
    if (found.length === 0) {
        throw new Error(`No events found for the given IDs: ${notFound.join(", ")}`);
    }
    // Map EventDetail → ICSEvent
    let rruleMapped = 0;
    let rruleFallback = 0;
    const icsEvents = found.map((e) => {
        if (e.recurrence) {
            try {
                const result = cronToRRule(e.recurrence);
                if (result.rrule)
                    rruleMapped++;
                else
                    rruleFallback++;
            }
            catch {
                // Malformed cron — generateICS will handle via fallback path
                rruleFallback++;
                console.error(`[schedule-export-ics] cronToRRule failed for eventId=${e.eventId} cron=${e.recurrence}`);
            }
        }
        return {
            eventId: e.eventId,
            name: e.name,
            description: e.description,
            startDate: e.startDate,
            endDate: e.endDate,
            location: e.location,
            recurrence: e.recurrence,
            timezone: e.timezone,
        };
    });
    const icsContent = generateICS(icsEvents);
    // Write under the account output/ tree: {PLATFORM_ROOT}/../data/accounts/{accountId}/output/ics/
    // — files under output/ surface in the operator's Artefacts panel and on the file share (Task 584).
    const platformRoot = process.env.PLATFORM_ROOT;
    if (!platformRoot) {
        throw new Error("PLATFORM_ROOT environment variable is required");
    }
    const icsDir = resolve(platformRoot, "..", "data/accounts", accountId, "output", "ics");
    await mkdir(icsDir, { recursive: true });
    // Sanitize eventId — should always be a UUID but defend against path traversal
    const safeId = found.length === 1
        ? found[0].eventId.replace(/[^a-f0-9-]/gi, "")
        : "";
    const filename = safeId
        ? `${safeId}.ics`
        : `calendar-export-${Date.now()}.ics`;
    const outputPath = resolve(icsDir, filename);
    await writeFile(outputPath, icsContent, "utf-8");
    console.error(`[schedule-export-ics] eventIds=[${eventIds.join(",")}] outputPath=${outputPath} eventCount=${found.length} rruleMapped=${rruleMapped} rruleFallback=${rruleFallback}`);
    return {
        outputPath,
        eventCount: found.length,
        rruleMapped,
        rruleFallback,
        notFound,
    };
}
//# sourceMappingURL=schedule-export-ics.js.map