"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateCron = validateCron;
exports.startSyncScheduler = startSyncScheduler;
exports.stopSyncScheduler = stopSyncScheduler;
const crypto = __importStar(require("crypto"));
const config_1 = require("./config");
const sync_config_1 = require("./sync-config");
const sync_service_1 = require("./sync-service");
const logger_1 = require("./logger");
const log = (0, logger_1.modLogger)('sync');
/** Return parsed cron or `null` if invalid.  Refuses empty-Set fields (e.g.
 *  `9-5` with A>B) and invalid step (`*\/0`) rather than silently accepting
 *  them as "never fires" / "every minute". */
function parseField(raw, min, max) {
    const out = new Set();
    for (const segment of raw.split(',')) {
        const part = segment.trim();
        if (!part)
            return null;
        let step = 1;
        let rangePart = part;
        const slashIdx = part.indexOf('/');
        if (slashIdx >= 0) {
            const stepRaw = part.slice(slashIdx + 1);
            const parsed = parseInt(stepRaw, 10);
            if (!Number.isFinite(parsed) || parsed <= 0)
                return null;
            step = parsed;
            rangePart = part.slice(0, slashIdx);
        }
        let start = min;
        let end = max;
        if (rangePart === '*') {
            /* full range */
        }
        else if (rangePart.includes('-')) {
            const [aStr, bStr] = rangePart.split('-');
            const a = parseInt(aStr, 10);
            const b = parseInt(bStr, 10);
            if (!Number.isFinite(a) || !Number.isFinite(b))
                return null;
            if (a > b)
                return null; // A>B would yield empty Set
            if (a < min || b > max)
                return null; // out-of-range
            start = a;
            end = b;
        }
        else {
            const n = parseInt(rangePart, 10);
            if (!Number.isFinite(n) || n < min || n > max)
                return null;
            start = end = n;
        }
        for (let v = start; v <= end; v += step) {
            if (v >= min && v <= max)
                out.add(v);
        }
    }
    if (out.size === 0)
        return null;
    return out;
}
function parseCron(expr) {
    const parts = expr.trim().split(/\s+/);
    if (parts.length !== 5)
        return null;
    const [m, h, dom, mo, dow] = parts;
    const minute = parseField(m, 0, 59);
    const hour = parseField(h, 0, 23);
    const domS = parseField(dom, 1, 31);
    const month = parseField(mo, 1, 12);
    const dowS = parseField(dow, 0, 6);
    if (!minute || !hour || !domS || !month || !dowS)
        return null;
    return { minute, hour, dom: domS, month, dow: dowS };
}
/** Human-readable error or `null` if valid. Consumed by `routes/sync.ts` at
 *  save-time so invalid crons are rejected with a 400 instead of silently
 *  being "enabled but never fires". */
function validateCron(expr) {
    if (!expr || !expr.trim())
        return '空表达式';
    const parts = expr.trim().split(/\s+/);
    if (parts.length !== 5)
        return `必须是 5 段（分 时 日 月 周），当前 ${parts.length} 段`;
    const parsed = parseCron(expr);
    if (!parsed)
        return '包含无效字段、空范围（如 9-5）、或步长为 0';
    return null;
}
function matches(cron, now) {
    return (cron.minute.has(now.getMinutes()) &&
        cron.hour.has(now.getHours()) &&
        cron.dom.has(now.getDate()) &&
        cron.month.has(now.getMonth() + 1) &&
        cron.dow.has(now.getDay()));
}
// ── Scheduler state ─────────────────────────────────────────────────────────
let interval = null;
let timeoutHandle = null;
/** Keyed by username — the last `YYYYMMDDHHMM` key at which we fired.  Guards
 *  against DST fall-back double-fires (same minute + hour twice in one day)
 *  and any scheduler-tick drift. */
const lastRunKey = new Map();
function minuteKey(d) {
    const pad = (n) => String(n).padStart(2, '0');
    return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}${pad(d.getHours())}${pad(d.getMinutes())}`;
}
async function runScheduledOnce(now) {
    const currentKey = minuteKey(now);
    const users = (0, sync_config_1.listUsersWithSyncConfig)();
    for (const username of users) {
        const cfg = (0, sync_config_1.getSyncConfig)(username);
        if (!cfg.schedule.enabled || !cfg.schedule.cron)
            continue;
        const parsed = parseCron(cfg.schedule.cron);
        if (!parsed || !matches(parsed, now))
            continue;
        // De-dupe per-minute (DST + tick jitter)
        if (lastRunKey.get(username) === currentKey)
            continue;
        lastRunKey.set(username, currentKey);
        const projects = (0, config_1.getProjects)().filter((p) => !p.archived && (0, config_1.isProjectOwner)(p, username));
        for (const p of projects) {
            // Mint runId before the call so the catch path can log it too
            // (reviewer I3: scheduler failures need cross-file correlation).
            const runId = `sync.${Date.now()}.${crypto.randomBytes(3).toString('hex')}`;
            try {
                await (0, sync_service_1.syncProject)(username, p.id, p.name, p.folderPath, undefined, { runId });
            }
            catch (err) {
                log.warn({ err, runId, user: username, projectId: p.id, projectName: p.name }, 'scheduled sync failed');
            }
        }
    }
}
function startSyncScheduler() {
    if (interval || timeoutHandle)
        return;
    // Align to top of minute: wait until seconds == 0, then fire every 60s.
    const alignDelay = (60 - new Date().getSeconds()) * 1000;
    timeoutHandle = setTimeout(() => {
        timeoutHandle = null;
        void runScheduledOnce(new Date()).catch(() => { });
        interval = setInterval(() => {
            void runScheduledOnce(new Date()).catch(() => { });
        }, 60000);
    }, alignDelay);
}
function stopSyncScheduler() {
    if (timeoutHandle) {
        clearTimeout(timeoutHandle);
        timeoutHandle = null;
    }
    if (interval) {
        clearInterval(interval);
        interval = null;
    }
    lastRunKey.clear();
}
//# sourceMappingURL=sync-scheduler.js.map