/*
 * Runtime storage plane / composition surface.
 * Purpose: resolve .rax/.rax_workspace, build layout, and provide an init plan
 * that Kernel or rax commands can apply explicitly.
 */
import { resolveRaxHome, resolveRaxWorkspace, } from "./raxPathResolver.js";
import { createRaxStorageLayout } from "./raxStorageLayout.js";
import { applyRaxStorageInitPlan, planRaxStorageInit, } from "./raxStorageInit.js";
function passThroughFailure(result, events) {
    if (result.ok) {
        throw new Error("expected storage plane failure");
    }
    return {
        ok: false,
        error: result.error,
        events: [...events, ...result.events],
    };
}
export function createStoragePlaneRuntime(input = {}) {
    const events = [];
    const home = resolveRaxHome({
        explicitHome: input.raxHome,
        homeDir: input.homeDir,
        env: input.env,
    });
    if (!home.ok) {
        return passThroughFailure(home, events);
    }
    events.push(...home.events);
    const workspace = resolveRaxWorkspace({
        cwd: input.cwd,
        explicitWorkspaceRoot: input.workspaceRoot,
    });
    if (!workspace.ok) {
        return passThroughFailure(workspace, events);
    }
    events.push(...workspace.events);
    const layout = createRaxStorageLayout({
        raxHomeRoot: home.value.root,
        raxWorkspaceRoot: workspace.value.root,
        agentId: input.agentId,
    });
    if (!layout.ok) {
        return passThroughFailure(layout, events);
    }
    events.push(...layout.events);
    return {
        ok: true,
        runtime: {
            kind: "praxis.storagePlaneRuntime",
            home: home.value,
            workspace: workspace.value,
            layout: layout.value,
            initPlan: planRaxStorageInit(layout.value),
            initMode: input.initMode ?? "manual",
            publicSafe: true,
        },
        events: [...events, "runtime.storagePlaneRuntime.created"],
    };
}
export async function createAndApplyStoragePlaneRuntime(input = {}) {
    const runtime = createStoragePlaneRuntime(input);
    if (!runtime.ok) {
        return runtime;
    }
    const init = await applyRaxStorageInitPlan(runtime.runtime.initPlan);
    return {
        ok: true,
        runtime: runtime.runtime,
        init,
        events: [...runtime.events, ...init.events],
    };
}
export { resolveRaxHome, resolveRaxWorkspace, } from "./raxPathResolver.js";
export { createRaxStorageLayout, } from "./raxStorageLayout.js";
export { applyRaxStorageInitPlan, planRaxStorageInit, } from "./raxStorageInit.js";
