/**
 * Institutional capital-markets classification (exposure vs instrument).
 * Source of truth: config/rwa-capital-markets-taxonomy.v1.json
 */

import { existsSync, readFileSync } from 'fs';
import { resolve } from 'path';

export interface CapitalMarketsFields {
  assetClass: string;
  assetGroup: string;
  instrumentType: string;
  underlyingAsset: string;
  tenor: string;
  collateralType: string;
  gruLayer?: string;
  defillamaRwaEligible?: boolean;
}

type TaxonomyInstrument = {
  ticker: string;
  asset_class: string;
  asset_group: string;
  instrument_type: string;
  underlying_asset: string;
  tenor: string;
  collateral_type: string;
  gru_layer?: string;
  defillamaEligible?: boolean;
};

type TaxonomyDocument = {
  version: string;
  instruments: TaxonomyInstrument[];
};

function projectRoot(): string {
  return (
    process.env.PROXMOX_ROOT?.trim() ||
    process.env.PHOENIX_REPO_ROOT?.trim() ||
    resolve(__dirname, '../../../../../..')
  );
}

function loadTaxonomyDocument(): TaxonomyDocument {
  const path = resolve(projectRoot(), 'config/rwa-capital-markets-taxonomy.v1.json');
  if (!existsSync(path)) {
    return { version: 'unknown', instruments: [] };
  }
  return JSON.parse(readFileSync(path, 'utf8')) as TaxonomyDocument;
}

const taxonomy = loadTaxonomyDocument();

const byTicker = new Map<string, CapitalMarketsFields>(
  taxonomy.instruments.map((row) => [
    row.ticker,
    {
      assetClass: row.asset_class,
      assetGroup: row.asset_group,
      instrumentType: row.instrument_type,
      underlyingAsset: row.underlying_asset,
      tenor: row.tenor,
      collateralType: row.collateral_type,
      gruLayer: row.gru_layer,
      defillamaRwaEligible: row.defillamaEligible,
    },
  ]),
);

export function getCapitalMarketsClassification(symbol: string): CapitalMarketsFields | undefined {
  return byTicker.get(symbol);
}

export const RWA_CAPITAL_MARKETS_TAXONOMY_VERSION = taxonomy.version;
