import { readFileSync, existsSync } from 'fs';
import { resolve } from 'path';
import { createHash } from 'crypto';

function projectRoot(): string {
  return (
    process.env.PROXMOX_ROOT?.trim() ||
    process.env.PHOENIX_REPO_ROOT?.trim() ||
    resolve(__dirname, '../../../../../..')
  );
}

function readJson<T>(relPath: string): T | null {
  const p = resolve(projectRoot(), relPath);
  if (!existsSync(p)) return null;
  return JSON.parse(readFileSync(p, 'utf8')) as T;
}

export interface SignoffRecord {
  schemaVersion: string;
  status: string;
  policyId?: string;
  methodologyId?: string;
  policyDocPath?: string;
  methodologyDocPath?: string;
  signedAt?: string | null;
  checklist?: Record<string, boolean>;
  classification?: string | Record<string, unknown>;
  model?: {
    approach?: string;
    stagingEnabled?: boolean;
    forwardLookingScenarios?: boolean;
  };
}

export function loadIas32Signoff(): SignoffRecord | null {
  return readJson<SignoffRecord>('config/compliance/ias32-gru-signoff.v1.json');
}

export function loadIfrs9Signoff(): SignoffRecord | null {
  return readJson<SignoffRecord>('config/compliance/ifrs9-ecl-signoff.v1.json');
}

export function isIas32Signed(): boolean {
  const s = loadIas32Signoff();
  return s?.status === 'signed';
}

export function isIfrs9Signed(): boolean {
  const s = loadIfrs9Signoff();
  return s?.status === 'signed';
}

export interface Ifrs9EclParameters {
  schemaVersion: string;
  reportingCurrency: string;
  segments: Array<{
    id: string;
    pd: number;
    lgd: number;
    stage: number;
    glCodesExposure?: string[];
    officeIds?: number[];
  }>;
  journalTemplate?: {
    debitGlCode: string;
    creditGlCode: string;
    officeId: number;
    narrativePrefix: string;
  };
}

export function loadIfrs9EclParameters(): Ifrs9EclParameters | null {
  const custom = process.env.OMNL_IFRS9_PARAMETERS_PATH?.trim();
  if (custom && existsSync(custom)) {
    return JSON.parse(readFileSync(custom, 'utf8')) as Ifrs9EclParameters;
  }
  const live = readJson<Ifrs9EclParameters>('config/compliance/ifrs9-ecl-parameters.v1.json');
  if (live) return live;
  return readJson<Ifrs9EclParameters>('config/compliance/ifrs9-ecl-parameters.v1.example.json');
}

export function loadXauReconcileBaseline(): Record<string, unknown> | null {
  return readJson('config/compliance/gru-xau-reconcile-baseline.v1.json');
}

export function computeEclAllowance(params: Ifrs9EclParameters, exposures: Array<{ segmentId: string; ead: number }>): {
  totalEcl: number;
  bySegment: Array<{ segmentId: string; ead: number; pd: number; lgd: number; ecl: number; stage: number }>;
} {
  const bySegment: Array<{ segmentId: string; ead: number; pd: number; lgd: number; ecl: number; stage: number }> = [];
  let totalEcl = 0;
  for (const exp of exposures) {
    const seg = params.segments.find((s) => s.id === exp.segmentId);
    if (!seg) continue;
    const ecl = exp.ead * seg.pd * seg.lgd;
    bySegment.push({
      segmentId: exp.segmentId,
      ead: exp.ead,
      pd: seg.pd,
      lgd: seg.lgd,
      ecl,
      stage: seg.stage,
    });
    totalEcl += ecl;
  }
  return { totalEcl, bySegment };
}

export function hashPolicyDoc(relPath: string): string | null {
  const p = resolve(projectRoot(), relPath);
  if (!existsSync(p)) return null;
  return createHash('sha256').update(readFileSync(p, 'utf8')).digest('hex');
}

export function loadIfrs13FairValueFeeds(): Record<string, unknown> | null {
  return readJson('config/compliance/ifrs13-fair-value-feeds.v1.json');
}

export function loadProvisionsRegister(): Record<string, unknown> | null {
  return readJson('config/omnl-provisions-register.json');
}

export function getComplianceSignoffsSummary(): Record<string, unknown> {
  const ias32 = loadIas32Signoff();
  const ifrs9 = loadIfrs9Signoff();
  const eclParams = loadIfrs9EclParameters();
  return {
    generatedAt: new Date().toISOString(),
    ias32: ias32
      ? {
          ...ias32,
          policySha256Computed: ias32.policyDocPath
            ? hashPolicyDoc('../GRU-Official-Docs-Monetary-Policies/docs/compliance/accounting/Accounting_Policy_IFRS_IAS32_GRU.md')
            : null,
          readyForExternalUse: ias32.status === 'signed',
        }
      : null,
    ifrs9: ifrs9
      ? {
          ...ifrs9,
          readyForExternalUse: ifrs9.status === 'signed' && process.env.OMNL_IFRS9_ECL_ENABLED === '1',
        }
      : null,
    eclParametersLoaded: Boolean(eclParams),
    custodianSnapshotConfigured: existsSync(
      resolve(projectRoot(), process.env.OMNL_CUSTODIAN_SNAPSHOT_PATH || 'config/omnl-custodian-snapshot.json')
    ),
  };
}
