import fs from 'fs';
import path from 'path';
import {
  mergeExchangeTokensWithM2Registry,
  type M2TokenCapabilities,
  type M2TokenRegistryFile,
} from '@dbis/settlement-core';

export type ExchangeConfig = {
  version: string;
  chainId: number;
  brandName: string;
  officeId: number;
  settlementOfficeExternalId: string;
  chainRegistry?: string;
  maxSupportedChains?: number;
  routers: Record<string, string>;
  factory: Record<string, string>;
  tokens: {
    symbol: string;
    name: string;
    address: string;
    decimals: number;
    native?: boolean;
    omnlLine?: string;
    moneyLayer?: string;
    swappable?: boolean;
    convertible?: boolean;
    transferableInternal?: boolean;
    transferableExternal?: boolean;
  }[];
  defaultSlippageBps: number;
  production: {
    requireApiKey: boolean;
    monitorSwaps: boolean;
    postSwapSettlementAudit: boolean;
    onlineBankMode?: boolean;
  };
};

let cached: ExchangeConfig | null = null;
let cachedM2: M2TokenRegistryFile | null = null;

export function loadM2TokenRegistry(): M2TokenRegistryFile {
  if (cachedM2) return cachedM2;
  const p =
    process.env.OMNL_M2_TOKEN_REGISTRY ||
    path.resolve(__dirname, '../../../config/omnl-m2-token-registry.v1.json');
  cachedM2 = JSON.parse(fs.readFileSync(p, 'utf8')) as M2TokenRegistryFile;
  return cachedM2;
}

export function loadExchangeTokens(): M2TokenCapabilities[] {
  const cfg = loadExchangeConfig();
  return mergeExchangeTokensWithM2Registry(cfg.tokens, loadM2TokenRegistry());
}

export function loadExchangeConfig(): ExchangeConfig {
  if (cached) return cached;
  const p =
    process.env.DBIS_EXCHANGE_CONFIG ||
    path.resolve(__dirname, '../../../config/dbis-exchange.v1.json');
  cached = JSON.parse(fs.readFileSync(p, 'utf8')) as ExchangeConfig;
  return cached;
}

export function exchangePort(): number {
  return parseInt(process.env.DBIS_EXCHANGE_PORT || '3012', 10);
}

export function tokenAggUrl(): string {
  return (process.env.TOKEN_AGGREGATION_URL || 'http://localhost:3000').replace(/\/$/, '');
}

export function settlementUrl(): string {
  return (process.env.SETTLEMENT_MIDDLEWARE_URL || 'http://localhost:3011').replace(/\/$/, '');
}
