"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchDynamicTokens = fetchDynamicTokens;
exports.getDynamicTokensForChain = getDynamicTokensForChain;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const os_1 = __importDefault(require("os"));
const CACHE_FILE = path_1.default.join(os_1.default.homedir(), '.nyxora', 'dynamic_tokens.json');
const CACHE_TTL = 24 * 60 * 60 * 1000; // 24 hours
const TOKEN_LIST_URLS = {
    ethereum: 'https://tokens.coingecko.com/uniswap/all.json',
    base: 'https://raw.githubusercontent.com/ethereum-optimism/ethereum-optimism.github.io/master/optimism.tokenlist.json',
    arbitrum: 'https://bridge.arbitrum.io/token-list-42161.json',
    optimism: 'https://static.optimism.io/optimism.tokenlist.json',
    bsc: 'https://tokens.pancakeswap.finance/pancakeswap-extended.json'
};
async function fetchDynamicTokens() {
    // Check cache first
    try {
        if (fs_1.default.existsSync(CACHE_FILE)) {
            const stats = fs_1.default.statSync(CACHE_FILE);
            if (Date.now() - stats.mtimeMs < CACHE_TTL) {
                return JSON.parse(fs_1.default.readFileSync(CACHE_FILE, 'utf-8'));
            }
        }
    }
    catch (e) {
        // Ignore cache error
    }
    const result = {};
    console.log('[DynamicTokenUpdater] Fetching updated token lists...');
    for (const [chain, url] of Object.entries(TOKEN_LIST_URLS)) {
        try {
            const res = await fetch(url);
            const data = await res.json();
            let tokens = [];
            if (data && data.tokens && Array.isArray(data.tokens)) {
                // Limit to top 50 to avoid massive multicall
                const topTokens = data.tokens.slice(0, 50);
                tokens = topTokens.map((t) => ({
                    symbol: t.symbol,
                    address: t.address
                }));
            }
            result[chain] = tokens;
        }
        catch (err) {
            console.warn(`[DynamicTokenUpdater] Failed to fetch list for ${chain}:`, err);
            result[chain] = [];
        }
    }
    // Save to cache
    try {
        fs_1.default.writeFileSync(CACHE_FILE, JSON.stringify(result, null, 2), 'utf-8');
    }
    catch (e) {
        console.error('[DynamicTokenUpdater] Failed to write cache', e);
    }
    return result;
}
async function getDynamicTokensForChain(chainName) {
    const allTokens = await fetchDynamicTokens();
    return allTokens[chainName] || [];
}
