/**
 * One-shot: prove sentinel-limits.json round-trip changes Sentinel.getConfig()
 * and policy thresholds (simulates Gateway restart without HTTP).
 *
 * Usage: node scripts/verify-sentinel-persist.mjs
 */
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';

const tmp = fs.mkdtempSync(path.join(os.tmpdir(), '4runr-persist-verify-'));
process.env['APPDATA'] = tmp;

const { Sentinel, policyManager } = await import('@4runr/sentinel');
const {
  saveSentinelLimitsToDisk,
  loadSentinelLimitsFromDisk,
  applyPersistedSentinelConfig,
  getSentinelLimitsFilePath,
} = await import('../dist/security/sentinel-config-store.js');

const distinctive = {
  enabled: true,
  runMaxDurationMs: 111_000,
  runMaxTokens: 22_000,
  runIdleMs: 12_345,
  loopWindow: 9,
  loopMax: 4,
  runMaxCost: 2.75,
};

saveSentinelLimitsToDisk(distinctive);
const filePath = getSentinelLimitsFilePath();
if (!fs.existsSync(filePath)) {
  console.error('FAIL: file not written', filePath);
  process.exit(1);
}
const onDisk = JSON.parse(fs.readFileSync(filePath, 'utf8'));
console.log('OK: wrote', filePath);
console.log('   config.runIdleMs on disk:', onDisk.config?.runIdleMs);

const loaded = loadSentinelLimitsFromDisk();
if (loaded?.runIdleMs !== distinctive.runIdleMs) {
  console.error('FAIL: load from disk', loaded);
  process.exit(1);
}
console.log('OK: loadSentinelLimitsFromDisk matches');

Sentinel.resetInstance();
const sentinel = Sentinel.getInstance();
const before = sentinel.getConfig().runIdleMs;
applyPersistedSentinelConfig(sentinel);
const after = sentinel.getConfig().runIdleMs;
if (after !== distinctive.runIdleMs) {
  console.error('FAIL: after boot apply', { before, after, expected: distinctive.runIdleMs });
  process.exit(1);
}
console.log('OK: fresh singleton after applyPersistedSentinelConfig', { before, after });

const violations = policyManager.evaluatePolicies(
  'verify-run',
  {
    runId: 'verify-run',
    createdAt: Date.now(),
    startedAt: Date.now() - 30_000,
    lastTokenAt: Date.now() - 30_000,
    tokenCount: 0,
    status: 'running',
    events: [],
  },
  sentinel.getConfig()
);
const idle = violations.find((v) => v.policy === 'idle');
if (!idle || idle.threshold !== distinctive.runIdleMs) {
  console.error('FAIL: policy threshold', idle);
  process.exit(1);
}
console.log('OK: idle policy threshold = persisted runIdleMs', idle.threshold);

fs.rmSync(tmp, { recursive: true, force: true });
console.log('\nAll persistence checks passed (fundamental, not UI-only).');
