
import { encodeBase64, VSBuffer } from '../../../base/common/buffer.js';
import { Schemas } from '../../../base/common/network.js';
import { URI } from '../../../base/common/uri.js';

const AGENT_HOST_SCHEME = "vscode-agent-host";
function toAgentHostUri(originalUri, connectionAuthority) {
    if (connectionAuthority === "local" && originalUri.scheme === Schemas.file) {
        return originalUri;
    }
    const originalAuthority = originalUri.authority || "";
    return ( URI.from({
        scheme: AGENT_HOST_SCHEME,
        authority: connectionAuthority,
        path: `/${originalUri.scheme}/${originalAuthority || "-"}${originalUri.path}`
    }));
}
function fromAgentHostUri(agentHostUri) {
    if (agentHostUri.scheme !== AGENT_HOST_SCHEME) {
        return agentHostUri;
    }
    const path = agentHostUri.path;
    const schemeEnd = path.indexOf("/", 1);
    if (schemeEnd === -1) {
        return ( URI.from({
            scheme: "file",
            path
        }));
    }
    const originalScheme = path.substring(1, schemeEnd);
    const authorityEnd = path.indexOf("/", schemeEnd + 1);
    if (authorityEnd === -1) {
        const originalAuthority = path.substring(schemeEnd + 1);
        return ( URI.from({
            scheme: originalScheme,
            authority: originalAuthority,
            path: "/"
        }));
    }
    let originalAuthority = path.substring(schemeEnd + 1, authorityEnd);
    if (originalAuthority === "-") {
        originalAuthority = "";
    }
    const originalPath = path.substring(authorityEnd);
    return ( URI.from({
        scheme: originalScheme,
        authority: originalAuthority || undefined,
        path: originalPath
    }));
}
function normalizeRemoteAgentHostAddress(address) {
    if (address.startsWith("ws://")) {
        return address.slice("ws://".length);
    }
    return address;
}
function agentHostAuthority(address) {
    const normalized = normalizeRemoteAgentHostAddress(address);
    if (/^[a-zA-Z0-9]+$/.test(normalized)) {
        return normalized;
    }
    if (/^[a-zA-Z0-9.:\-]+$/.test(normalized)) {
        return normalized.replaceAll(":", "__");
    }
    return `b64-${encodeBase64(VSBuffer.fromString(normalized), false, true)}`;
}
const AGENT_HOST_LABEL_FORMATTER = {
    scheme: AGENT_HOST_SCHEME,
    formatting: {
        label: "${path}",
        separator: "/",
        stripPathSegments: 2
    }
};

export { AGENT_HOST_LABEL_FORMATTER, AGENT_HOST_SCHEME, agentHostAuthority, fromAgentHostUri, normalizeRemoteAgentHostAddress, toAgentHostUri };
