// engine/figma/thumbnail-fetcher.ts — Figma Images API thumbnail fetcher (SPEC-424)
const FIGMA_API_BASE = 'https://api.figma.com/v1';
const BATCH_SIZE = 50;
function sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}
export function chunkArray(arr, size) {
    const chunks = [];
    for (let i = 0; i < arr.length; i += size) {
        chunks.push(arr.slice(i, i + size));
    }
    return chunks;
}
export async function fetchThumbnailUrls(fileKey, nodeIds, accessToken) {
    const batches = chunkArray(nodeIds, BATCH_SIZE);
    const merged = {};
    for (let i = 0; i < batches.length; i++) {
        if (i > 0) {
            await sleep(1000);
        }
        const batch = batches[i];
        if (batch === undefined || batch.length === 0) {
            continue;
        }
        const encodedIds = encodeURIComponent(batch.join(','));
        const url = `${FIGMA_API_BASE}/images/${fileKey}?ids=${encodedIds}&format=png&scale=1`;
        let response;
        try {
            response = await fetch(url, {
                headers: { 'X-Figma-Token': accessToken },
            });
        }
        catch (err) {
            console.error(`Figma Images API fetch error for batch ${i}:`, err);
            continue;
        }
        if (!response.ok) {
            console.error(`Figma Images API error ${response.status} for batch ${i}`);
            continue;
        }
        const data = (await response.json());
        Object.assign(merged, data.images);
    }
    return merged;
}
export function buildThumbnailMarkdown(nodeIdToName, thumbnails) {
    const lines = [];
    for (const [nodeId, url] of Object.entries(thumbnails)) {
        if (url === null) {
            continue;
        }
        const name = nodeIdToName[nodeId] ?? nodeId;
        lines.push(`- [${name}](${url})`);
    }
    return lines.join('\n');
}
//# sourceMappingURL=thumbnail-fetcher.js.map