import { resolve, basename } from "node:path";
import { readFile, stat } from "node:fs/promises";
import { realpathSync } from "node:fs";
import { getSession } from "../lib/neo4j.js";
import { ingestIcs, } from "../lib/ics-graph-ingest.js";
const MAX_FILE_SIZE_BYTES = 20 * 1024 * 1024; // 20 MB
/**
 * Read an .ics file from inside the account directory, parse it, and either
 * preview (dry-run) or write (commit) the graph state described by the file.
 *
 *   path-contain + size gate ──▶ parseICS ──▶ ingestIcs(mode)
 *
 * Path containment matches the existing `schedule-import-ics` behaviour:
 * the file must resolve inside `data/accounts/<accountId>/` so an operator
 * can't point the tool at arbitrary disk.
 */
export async function scheduleArchiveIcs(params) {
    const { filePath, mode, accountId, userId, sessionId } = params;
    const platformRoot = process.env.PLATFORM_ROOT;
    if (!platformRoot) {
        throw new Error("PLATFORM_ROOT environment variable is required");
    }
    // Path containment — same recipe as schedule-import-ics.
    const accountDir = resolve(platformRoot, "..", "data/accounts", accountId);
    let resolvedPath;
    try {
        resolvedPath = realpathSync(filePath);
        const accountResolved = realpathSync(accountDir);
        if (!resolvedPath.startsWith(accountResolved + "/")) {
            process.stderr.write(`[schedule-archive-ics] path validation failed: outside account directory\n`);
            throw new Error("Access denied: file is outside the account directory");
        }
    }
    catch (err) {
        if (err.code === "ENOENT") {
            process.stderr.write(`[schedule-archive-ics] path validation failed: file not found\n`);
            throw new Error(`File not found: ${filePath}`);
        }
        throw err;
    }
    const fileStat = await stat(resolvedPath);
    if (fileStat.size > MAX_FILE_SIZE_BYTES) {
        process.stderr.write(`[schedule-archive-ics] path validation failed: file too large (${fileStat.size} bytes)\n`);
        throw new Error(`File too large: ${fileStat.size} bytes (max ${MAX_FILE_SIZE_BYTES})`);
    }
    const fileContent = await readFile(resolvedPath, "utf-8");
    const session = getSession();
    try {
        return await ingestIcs({
            fileContent,
            filename: basename(resolvedPath),
            mode,
            accountId,
            userId,
            ...(sessionId !== undefined ? { sessionId } : {}),
            session,
        });
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=schedule-archive-ics.js.map