import { fetchFineractGlAccounts, loadIpsasRegistry } from './omnl-ipsas-gl';
import { fetchOmnlComplianceAggregated } from './omnl-compliance';
import {
  loadIas32Signoff,
  loadIfrs9Signoff,
  loadIfrs9EclParameters,
  computeEclAllowance,
  isIas32Signed,
  isIfrs9Signed,
  getComplianceSignoffsSummary,
  loadIfrs13FairValueFeeds,
  loadProvisionsRegister,
} from './omnl-compliance-pack';

export { getComplianceSignoffsSummary };

/** IFRS 7-style liquidity / liability snapshot (machine-readable; requires accountant review). */
export async function buildIfrs7Disclosure(lineId?: string): Promise<Record<string, unknown>> {
  const line = lineId || process.env.OMNL_HEALTH_LINE_ID?.trim() || '';
  const registry = loadIpsasRegistry();
  const ias32 = loadIas32Signoff();
  let glCount = 0;
  try {
    glCount = (await fetchFineractGlAccounts()).length;
  } catch {
    glCount = 0;
  }
  let compliance: Record<string, unknown> | null = null;
  if (line) {
    try {
      compliance = (await fetchOmnlComplianceAggregated(line)) as unknown as Record<string, unknown>;
    } catch {
      compliance = null;
    }
  }
  return {
    standard: 'IFRS 7',
    disclaimer: isIas32Signed()
      ? 'Automated extract — signed IAS 32 policy on file'
      : 'Requires qualified accountant sign-off — IAS 32 policy pending',
    generatedAt: new Date().toISOString(),
    lineId: line || null,
    ias32SignoffStatus: ias32?.status ?? 'missing',
    financialLiabilities: {
      policyReference: '../GRU-Official-Docs-Monetary-Policies/docs/compliance/accounting/Accounting_Policy_IFRS_IAS32_GRU.md',
      classification: ias32?.classification ?? null,
      glRoles: registry.monetaryLayerHints?.m1_liability,
      fineractGlAccountCount: glCount,
    },
    liquidityRisk: {
      onChainReserveR: compliance?.r ?? null,
      onChainM1SupplyS1: compliance?.s1 ?? null,
      reportingCompliant: compliance?.reportingCompliant ?? null,
    },
    creditRisk: {
      eclEngineConfigured: Boolean(process.env.OMNL_IFRS9_ECL_ENABLED),
      ifrs9SignoffStatus: loadIfrs9Signoff()?.status ?? 'missing',
    },
  };
}

/** IFRS 9 classification / measurement + ECL allowance from parameters. */
export function buildIfrs9Disclosure(exposureOverrides?: Array<{ segmentId: string; ead: number }>): Record<string, unknown> {
  const signoff = loadIfrs9Signoff();
  const params = loadIfrs9EclParameters();
  const exposures =
    exposureOverrides ??
    (params?.segments ?? []).map((s) => ({
      segmentId: s.id,
      ead: parseFloat(process.env[`ECL_EAD_${s.id.toUpperCase()}`] || '0') || 0,
    }));
  const ecl =
    params && exposures.some((e) => e.ead > 0)
      ? computeEclAllowance(params, exposures)
      : { totalEcl: 0, bySegment: [] };
  return {
    standard: 'IFRS 9',
    disclaimer: isIfrs9Signed()
      ? 'Signed methodology on file — verify amounts before posting'
      : 'Requires qualified accountant sign-off — methodology pending',
    generatedAt: new Date().toISOString(),
    signoffStatus: signoff?.status ?? 'missing',
    classification: {
      gruInstrument: 'financial_liability',
      defaultMeasurement: 'amortized_cost',
      policyDoc: '../GRU-Official-Docs-Monetary-Policies/docs/compliance/accounting/IFRS9_ECL_METHODOLOGY_GRU.md',
      approach: signoff?.model?.approach ?? (params ? 'from_parameters_file' : 'unset'),
    },
    impairment: {
      eclEnabled: process.env.OMNL_IFRS9_ECL_ENABLED === '1',
      stagingModel: process.env.OMNL_IFRS9_STAGING_MODEL || signoff?.model?.approach || 'simplified',
      provisionGlCodes: ['52100', '23010'],
      totalEclAllowance: ecl.totalEcl,
      bySegment: ecl.bySegment,
      parametersSchemaVersion: params?.schemaVersion ?? null,
    },
    derecognition: {
      automated: false,
      finteractJournalRequired: true,
      monthlyScript: 'scripts/compliance/run-ifrs9-ecl-monthly.sh',
    },
  };
}

/** IFRS 13 fair-value hierarchy tagging for reserve evidence. */
export function buildIfrs13Disclosure(lineId?: string): Record<string, unknown> {
  const line = lineId || process.env.OMNL_HEALTH_LINE_ID?.trim() || '';
  const feeds = loadIfrs13FairValueFeeds();
  return {
    standard: 'IFRS 13',
    disclaimer: isIas32Signed() ? 'Supporting reserve evidence hierarchy' : 'Pending IAS 32 sign-off',
    generatedAt: new Date().toISOString(),
    lineId: line || null,
    configSchemaVersion: feeds?.schemaVersion ?? null,
    hierarchy: feeds?.hierarchy ?? {
      level1: {
        description: 'Quoted prices in active markets (e.g. LBMA gold fix feeds)',
        envFeed: process.env.OMNL_LBMA_FEED_URL || null,
      },
      level2: {
        description: 'Observable inputs',
        contracts: {
          reserve: process.env.OMNL_RESERVE_COMMITMENT_STORE || null,
          notary: process.env.OMNL_NOTARY_REGISTRY || null,
        },
      },
      level3: {
        description: 'Custodian / PoR attestation',
        custodianPath: process.env.OMNL_CUSTODIAN_SNAPSHOT_PATH || 'config/omnl-custodian-snapshot.json',
      },
    },
    deviationThresholdPercent: feeds?.deviationThresholdPercent ?? 2.5,
    reportScript: 'scripts/omnl/omnl-fair-value-hierarchy-report.sh',
    reserveCommitment: {
      primaryChain: 138,
      mirrorChain: 651940,
    },
  };
}

/** IAS 21 FX / IAS 37 provisions pointers. */
export function buildIas21Ias37Disclosure(): Record<string, unknown> {
  const provisions = loadProvisionsRegister();
  const provList = (provisions?.provisions as unknown[]) ?? [];
  const contingent = (provisions?.contingentLiabilities as unknown[]) ?? [];
  return {
    generatedAt: new Date().toISOString(),
    ias21: {
      revaluationGlIncome: '42100',
      revaluationGlExpense: '52100',
      fxReserveGl: ['12010', '12020', '12090'],
      automatedJob: 'scripts/omnl/omnl-fx-revaluation-post.sh',
    },
    ias37: {
      provisionGlHeader: '23000',
      provisionGlDetail: '23010',
      registerPath: 'config/omnl-provisions-register.json',
      provisionCount: provList.length,
      contingentLiabilityCount: contingent.length,
      provisions: provList,
      contingentLiabilities: contingent,
      reportScript: 'scripts/omnl/omnl-provisions-report.sh',
    },
  };
}

export async function buildFullDisclosure(lineId?: string): Promise<Record<string, unknown>> {
  return {
    generatedAt: new Date().toISOString(),
    signoffs: getComplianceSignoffsSummary(),
    ifrs7: await buildIfrs7Disclosure(lineId),
    ifrs9: buildIfrs9Disclosure(),
    ifrs13: buildIfrs13Disclosure(lineId),
    ias21_ias37: buildIas21Ias37Disclosure(),
  };
}
