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

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

export function loadRegistry(): PolicyMeta[] {
  ensureStorage();
  if (!fs.existsSync(PolicyConfig.registryPath)) fs.writeFileSync(PolicyConfig.registryPath, '[]');
  try {
    return JSON.parse(fs.readFileSync(PolicyConfig.registryPath, 'utf-8')) as PolicyMeta[];
  } catch {
    return [];
  }
}

export function saveRegistry(reg: PolicyMeta[]) {
  ensureStorage();
  fs.writeFileSync(PolicyConfig.registryPath, JSON.stringify(reg, null, 2));
}

export function upsertPolicy(
  reg: PolicyMeta[],
  meta: Partial<PolicyMeta> & { policyId: string }
): PolicyMeta[] {
  const idx = reg.findIndex((p) => p.policyId === meta.policyId);
  const now = new Date().toISOString();
  if (idx === -1) {
    reg.push({
      policyId: meta.policyId,
      name: meta['name'] || meta.policyId,
      description: meta['description'] || '',
      weight: typeof meta['weight'] === 'number' ? meta['weight']! : 0.5,
      status: (meta['status'] as any) || 'active',
      trend: (meta['trend'] as any) || '→',
      lastUpdate: now,
      _lastDelta: 0,
    });
  } else {
    reg[idx] = { ...reg[idx], ...meta, lastUpdate: now };
  }
  return reg;
}
