import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
export const WORKSPACE_PERMISSION_REPAIR_NEEDED_CODE = "workspace_permission_repair_needed";
export const MANAGED_WORKSPACE_CONFIGURATION_ERROR_CODE = "managed_workspace_configuration_error";
export class WorkspacePermissionPreflightError extends Error {
    errorCode = WORKSPACE_PERMISSION_REPAIR_NEEDED_CODE;
    failure;
    constructor(failure) {
        super(formatWorkspacePermissionPreflightMessage(failure));
        this.name = "WorkspacePermissionPreflightError";
        this.failure = failure;
    }
}
export class ManagedWorkspaceConfigurationError extends Error {
    errorCode = MANAGED_WORKSPACE_CONFIGURATION_ERROR_CODE;
    failure;
    constructor(failure) {
        super(formatManagedWorkspaceConfigurationErrorMessage(failure));
        this.name = "ManagedWorkspaceConfigurationError";
        this.failure = failure;
    }
}
function errorCode(error) {
    const code = error?.code;
    return typeof code === "string" && code.trim().length > 0 ? code : null;
}
function errorMessage(error) {
    return error instanceof Error ? error.message : String(error);
}
function toFailure(entry, operation, error) {
    return {
        kind: entry.kind,
        path: entry.path,
        operation,
        code: errorCode(error),
        message: errorMessage(error),
    };
}
export function formatWorkspacePermissionPreflightMessage(failure) {
    const codeSuffix = failure.code ? ` (${failure.code})` : "";
    return [
        `Rudder managed agent directory permission repair needed: managed ${failure.kind} path is not writable: ${failure.path}${codeSuffix}.`,
        "Repair the managed agent directory permissions, choose a writable organization workspace home with RUDDER_ORGANIZATION_WORKSPACE_HOME, or move RUDDER_HOME before starting the run.",
    ].join(" ");
}
export function formatManagedWorkspaceConfigurationErrorMessage(failure) {
    return [
        `Rudder runtime configuration error: managed ${failure.kind} path is missing before workspace preflight.`,
        "This is a Rudder runtime bootstrap bug; rebuild the run context before starting the run.",
    ].join(" ");
}
export function workspacePreflightPaths(input) {
    return [
        { kind: "agent_home", path: input.agentHome },
        { kind: "instructions", path: input.instructionsDir },
        { kind: "memory", path: input.memoryDir },
        { kind: "life", path: input.lifeDir },
        { kind: "skills", path: input.skillsDir },
    ];
}
function validatePreflightPath(entry) {
    if (entry.path.trim().length > 0)
        return;
    throw new ManagedWorkspaceConfigurationError({
        kind: entry.kind,
        path: entry.path,
        operation: "configure",
        code: "MISSING_PATH",
        message: "Managed workspace path is missing.",
    });
}
async function ensureDirectory(entry) {
    try {
        await fs.mkdir(entry.path, { recursive: true });
    }
    catch (error) {
        throw new WorkspacePermissionPreflightError(toFailure(entry, "mkdir", error));
    }
    try {
        const stat = await fs.stat(entry.path);
        if (!stat.isDirectory()) {
            throw new Error("Path exists but is not a directory");
        }
    }
    catch (error) {
        throw new WorkspacePermissionPreflightError(toFailure(entry, "stat", error));
    }
}
async function probeWritableDirectory(entry) {
    const probePath = path.join(entry.path, `.rudder-write-probe-${process.pid}-${randomUUID()}`);
    try {
        await fs.writeFile(probePath, "ok", { flag: "wx" });
    }
    catch (error) {
        throw new WorkspacePermissionPreflightError(toFailure(entry, "write_probe", error));
    }
    finally {
        await fs.rm(probePath, { force: true }).catch(() => undefined);
    }
}
export async function preflightManagedAgentWorkspace(input) {
    const entries = workspacePreflightPaths(input);
    for (const entry of entries) {
        validatePreflightPath(entry);
        await ensureDirectory(entry);
        await probeWritableDirectory(entry);
    }
    return entries;
}
export function isWorkspacePermissionPreflightError(error) {
    return error instanceof WorkspacePermissionPreflightError;
}
export function isManagedWorkspaceConfigurationError(error) {
    return error instanceof ManagedWorkspaceConfigurationError;
}
//# sourceMappingURL=managed-workspace-preflight.js.map