export * from "./gen/types.gen.js";
import { createClient } from "./gen/client/client.gen.js";
import { KiloClient } from "./gen/sdk.gen.js";
export { KiloClient };
function pick(value, fallback, encode) {
    if (!value)
        return;
    if (!fallback)
        return value;
    if (value === fallback)
        return fallback;
    if (encode && value === encode(fallback))
        return fallback;
    return value;
}
function rewrite(request, values) {
    if (request.method !== "GET" && request.method !== "HEAD")
        return request;
    const url = new URL(request.url);
    let changed = false;
    for (const [name, key] of [
        ["x-kilo-directory", "directory"],
        ["x-kilo-workspace", "workspace"],
    ]) {
        const value = pick(request.headers.get(name), key === "directory" ? values.directory : values.workspace, key === "directory" ? encodeURIComponent : undefined);
        if (!value)
            continue;
        if (!url.searchParams.has(key)) {
            url.searchParams.set(key, value);
        }
        changed = true;
    }
    if (!changed)
        return request;
    const next = new Request(url, request);
    next.headers.delete("x-kilo-directory");
    next.headers.delete("x-kilo-workspace");
    return next;
}
export function createKiloClient(config) {
    if (!config?.fetch) {
        const customFetch = (req) => {
            // Pass duplex in the init arg so it survives VS Code's proxy-agent
            // fetch wrapper, which calls originalFetch(request, { ...init, dispatcher })
            // and would otherwise drop duplex from the cloned Request.
            // timeout: false disables Bun's default request timeout for long-running
            // streaming calls (replaces the old req.timeout = false assignment which
            // wouldn't survive the clone triggered by passing an init object).
            return fetch(req, { duplex: "half", timeout: false });
        };
        config = {
            ...config,
            fetch: customFetch,
        };
    }
    if (config?.directory) {
        config.headers = {
            ...config.headers,
            "x-kilo-directory": encodeURIComponent(config.directory),
        };
    }
    if (config?.experimental_workspaceID) {
        config.headers = {
            ...config.headers,
            "x-kilo-workspace": config.experimental_workspaceID,
        };
    }
    // Node.js/Electron require duplex: "half" when creating Request objects
    // with a body. The option propagates through config → opts → requestInit
    // and is harmless in environments that don't need it (Bun, browsers).
    ;
    config.duplex = "half";
    const client = createClient(config);
    client.interceptors.request.use((request) => rewrite(request, {
        directory: config?.directory,
        workspace: config?.experimental_workspaceID,
    }));
    client.interceptors.response.use((response) => {
        const contentType = response.headers.get("content-type");
        if (contentType === "text/html")
            throw new Error("Request is not supported by this version of OpenCode Server (Server responded with text/html)");
        return response;
    });
    // The generated client falls back to throwing a literal `{}` when the server
    // responds with an empty / unparseable error body, which surfaces as a bare
    // `{}` in TUI / CLI error output. Wrap ONLY that case in a real Error so
    // downstream formatters get a useful message — but pass through any parsed
    // JSON error body unchanged so existing consumers can still inspect fields.
    client.interceptors.error.use((error, response, request) => {
        const isEmpty = error === undefined ||
            error === null ||
            error === "" ||
            (typeof error === "object" && !(error instanceof Error) && Object.keys(error).length === 0);
        if (!isEmpty)
            return error;
        const method = request?.method ?? "?";
        const url = request?.url ?? "?";
        if (!response)
            return new Error(`kilo server ${method} ${url}: network error (no response)`);
        const status = response.status;
        const statusText = response.statusText ? " " + response.statusText : "";
        return new Error(`kilo server ${method} ${url} → ${status}${statusText}: (empty response body)`);
    });
    return new KiloClient({ client });
}
