/**
 * Runtime management (prune, disk usage, buildkit reset) via platform IPC.
 */
import path from "path";
import { getContext } from "../client.js";
import { writeIpcFile, pollJsonFile, clearStaleResult } from "../ipc.js";

function groupFolder(): string {
  return process.env.NANOCLAW_GROUP_FOLDER ?? "";
}

function messagesDir(ipcDir: string): string {
  return path.join(ipcDir, "messages");
}

export async function pruneRuntime(
  scope: "builder" | "images" | "images-all" | "volumes" | "all",
  ipcDir?: string
): Promise<unknown> {
  const dir = ipcDir ?? getContext().ipcDir;
  const resultFile = path.join(dir, "prune-result.json");
  clearStaleResult(resultFile);
  writeIpcFile(messagesDir(dir), { type: "runtime-prune", scope, groupFolder: groupFolder() });
  return pollJsonFile(
    resultFile,
    (d) => {
      const data = d as Record<string, unknown>;
      return Boolean(data.timestamp) && data.scope === scope;
    },
    120000,
  );
}

export async function getDiskUsage(ipcDir?: string): Promise<unknown> {
  const dir = ipcDir ?? getContext().ipcDir;
  const resultFile = path.join(dir, "disk-usage.json");
  clearStaleResult(resultFile);
  writeIpcFile(messagesDir(dir), { type: "runtime-disk-usage", groupFolder: groupFolder() });
  return pollJsonFile(resultFile, (d) => Boolean((d as Record<string, unknown>).timestamp), 30000);
}

export async function resetBuildkit(ipcDir?: string): Promise<unknown> {
  const dir = ipcDir ?? getContext().ipcDir;
  const resultFile = path.join(dir, "buildkit-reset-result.json");
  clearStaleResult(resultFile);
  writeIpcFile(messagesDir(dir), { type: "buildkit-reset", groupFolder: groupFolder() });
  return pollJsonFile(resultFile, (d) => Boolean((d as Record<string, unknown>).timestamp), 90000);
}
