import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const __dirname = dirname(fileURLToPath(import.meta.url));
const DEFAULT_MAP_PATH = join(__dirname, 'observer-chain-map.json');

/** Load the node->chains map. Throws on missing/invalid JSON (caller handles). */
export function loadChainMap(path = DEFAULT_MAP_PATH) {
  const raw = JSON.parse(readFileSync(path, 'utf8'));
  const map = new Map();
  for (const [node, chains] of Object.entries(raw)) {
    if (node === '_note') continue;
    if (Array.isArray(chains) && chains.length > 0) map.set(node, chains);
  }
  return map;
}

/** node_chosen -> array of L-chains, or null if not in any chain. */
export function chainsFor(node, map) {
  if (!node || typeof node !== 'string') return null;
  const chains = map.get(node);
  return chains && chains.length > 0 ? chains : null;
}
