#!/usr/bin/env node
/**
 * Exit 1 if reporting is not compliant (policy + freshness + ops) or RPC error.
 * Env: RPC, OMNL_COMPLIANCE_CORE_*, OMNL_MONITOR_LINE_ID, OMNL_MONITOR_CHAIN_ID
 */
import { Contract, JsonRpcProvider } from 'ethers';

const ABI = [
  'function getCompliance(bytes32 lineId) view returns (uint256 s0, uint256 s1, uint256 r, uint256 validUntil, bytes32 evidenceHash, bytes32 merkleRoot, uint256 minR, uint256 maxS1, bool m0Ok, bool m1Ok, bool attestationStale, bool policyOk, bool operational, bool reportingCompliant)',
];

async function main() {
  const chainId = parseInt(process.env.OMNL_MONITOR_CHAIN_ID || '138', 10);
  const lineId = process.env.OMNL_MONITOR_LINE_ID;
  const addr =
    chainId === 138
      ? process.env.OMNL_COMPLIANCE_CORE_138
      : chainId === 651940
        ? process.env.OMNL_COMPLIANCE_CORE_651940
        : process.env[`OMNL_COMPLIANCE_CORE_${chainId}`];
  const rpc =
    chainId === 138
      ? process.env.RPC_URL_138 || process.env.RPC_URL
      : process.env.CHAIN_651940_RPC_URL || 'https://mainnet-rpc.alltra.global';

  if (!lineId || !addr || !rpc) {
    console.error('Set OMNL_MONITOR_LINE_ID, OMNL_COMPLIANCE_CORE_*, and RPC for chain');
    process.exit(2);
  }

  const provider = new JsonRpcProvider(rpc, chainId);
  const c = new Contract(addr, ABI, provider);
  const r = await c.getCompliance(lineId);
  const ok = r.reportingCompliant;
  console.log(
    JSON.stringify({
      chainId,
      reportingCompliant: ok,
      policyOk: r.policyOk,
      attestationStale: r.attestationStale,
      operational: r.operational,
      validUntil: r.validUntil.toString(),
    })
  );
  if (!ok) process.exit(1);
}

main().catch((e) => {
  console.error(e);
  process.exit(2);
});
