import cron from "node-cron";
import logger from "../logger.js";
import { archiveOldTraces, checkIncompleteArchive } from "./archive.js";
export class ArchiveScheduler {
    task = null;
    dbPath;
    config;
    constructor(dbPath, config) {
        this.dbPath = dbPath;
        this.config = config;
    }
    /**
     * Start the archive scheduler
     * Performs crash recovery check on startup
     */
    async start() {
        if (!this.config.archiveEnabled) {
            logger.info("[Archive] archive scheduler disabled by config");
            return;
        }
        logger.info("[Archive] starting archive scheduler", {
            schedule: this.config.archiveSchedule,
            activeDays: this.config.activeDays,
            maxFiles: this.config.archiveMaxFiles,
        });
        // Crash recovery: check for incomplete archive from previous run
        try {
            const wasIncomplete = await checkIncompleteArchive(this.dbPath);
            if (wasIncomplete) {
                logger.info("[Archive] recovered from incomplete archive operation");
            }
        }
        catch (error) {
            logger.error("[Archive] crash recovery check failed", { error });
            // Continue starting scheduler even if recovery check fails
        }
        this.task = cron.schedule(this.config.archiveSchedule, async () => {
            try {
                logger.info("[Archive] starting scheduled archive...");
                const result = await archiveOldTraces(this.dbPath, this.config);
                if (result.success) {
                    if (result.archivedTraces > 0) {
                        logger.info("[Archive] completed successfully", {
                            archivedTraces: result.archivedTraces,
                            archiveFile: result.archiveFile,
                            duration: `${result.duration}ms`,
                        });
                    }
                    else {
                        logger.info("[Archive] no traces to archive");
                    }
                }
                else {
                    logger.error("[Archive] failed", { error: result.error });
                }
            }
            catch (error) {
                logger.error("[Archive] unexpected error", { error });
            }
        });
        this.task.start();
        logger.info("[Archive] archive scheduler started");
    }
    stop() {
        if (this.task) {
            this.task.stop();
            this.task = null;
            logger.info("[Archive] archive scheduler stopped");
        }
    }
    /**
     * Trigger archive operation immediately (for testing purposes only)
     * @internal
     */
    async triggerNow() {
        return archiveOldTraces(this.dbPath, this.config).then(() => { });
    }
}
