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

const API_ORIGIN = 'https://bazaar.leoverlay.com';
const CATALOGUE_ORIGIN = 'https://www.leoverlay.com';

async function readJson(url, cached) {
    const response = await fetch(url, {
        headers: cached?.etag ? { 'If-None-Match': cached.etag } : {},
        signal: AbortSignal.timeout(10_000),
    });
    if (response.status === 304 && cached) {
        return cached; // Reusing a body does not extend quote expiry.
    }
    if (!response.ok) {
        const error = new Error('HTTP ' + response.status + ' reading ' + url);
        error.retryAfter = response.headers.get('retry-after');
        throw error;
    }
    return { body: await response.json(), etag: response.headers.get('etag') };
}

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

    return {
        async refresh() {
            prices = [];
            const result = await readJson(
                API_ORIGIN + '/v1/pricing/uniques?cycle=' + encodeURIComponent(cycle),
                feedCache,
            );
            const feed = result.body;
            assert.equal(feed.schemaVersion, 1, 'Unsupported feed schema');
            assert.equal(feed.cycle, cycle, 'Wrong cycle');
            assert(Array.isArray(feed.quotes), 'Invalid quotes');

            if (feed.catalogueRevision === null) {
                assert.equal(feed.quotes.length, 0, 'Missing catalogue for quotes');
                feedCache = result;
                return;
            }
            assert(/^[0-9a-f]{40}$/.test(feed.catalogueRevision), 'Invalid catalogue revision');
            if (catalogueCache?.body.catalogueRevision !== feed.catalogueRevision) {
                catalogueCache = await readJson(
                    CATALOGUE_ORIGIN + '/catalogue/uniques/' + feed.catalogueRevision + '.json',
                );
            }
            const catalogue = catalogueCache.body;
            assert.equal(catalogue.schemaVersion, 4, 'Unsupported catalogue schema');
            assert.equal(catalogue.catalogueRevision, feed.catalogueRevision, 'Wrong catalogue');
            const items = new Map(catalogue.uniques.map(item => [item.uniqueId, item]));
            const resolved = feed.quotes.map(quote => {
                const item = items.get(quote.identity?.uniqueId);
                assert(item, 'Unknown unique');
                assert([0, 1, 2, 3, 4].includes(quote.identity.legendaryPotential), 'Invalid LP');
                assert(Array.isArray(quote.identity.variantAffixIds), 'Missing variant identity');
                assert(
                    ['available', 'last-known', 'insufficient-data', 'stale', 'unavailable']
                        .includes(quote.status),
                    'Unknown status',
                );
                if (quote.status === 'available') {
                    assert(
                        quote.medianGold > 0 && Number.isFinite(quote.expiresAt),
                        'Invalid price',
                    );
                }
                return { ...quote, name: item.names['en-US'] || 'Unique #' + item.uniqueId };
            });

            feedCache = result;
            prices = resolved;
        },
        getUniquePrices() {
            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 = createUniquePriceReader(process.argv[2]);
        await reader.refresh();
        console.log(JSON.stringify(reader.getUniquePrices(), null, 2));
    } catch (error) {
        console.error(error.message);
        if (error.retryAfter) console.error('Retry-After: ' + error.retryAfter);
        process.exitCode = 1;
    }
}
