/**
 * Network adapter for browser extensions.
 * Provides a consistent interface for network requests, 
 * moving away from GM_xmlhttpRequest.
 */
class NetworkAdapter {
    /**
     * Performs a fetch request.
     * In Manifest V3, this can be done from the service worker or content script 
     * depending on host permissions.
     */
    async request(url, options = {}) {
        try {
            const response = await fetch(url, options);
            return {
                ok: response.ok,
                status: response.status,
                statusText: response.statusText,
                data: await this._parseResponse(response),
                headers: Object.fromEntries(response.headers.entries())
            };
        } catch (error) {
            console.error("Network request failed", error);
            return {
                ok: false,
                status: 0,
                error: error.message
            };
        }
    }

    async _parseResponse(response) {
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
            return await response.json();
        }
        return await response.text();
    }
}

window.LlamaNetworkAdapter = NetworkAdapter;
