#!/usr/bin/env node
/**
 * Validate hybx-omnl-cross-chain-lines.json: structure, lineId hex, token addresses.
 * Exit 0 on success; exit 1 on validation errors (stderr).
 */
import { readFileSync } from 'fs';
import { resolve } from 'path';
import { fileURLToPath } from 'url';
const __dirname = fileURLToPath(new URL('.', import.meta.url));

function isAddr(s) {
  return typeof s === 'string' && /^0x[a-fA-F0-9]{40}$/.test(s);
}

const root = resolve(__dirname, '../..');
const configPath = process.env.OMNL_CROSS_CHAIN_CONFIG || resolve(root, 'config/hybx-omnl-cross-chain-lines.json');

function fail(msg) {
  console.error(msg);
  process.exit(1);
}

const raw = readFileSync(configPath, 'utf8');
let data;
try {
  data = JSON.parse(raw);
} catch (e) {
  fail(`Invalid JSON: ${configPath}: ${e}`);
}

if (!data.lines || !Array.isArray(data.lines)) {
  fail('Expected top-level { lines: [...] }');
}

for (let i = 0; i < data.lines.length; i++) {
  const row = data.lines[i];
  const lid = row.lineId;
  if (typeof lid !== 'string' || !/^0x[a-fA-F0-9]{64}$/.test(lid)) {
    fail(`lines[${i}].lineId must be bytes32 hex: ${lid}`);
  }
  if (!row.chains || typeof row.chains !== 'object') {
    fail(`lines[${i}].chains must be an object`);
  }
  for (const [cid, pair] of Object.entries(row.chains)) {
    if (!/^\d+$/.test(cid)) fail(`lines[${i}].chains key must be chain id string: ${cid}`);
    if (!pair || typeof pair !== 'object') fail(`lines[${i}].chains[${cid}] invalid`);
    const p = pair;
    if (!isAddr(p.tokenM0)) fail(`lines[${i}].chains[${cid}].tokenM0 invalid address: ${p.tokenM0}`);
    if (!isAddr(p.tokenM1)) fail(`lines[${i}].chains[${cid}].tokenM1 invalid address: ${p.tokenM1}`);
  }
}

console.log(`OK: ${configPath} (${data.lines.length} line(s))`);
