/**
 * P2-5 smoke test — scripts/worker.ts wires the nightly rollup tick.
 *
 * Run: npx tsx scripts/smoke/p2-5-rollup-tick.ts
 */
import './_lib';
import { ok, fail } from './_lib';
import { readFileSync } from 'fs';
import path from 'path';
import { shouldRunRollupNow } from '../../src/lib/services/rollup-scheduler';

function main(): void {
    // 1. worker.ts must import the scheduler and register the tick.
    const workerFile = path.resolve(__dirname, '../../scripts/worker.ts');
    const src = readFileSync(workerFile, 'utf8');

    if (!/runRollupTickIfDue/.test(src)) {
        fail('P2-5 scheduler import', 'worker.ts does not import runRollupTickIfDue');
    }
    ok('worker.ts imports runRollupTickIfDue');

    if (!/HEARTBEAT_RETENTION_DAYS/.test(src)) {
        fail('P2-5 retention env', 'worker.ts does not read HEARTBEAT_RETENTION_DAYS');
    }
    ok('worker.ts reads HEARTBEAT_RETENTION_DAYS');

    if (!/HEARTBEAT_ROLLUP_INTERVAL_HOURS/.test(src)) {
        fail('P2-5 interval env', 'worker.ts does not read HEARTBEAT_ROLLUP_INTERVAL_HOURS');
    }
    ok('worker.ts reads HEARTBEAT_ROLLUP_INTERVAL_HOURS');

    if (!/setInterval\(\s*async[^,]*\n[\s\S]*runRollupTickIfDue/.test(src)) {
        fail('P2-5 tick registered', 'no setInterval calls runRollupTickIfDue');
    }
    ok('worker.ts registers a setInterval that calls runRollupTickIfDue');

    // 2. shouldRunRollupNow shape sanity (the worker depends on this).
    const NOW = new Date('2026-06-01T12:00:00Z');
    if (!shouldRunRollupNow(null, 24, NOW)) {
        fail('P2-5 shouldRunRollupNow', 'null lastRunAt should be runnable');
    }
    ok('shouldRunRollupNow(null, 24, now) === true');

    const recent = new Date('2026-06-01T11:00:00Z'); // 1h ago
    if (shouldRunRollupNow(recent, 24, NOW)) {
        fail('P2-5 shouldRunRollupNow', '1h-old run should not re-run under 24h interval');
    }
    ok('shouldRunRollupNow refuses to re-run under interval');

    const oldRun = new Date('2026-05-31T11:00:00Z'); // 25h ago
    if (!shouldRunRollupNow(oldRun, 24, NOW)) {
        fail('P2-5 shouldRunRollupNow', '25h-old run should re-run under 24h interval');
    }
    ok('shouldRunRollupNow runs again when interval elapsed');

    ok('P2-5 rollup-tick', 'worker schedules nightly rollup; helper behaviour matches contract');
}

main();
