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

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

export function createIdolPriceReader(cycle) {
    const cache = new Map();
    let prices = [];
    let nextRequestAt = 0;

    async function readJson(url, paced = false) {
        if (paced) {
            await setTimeout(Math.max(0, nextRequestAt - Date.now()));
            nextRequestAt = Date.now() + 3_000; // Leave room within the shared 30/minute limit.
        }

        const cached = cache.get(url);
        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.body; // This does not extend quote expiry.
        }
        if (!response.ok) {
            const error = new Error(`HTTP ${response.status} reading ${url}`);
            error.status = response.status;
            error.retryAfter = response.headers.get('retry-after');
            throw error;
        }

        const body = await response.json();
        cache.set(url, { body, etag: response.headers.get('etag') });
        return body;
    }

    return {
        async refresh() {
            prices = []; // Failed refreshes must not leave usable-looking old results.
            const found = new Map();
            let catalogue;
            let pageCount = 1;

            for (let page = 0; page < pageCount; page++) {
                const query = new URLSearchParams({ cycle, page: String(page) });
                const data = await readJson(
                    `${API_ORIGIN}/v1/pricing/idols?${query}`,
                    true,
                );
                assert.equal(data.schemaVersion, 1, 'Unsupported idol feed schema');
                assert.equal(data.cycle, cycle, 'Wrong cycle');
                assert.equal(data.page, page, 'Wrong page');
                assert.equal(data.pageSize, 50, 'Unsupported page size');
                assert(Number.isSafeInteger(data.total) && data.total >= 0, 'Invalid total');
                assert(Array.isArray(data.quotes), 'Invalid quotes');

                if (page === 0) {
                    pageCount = Math.ceil(data.total / data.pageSize);
                    assert(pageCount <= 10_001, 'Page count exceeds the API pagination limit');
                    if (!data.quotes.length) {
                        return;
                    }
                    assert(/^[0-9a-f]{64}$/.test(data.catalogueRevision), 'Invalid revision');
                    catalogue = await readJson(
                        `${CATALOGUE_ORIGIN}/catalogue/idols/${data.catalogueRevision}/catalogue.json`,
                    );
                    assert.equal(catalogue.schemaVersion, 1, 'Unsupported idol catalogue');
                }
                assert.equal(
                    catalogue.catalogueRevision,
                    data.catalogueRevision,
                    'Revision changed; refresh again',
                );

                for (const quote of data.quotes) {
                    assert(
                        ['available', 'stale', 'insufficient-data'].includes(quote.status),
                        'Unknown status',
                    );
                    assert(Number.isFinite(quote.expiresAt), 'Invalid expiry');
                    const identity = quote.identity;
                    assert.equal(identity?.cycle, cycle, 'Missing or mismatched identity');
                    const base = catalogue.bases.find(base =>
                        base.itemType === identity.itemType && base.subType === identity.subType
                    );
                    assert(base, 'Unknown idol base');
                    const affixes = identity.affixes.map(affix => {
                        const definition = catalogue.affixes.find(entry => entry.id === affix.id);
                        assert(definition, `Unknown affix ${affix.id}`);
                        return { ...affix, name: definition.names['en-US'] };
                    });
                    if (quote.status === 'available') {
                        assert(quote.medianGold > 0, 'Available quote has no price');
                    }
                    found.set(quote.id, {
                        ...quote,
                        name: base.names['en-US'],
                        iconUrl: new URL(base.iconUrl, CATALOGUE_ORIGIN).href,
                        affixes,
                    });
                }
                if (!data.quotes.length) {
                    break;
                }
            }

            prices = [...found.values()]; // Cohorts can move between pages during a refresh.
        },
        getIdolPrices() {
            return prices.filter(quote =>
                quote.status === 'available' && quote.expiresAt > Date.now()
            );
        },
    };
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
    const cycle = process.argv[2];
    if (!cycle) {
        console.error('Usage: node idol-prices.mjs <active-cycle-id>');
        process.exitCode = 1;
    } else {
        try {
            const reader = createIdolPriceReader(cycle);
            await reader.refresh();
            console.log(JSON.stringify(reader.getIdolPrices(), null, 2));
        } catch (error) {
            console.error(error.message);
            if (error.retryAfter) {
                console.error(`Retry-After: ${error.retryAfter}`);
            }
            process.exitCode = 1;
        }
    }
}
