// Node 22+. Run: node affix-prices.mjs <active-cycle-id>
import assert from 'node:assert/strict';
import { pathToFileURL } from 'node:url';

export function createAffixPriceReader(cycle) {
    assert(
        typeof cycle === 'string' && /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(cycle),
        'Choose a cycle ID',
    );
    let cached;
    let prices = [];

    return {
        async refresh() {
            prices = [];
            const response = await fetch(
                `https://bazaar.leoverlay.com/v1/pricing/affixes?cycle=${
                    encodeURIComponent(cycle)
                }`,
                {
                    headers: cached?.etag ? { 'If-None-Match': cached.etag } : {},
                    signal: AbortSignal.timeout(10_000),
                },
            );
            if (!response.ok && !(response.status === 304 && cached)) {
                const error = new Error(`HTTP ${response.status} reading affix prices`);
                error.retryAfter = response.headers.get('retry-after');
                throw error;
            }
            const feed = response.status === 304 ? cached.body : await response.json();
            assert.equal(feed.schemaVersion, 1, 'Unsupported feed schema');
            assert.equal(feed.cycle, cycle, 'Wrong cycle');
            assert(Array.isArray(feed.quotes), 'Invalid quotes');
            for (const quote of feed.quotes) {
                assert(
                    Number.isInteger(quote.identity?.itemType)
                        && Number.isInteger(quote.identity?.affixId),
                    'Invalid identity',
                );
                assert([5, 6].includes(quote.identity.tier), 'Invalid stored tier');
                assert(
                    ['available', 'insufficient-data', 'stale'].includes(quote.status),
                    'Unknown status',
                );
                if (quote.status === 'available') {
                    assert(
                        quote.medianGold > 0 && Number.isFinite(quote.expiresAt),
                        'Invalid price',
                    );
                }
            }
            if (response.status !== 304) {
                cached = { body: feed, etag: response.headers.get('etag') };
            }
            prices = feed.quotes;
        },
        getAffixPrices() {
            return prices.filter(quote =>
                quote.status === 'available' && quote.expiresAt > Date.now()
            );
        },
    };
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
    try {
        const reader = createAffixPriceReader(process.argv[2]);
        await reader.refresh();
        console.log(JSON.stringify(reader.getAffixPrices(), null, 2));
    } catch (error) {
        console.error(error.message);
        if (error.retryAfter) console.error(`Retry-After: ${error.retryAfter}`);
        process.exitCode = 1;
    }
}
