import { readFileSync, existsSync } from 'fs';
import { createHash } from 'crypto';
import { loadIpsasRegistryPath } from './omnl-ipsas-gl';
import { loadJournalMatrixPath } from './omnl-journal-matrix';

export interface OmnlReconcileAnchorResult {
  ok: boolean;
  sha256: string;
  registryPath: string;
  matrixPath: string;
  generatedAt: string;
  error?: string;
}

/** Same canonical SHA-256 as `scripts/omnl-reconcile-report.mjs` (IPSAS registry + journal matrix JSON). */
export function computeOmnlReconcileAnchor(): OmnlReconcileAnchorResult {
  const generatedAt = new Date().toISOString();
  try {
    const registryPath = loadIpsasRegistryPath();
    const matrixPath = loadJournalMatrixPath();
    if (!existsSync(registryPath)) {
      return {
        ok: false,
        sha256: '',
        registryPath,
        matrixPath,
        generatedAt,
        error: `IPSAS registry file missing: ${registryPath}`,
      };
    }
    if (!existsSync(matrixPath)) {
      return {
        ok: false,
        sha256: '',
        registryPath,
        matrixPath,
        generatedAt,
        error: `Journal matrix file missing: ${matrixPath}`,
      };
    }
    const reg = readFileSync(registryPath, 'utf8');
    const matrix = readFileSync(matrixPath, 'utf8');
    const canonical = JSON.stringify({
      registry: JSON.parse(reg) as unknown,
      matrix: JSON.parse(matrix) as unknown,
    });
    const sha256 = createHash('sha256').update(canonical).digest('hex');
    return { ok: true, sha256, registryPath, matrixPath, generatedAt };
  } catch (e) {
    const msg = e instanceof Error ? e.message : String(e);
    return {
      ok: false,
      sha256: '',
      registryPath: '',
      matrixPath: '',
      generatedAt,
      error: msg,
    };
  }
}
