"use strict";
var BrowserAgent;
(function (BrowserAgent) {
    BrowserAgent.CONFIG_KEY = "browserAgentConfig";
    // BUILD_BACKEND_URL and BUILD_LIVE_BACKEND_URL are declared in
    // src/build-config.ts (generated).  At runtime under Vitest, namespace
    // merging across files doesn't happen, so we guard with `typeof` and fall
    // back to the dev default.
    const resolvedBackendUrl = typeof BrowserAgent.BUILD_BACKEND_URL !== "undefined" ? BrowserAgent.BUILD_BACKEND_URL : "http://localhost:8787";
    BrowserAgent.LIVE_BACKEND_URL = typeof BrowserAgent.BUILD_LIVE_BACKEND_URL !== "undefined" ? BrowserAgent.BUILD_LIVE_BACKEND_URL : "https://utility.lecoindulmnp.fr";
    BrowserAgent.DEBUG_LIVE_API_KEY = "debugLiveApi";
    BrowserAgent.DEFAULT_CONFIG = {
        serverUrl: resolvedBackendUrl,
        authToken: "",
        model: "MiniMax-M2.7-highspeed",
        requestTimeoutMs: 30000,
        maxSteps: 12,
        maxDomTextChars: 60000,
        maxScreenshotWidth: 1280,
        captureDom: true,
        captureScreenshot: true,
        autopilot: true
    };
    function mergeConfig(value) {
        const v = value || {};
        return {
            ...BrowserAgent.DEFAULT_CONFIG,
            ...v,
            // Never let a stored empty string override a useful default
            serverUrl: v.serverUrl?.trim() || BrowserAgent.DEFAULT_CONFIG.serverUrl,
            model: v.model?.trim() || BrowserAgent.DEFAULT_CONFIG.model,
            requestTimeoutMs: numberOrDefault(v.requestTimeoutMs, BrowserAgent.DEFAULT_CONFIG.requestTimeoutMs),
            maxSteps: numberOrDefault(v.maxSteps, BrowserAgent.DEFAULT_CONFIG.maxSteps),
            maxDomTextChars: numberOrDefault(v.maxDomTextChars, BrowserAgent.DEFAULT_CONFIG.maxDomTextChars),
            maxScreenshotWidth: numberOrDefault(v.maxScreenshotWidth, BrowserAgent.DEFAULT_CONFIG.maxScreenshotWidth),
            captureDom: v.captureDom ?? BrowserAgent.DEFAULT_CONFIG.captureDom,
            captureScreenshot: v.captureScreenshot ?? BrowserAgent.DEFAULT_CONFIG.captureScreenshot,
            autopilot: v.autopilot ?? BrowserAgent.DEFAULT_CONFIG.autopilot
        };
    }
    BrowserAgent.mergeConfig = mergeConfig;
    function numberOrDefault(value, fallback) {
        const parsed = typeof value === "number" ? value : Number(value);
        return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
    }
    BrowserAgent.numberOrDefault = numberOrDefault;
    function endpointUrl(config, path) {
        return `${config.serverUrl.replace(/\/+$/, "")}${path}`;
    }
    BrowserAgent.endpointUrl = endpointUrl;
    async function getStoredConfig() {
        return new Promise((resolve) => {
            chrome.storage.local.get([BrowserAgent.CONFIG_KEY, BrowserAgent.DEBUG_LIVE_API_KEY], (items) => {
                const stored = items[BrowserAgent.CONFIG_KEY];
                const merged = mergeConfig(stored);
                if (items[BrowserAgent.DEBUG_LIVE_API_KEY] === true && BrowserAgent.LIVE_BACKEND_URL) {
                    merged.serverUrl = BrowserAgent.LIVE_BACKEND_URL;
                }
                resolve(merged);
            });
        });
    }
    BrowserAgent.getStoredConfig = getStoredConfig;
    async function getBackendBaseUrl() {
        const config = await getStoredConfig();
        return config.serverUrl.replace(/\/+$/, "");
    }
    BrowserAgent.getBackendBaseUrl = getBackendBaseUrl;
    function validateConfig(config) {
        if (!config.serverUrl.trim()) {
            return {
                code: "CONFIG_MISSING_SERVER_URL",
                message: "Server URL is required.",
                suggestion: "Enter your proxy base URL, for example http://localhost:8787."
            };
        }
        try {
            const url = new URL(config.serverUrl);
            if (!["http:", "https:"].includes(url.protocol)) {
                return {
                    code: "CONFIG_INVALID_PROTOCOL",
                    message: "Server URL must use http or https.",
                    suggestion: "Use the base URL of your browser-agent proxy."
                };
            }
        }
        catch (error) {
            return {
                code: "CONFIG_INVALID_SERVER_URL",
                message: "Server URL is not a valid URL.",
                details: normalizeError(error)
            };
        }
        if (!config.model.trim()) {
            return {
                code: "CONFIG_MISSING_MODEL",
                message: "Model is required.",
                suggestion: "Use the model name expected by your proxy."
            };
        }
        return null;
    }
    BrowserAgent.validateConfig = validateConfig;
    function normalizeError(error, code = "UNKNOWN_ERROR", suggestion) {
        if (error && typeof error === "object" && "message" in error) {
            return {
                code,
                message: String(error.message),
                details: stringifyDetails(error),
                suggestion
            };
        }
        return {
            code,
            message: String(error || "Unknown error"),
            suggestion
        };
    }
    BrowserAgent.normalizeError = normalizeError;
    function actionId(action, fallbackPrefix = "action") {
        return action.id || `${fallbackPrefix}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
    }
    BrowserAgent.actionId = actionId;
    function createId(prefix) {
        const cryptoValue = globalThis.crypto?.randomUUID?.();
        return cryptoValue ? `${prefix}_${cryptoValue}` : `${prefix}_${Date.now()}_${Math.random().toString(16).slice(2)}`;
    }
    BrowserAgent.createId = createId;
    function nowIso() {
        return new Date().toISOString();
    }
    BrowserAgent.nowIso = nowIso;
    function truncateText(text, maxChars) {
        if (text.length <= maxChars) {
            return { text, truncated: false };
        }
        return {
            text: `${text.slice(0, maxChars)}\n\n[truncated ${text.length - maxChars} chars]`,
            truncated: true
        };
    }
    BrowserAgent.truncateText = truncateText;
    function stringifyDetails(error) {
        try {
            return JSON.parse(JSON.stringify(error));
        }
        catch {
            return String(error);
        }
    }
})(BrowserAgent || (BrowserAgent = {}));
//# sourceMappingURL=shared.js.map