import fs from 'node:fs';
import { PolicyConfig } from '../../config/policy.config';
import { PolicyHistoryRecord } from './policy_types';

function ensureStorage() {
  fs.mkdirSync('./storage', { recursive: true });
}

export function appendHistory(rec: PolicyHistoryRecord) {
  ensureStorage();
  if (!fs.existsSync(PolicyConfig.historyPath)) fs.writeFileSync(PolicyConfig.historyPath, '[]');
  const arr: PolicyHistoryRecord[] = JSON.parse(
    fs.readFileSync(PolicyConfig.historyPath, 'utf-8') || '[]'
  );
  arr.push(rec);
  fs.writeFileSync(PolicyConfig.historyPath, JSON.stringify(arr, null, 2));
}

export function loadHistory(): PolicyHistoryRecord[] {
  ensureStorage();
  if (!fs.existsSync(PolicyConfig.historyPath)) return [];
  return JSON.parse(fs.readFileSync(PolicyConfig.historyPath, 'utf-8') || '[]');
}
