import { createHash } from "node:crypto";
import { safeSummary } from "./memory-audit-event-builders.js";
function maskedCoordinate(value, redactString) {
    const redacted = redactString(value);
    if (redacted !== value) {
        return redacted;
    }
    const digest = createHash("sha256").update(value).digest("hex").slice(0, 12);
    return `[redacted:${digest}]`;
}
export function sanitizeMemoryScope(scope, redactString) {
    switch (scope.kind) {
        case "user":
            return {
                kind: "user",
                userId: maskedCoordinate(scope.userId, redactString),
            };
        case "workspace":
            return {
                kind: "workspace",
                workspaceId: maskedCoordinate(scope.workspaceId, redactString),
            };
        case "project":
            return {
                kind: "project",
                projectId: maskedCoordinate(scope.projectId, redactString),
            };
        case "workflow":
            return {
                kind: "workflow",
                workflowDefinitionId: maskedCoordinate(scope.workflowDefinitionId, redactString),
            };
        case "global":
            return { kind: "global" };
        default: {
            const never = scope;
            return never;
        }
    }
}
export function memoryScopeKey(scope) {
    switch (scope.kind) {
        case "user":
            return `user:${scope.userId}`;
        case "workspace":
            return `workspace:${scope.workspaceId}`;
        case "project":
            return `project:${scope.projectId}`;
        case "workflow":
            return `workflow:${scope.workflowDefinitionId}`;
        case "global":
            return "global";
        default: {
            const never = scope;
            return never;
        }
    }
}
export function sanitizeAuditEvent(event, redactString) {
    const redactedSummary = safeSummary(event.summary, redactString);
    switch (event.kind) {
        case "memory:retrieved":
            return {
                ...event,
                summary: redactedSummary,
                scopes: event.scopes.map((scope) => sanitizeMemoryScope(scope, redactString)),
            };
        case "memory:workflow-used":
            return { ...event, summary: redactedSummary };
        default:
            return {
                ...event,
                summary: redactedSummary,
                scope: sanitizeMemoryScope(event.scope, redactString),
            };
    }
}
export function auditEventTouchesScope(event, allowedScopeKeys) {
    switch (event.kind) {
        case "memory:retrieved":
            return event.scopes.some((scope) => allowedScopeKeys.has(memoryScopeKey(scope)));
        case "memory:workflow-used":
            return false;
        default:
            return allowedScopeKeys.has(memoryScopeKey(event.scope));
    }
}
