import fs from 'fs';
import path from 'path';

export type OmnlChainEntry = {
  chainId: number;
  name: string;
  type: 'evm' | 'non-evm';
  nativeSymbol: string;
  tier: string;
  omnlRole: string;
  status: 'active' | 'staged' | 'reserved';
  rpcEnv: string;
  explorerUrl?: string;
  rpcDefault?: string;
  settlement: {
    m2LoadEnabled: boolean;
    swapEnabled: boolean;
    bridgeEnabled: boolean;
    officeId: number;
  };
  complianceEnv?: string;
};

export type OmnlChainRegistry = {
  version: string;
  brand: string;
  maxCapacity: number;
  primaryChainId: number;
  mirrorChainId: number;
  settlementOfficeId: number;
  chains: OmnlChainEntry[];
  stats?: { total: number; active: number; staged: number; reserved: number };
};

let cached: OmnlChainRegistry | null = null;

export function resolveChainRegistryPath(): string {
  if (process.env.OMNL_SUPPORTED_CHAINS_CONFIG) return process.env.OMNL_SUPPORTED_CHAINS_CONFIG;
  const candidates = [
    path.resolve(process.cwd(), 'config/omnl-supported-chains.v1.json'),
    path.resolve(__dirname, '../../../config/omnl-supported-chains.v1.json'),
    path.resolve(__dirname, '../../../../config/omnl-supported-chains.v1.json'),
  ];
  for (const p of candidates) {
    if (fs.existsSync(p)) return p;
  }
  return candidates[1];
}

export function loadOmnlChainRegistry(): OmnlChainRegistry {
  if (cached) return cached;
  const p = resolveChainRegistryPath();
  cached = JSON.parse(fs.readFileSync(p, 'utf8')) as OmnlChainRegistry;
  return cached;
}

export function getActiveChains(): OmnlChainEntry[] {
  return loadOmnlChainRegistry().chains.filter((c) => c.status === 'active');
}

export function getChainById(chainId: number): OmnlChainEntry | undefined {
  return loadOmnlChainRegistry().chains.find((c) => c.chainId === chainId);
}

export function getSupportedChainIds128(): number[] {
  return loadOmnlChainRegistry().chains.map((c) => c.chainId);
}
