import { normalizeAgentUrlKey } from "@rudderhq/shared";
import { createHash } from "node:crypto";
export const AGENT_WORKSPACE_SHORT_ID_MIN_LENGTH = 8;
export const AGENT_WORKSPACE_SHORT_ID_STEP = 4;
function normalizeAgentIdHex(agentId) {
    return agentId.trim().toLowerCase().replace(/[^a-f0-9]/g, "");
}
function ensureAgentWorkspaceIdSeed(agentId) {
    const normalized = normalizeAgentIdHex(agentId);
    if (normalized.length >= AGENT_WORKSPACE_SHORT_ID_MIN_LENGTH) {
        return normalized;
    }
    return createHash("sha1").update(agentId.trim()).digest("hex");
}
export function normalizeAgentWorkspaceSlug(value) {
    return normalizeAgentUrlKey(value) ?? "agent";
}
export function extractAgentWorkspaceShortId(agentId, length = AGENT_WORKSPACE_SHORT_ID_MIN_LENGTH) {
    const normalizedId = ensureAgentWorkspaceIdSeed(agentId);
    const safeLength = Math.max(AGENT_WORKSPACE_SHORT_ID_MIN_LENGTH, Math.min(length, normalizedId.length));
    return normalizedId.slice(0, safeLength);
}
export function buildAgentWorkspaceKey(name, agentId, shortIdLength = AGENT_WORKSPACE_SHORT_ID_MIN_LENGTH) {
    const slug = normalizeAgentWorkspaceSlug(name);
    const shortId = extractAgentWorkspaceShortId(agentId, shortIdLength);
    return `${slug}--${shortId}`;
}
export function deriveUniqueAgentWorkspaceKey(input) {
    const existingKeys = new Set(Array.from(input.existingKeys ?? [])
        .map((value) => value.trim())
        .filter((value) => value.length > 0));
    const normalizedId = ensureAgentWorkspaceIdSeed(input.agentId);
    for (let length = AGENT_WORKSPACE_SHORT_ID_MIN_LENGTH; length <= normalizedId.length; length = length === normalizedId.length ? normalizedId.length + 1 : Math.min(normalizedId.length, length + AGENT_WORKSPACE_SHORT_ID_STEP)) {
        const candidate = buildAgentWorkspaceKey(input.name, input.agentId, length);
        if (!existingKeys.has(candidate)) {
            return candidate;
        }
        if (length === normalizedId.length)
            break;
    }
    throw new Error(`Unable to allocate unique workspace key for agent "${input.agentId}".`);
}
export function resolveStoredOrDerivedAgentWorkspaceKey(agent) {
    const stored = agent.workspaceKey?.trim();
    if (stored)
        return stored;
    return buildAgentWorkspaceKey(agent.name, agent.id);
}
//# sourceMappingURL=agent-workspace-key.js.map