"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadListenerConfig = loadListenerConfig;
exports.applyEnvOverrides = applyEnvOverrides;
exports.buildResourceRegistry = buildResourceRegistry;
exports.collectSearchableFields = collectSearchableFields;
const fs_1 = require("fs");
const path_1 = require("path");
function readJson(path) {
    if (!(0, fs_1.existsSync)(path))
        return null;
    return JSON.parse((0, fs_1.readFileSync)(path, 'utf8'));
}
function normAddr(a) {
    return a.toLowerCase();
}
function loadListenerConfig(projectRoot) {
    const p = (0, path_1.resolve)(projectRoot, 'config/swift-listener-chain138.v1.json');
    const config = readJson(p);
    applyEnvOverrides(config);
    return config;
}
function envFlag(name) {
    return process.env[name] === '1';
}
function applyEnvOverrides(config) {
    if (process.env.SWIFT_LISTENER_FILE_INBOX === '1')
        config.adapters.fileInbox.enabled = true;
    if (process.env.SWIFT_LISTENER_FILE_INBOX === '0')
        config.adapters.fileInbox.enabled = false;
    if (envFlag('SWIFT_LISTENER_WEBHOOK'))
        config.adapters.webhook.enabled = true;
    if (process.env.SWIFT_LISTENER_WEBHOOK === '0')
        config.adapters.webhook.enabled = false;
    if (envFlag('SWIFT_LISTENER_P2P_RAIL'))
        config.adapters.p2pRail.enabled = true;
    if (envFlag('SWIFT_LISTENER_FIN_GATEWAY'))
        config.adapters.finGateway.enabled = true;
    if (envFlag('SWIFT_LISTENER_FIN_TCP'))
        config.adapters.swiftFinTcp.enabled = true;
    if (process.env.SWIFT_LISTENER_FIN_TCP === '0')
        config.adapters.swiftFinTcp.enabled = false;
    if (envFlag('SWIFT_LISTENER_AS4_INBOX'))
        config.adapters.as4Inbox.enabled = true;
    if (envFlag('SWIFT_LISTENER_MAIL_INBOX'))
        config.adapters.mailAttachmentInbox.enabled = true;
    if (envFlag('SWIFT_LISTENER_TELEX_INBOX'))
        config.adapters.telexInbox.enabled = true;
    config.outbound ??= defaultOutboundConfig();
    if (envFlag('SWIFT_LISTENER_OMNL_FORWARD'))
        config.outbound.omnlForward.enabled = true;
    if (process.env.SWIFT_LISTENER_OMNL_FORWARD === '0')
        config.outbound.omnlForward.enabled = false;
    if (envFlag('SWIFT_LISTENER_INTAKE_GATEWAY'))
        config.outbound.intakeGateway.enabled = true;
    if (process.env.SWIFT_LISTENER_INTAKE_GATEWAY === '0')
        config.outbound.intakeGateway.enabled = false;
    applyAttestationEnvFlags(config);
}
/** Align with config/chain138-iso20022-attestation.v1.json envFlags when set on operator host. */
function applyAttestationEnvFlags(config) {
    if (process.env.CHECKPOINT_ISO_OMNL_STORE === '1') {
        config.outbound ??= defaultOutboundConfig();
        config.outbound.omnlForward.enabled = true;
    }
    if (process.env.CHECKPOINT_RECORD_ISO_ATTESTATION === '1') {
        config.outbound ??= defaultOutboundConfig();
        config.outbound.intakeGateway.enabled = true;
    }
}
function defaultOutboundConfig() {
    return {
        omnlForward: {
            enabled: true,
            mode: 'local_and_api',
            apiPath: '/api/v1/omnl/iso20022/messages',
            tokenAggregationUrlEnv: 'TOKEN_AGGREGATION_URL',
            apiKeyEnv: 'OMNL_API_KEY',
            localStoreDir: 'config/iso20022-omnl/messages',
        },
        intakeGateway: {
            enabled: true,
            gatewayAddressEnv: 'ISO20022_INTAKE_GATEWAY_MAINNET',
            gatewayAddressFallback: '0x66C89F91A4e830d87fcE4E5F86aFA71A96FbDa3d',
            rpcUrlEnv: 'RPC_URL_138',
            privateKeyEnv: 'PRIVATE_KEY',
            executeEnv: 'SWIFT_LISTENER_GATEWAY_EXECUTE',
            dryRunDefault: false,
            autoExecuteWhenKeyPresent: true,
            chainId: 138,
        },
    };
}
/** Build searchable registry from Chain 138 + cW* config sources. */
function buildResourceRegistry(projectRoot, config) {
    const symbols = new Set();
    const cwSymbols = new Set(Object.values(config.cToCwSymbolMapping));
    const addresses = new Map();
    const contracts = [];
    for (const [cSym, cwSym] of Object.entries(config.cToCwSymbolMapping)) {
        symbols.add(cSym);
        symbols.add(cwSym);
        cwSymbols.add(cwSym);
    }
    const ei = readJson((0, path_1.resolve)(projectRoot, 'config/ei-matrix-138-assets-and-pools.v1.json'));
    if (ei?.canonicalTokens) {
        for (const t of ei.canonicalTokens) {
            symbols.add(t.symbol);
            addresses.set(normAddr(t.address), { symbol: t.symbol, chainId: 138 });
        }
    }
    if (ei?.dodoStackA?.integration) {
        contracts.push(ei.dodoStackA.integration);
        addresses.set(normAddr(ei.dodoStackA.integration), { symbol: 'DODOPMMIntegration', chainId: 138 });
    }
    if (ei?.dodoStackA?.provider) {
        contracts.push(ei.dodoStackA.provider);
        addresses.set(normAddr(ei.dodoStackA.provider), { symbol: 'DODOPMMProvider', chainId: 138 });
    }
    for (const pool of ei?.dodoStackA?.pools ?? []) {
        contracts.push(pool.pool);
        addresses.set(normAddr(pool.pool), { symbol: pool.name ?? 'PMM_POOL', chainId: 138 });
    }
    if (ei?.enhancedSwapRouter) {
        contracts.push(ei.enhancedSwapRouter);
        addresses.set(normAddr(ei.enhancedSwapRouter), { symbol: 'EnhancedSwapRouter', chainId: 138 });
    }
    if (ei?.enhancedSwapRouterV2) {
        contracts.push(ei.enhancedSwapRouterV2);
        addresses.set(normAddr(ei.enhancedSwapRouterV2), { symbol: 'EnhancedSwapRouterV2', chainId: 138 });
    }
    for (const pool of ei?.uniswapV3Native?.pools ?? []) {
        contracts.push(pool.pool);
        addresses.set(normAddr(pool.pool), { symbol: 'UniV3Pool', chainId: 138 });
    }
    const attestation = readJson((0, path_1.resolve)(projectRoot, 'config/chain138-iso20022-attestation.v1.json'));
    for (const addr of Object.values(attestation?.contracts ?? {})) {
        if (addr.startsWith('0x') && addr.length === 42) {
            contracts.push(addr);
            addresses.set(normAddr(addr), { chainId: 138 });
        }
    }
    const mapping = readJson((0, path_1.resolve)(projectRoot, 'config/token-mapping-multichain.json'));
    for (const [c, cw] of Object.entries(mapping?.cToCwSymbolMapping ?? config.cToCwSymbolMapping)) {
        symbols.add(c);
        symbols.add(cw);
        cwSymbols.add(cw);
    }
    for (const pair of mapping?.pairs ?? []) {
        for (const tok of pair.tokens ?? []) {
            if (tok.addressFrom?.startsWith('0x') && tok.addressFrom.length === 42 && pair.fromChainId === 138) {
                addresses.set(normAddr(tok.addressFrom), { symbol: tok.key, chainId: 138 });
            }
            if (tok.addressTo?.startsWith('0x') && tok.addressTo.length === 42 && tok.addressTo !== '0x0000000000000000000000000000000000000000') {
                const sym = tok.key.includes('_cW') ? config.cToCwSymbolMapping[tok.key.replace('Compliant_', '').replace('_cW', '')] ?? tok.key : tok.key;
                addresses.set(normAddr(tok.addressTo), { symbol: sym, chainId: pair.toChainId });
                if (String(sym).startsWith('cW'))
                    cwSymbols.add(String(sym));
            }
        }
    }
    return {
        chainId: config.chain138.chainId,
        chainNames: config.chain138.names.map((n) => n.toLowerCase()),
        symbols,
        cwSymbols,
        addresses,
        instructionPrefixes: config.matchHints.instructionIdPrefixes,
        remittanceKeywords: config.matchHints.remittanceKeywords.map((k) => k.toLowerCase()),
        contracts,
    };
}
function collectSearchableFields(parsed, prefix = '') {
    const out = [];
    for (const [k, v] of Object.entries(parsed)) {
        const path = prefix ? `${prefix}.${k}` : k;
        if (v == null)
            continue;
        if (typeof v === 'string')
            out.push(v);
        else if (typeof v === 'number' || typeof v === 'boolean')
            out.push(String(v));
        else if (Array.isArray(v)) {
            for (const item of v) {
                if (typeof item === 'string')
                    out.push(item);
                else if (item && typeof item === 'object')
                    out.push(...collectSearchableFields(item, path));
            }
        }
        else if (typeof v === 'object') {
            out.push(...collectSearchableFields(v, path));
        }
    }
    return out;
}
//# sourceMappingURL=resourceRegistry.js.map