/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { fetchWithTimeout } from '@google/gemini-cli-core';
import { AsyncFzf } from 'fzf';
export class ExtensionRegistryClient {
    static REGISTRY_URL = 'https://geminicli.com/extensions.json';
    static FETCH_TIMEOUT_MS = 10000; // 10 seconds
    static fetchPromise = null;
    /** @internal */
    static resetCache() {
        ExtensionRegistryClient.fetchPromise = null;
    }
    async getExtensions(page = 1, limit = 10, orderBy = 'ranking') {
        const allExtensions = [...(await this.fetchAllExtensions())];
        switch (orderBy) {
            case 'ranking':
                allExtensions.sort((a, b) => a.rank - b.rank);
                break;
            case 'alphabetical':
                allExtensions.sort((a, b) => a.extensionName.localeCompare(b.extensionName));
                break;
            default: {
                const _exhaustiveCheck = orderBy;
                throw new Error(`Unhandled orderBy: ${_exhaustiveCheck}`);
            }
        }
        const startIndex = (page - 1) * limit;
        const endIndex = startIndex + limit;
        return {
            extensions: allExtensions.slice(startIndex, endIndex),
            total: allExtensions.length,
        };
    }
    async searchExtensions(query) {
        const allExtensions = await this.fetchAllExtensions();
        if (!query.trim()) {
            return allExtensions;
        }
        const fzf = new AsyncFzf(allExtensions, {
            selector: (ext) => `${ext.extensionName} ${ext.extensionDescription} ${ext.fullName}`,
            fuzzy: true,
        });
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
        const results = await fzf.find(query);
        // eslint-disable-next-line @typescript-eslint/no-unsafe-return
        return results.map((r) => r.item);
    }
    async getExtension(id) {
        const allExtensions = await this.fetchAllExtensions();
        return allExtensions.find((ext) => ext.id === id);
    }
    async fetchAllExtensions() {
        if (ExtensionRegistryClient.fetchPromise) {
            return ExtensionRegistryClient.fetchPromise;
        }
        ExtensionRegistryClient.fetchPromise = (async () => {
            try {
                const response = await fetchWithTimeout(ExtensionRegistryClient.REGISTRY_URL, ExtensionRegistryClient.FETCH_TIMEOUT_MS);
                if (!response.ok) {
                    throw new Error(`Failed to fetch extensions: ${response.statusText}`);
                }
                // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
                return (await response.json());
            }
            catch (error) {
                ExtensionRegistryClient.fetchPromise = null;
                throw error;
            }
        })();
        return ExtensionRegistryClient.fetchPromise;
    }
}
//# sourceMappingURL=extensionRegistryClient.js.map