import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const projectRoot = path.resolve(__dirname, "..");

const removableDirs = [
  "dist",
  "Current",
  "tmp",
  ".codex-logs",
  ".playwright-cli",
  "output",
  "backups",
  "Release",
];

const removableFiles = [
  ".codex-api.err.log",
  ".codex-api.log",
  ".codex-api.out.log",
  ".codex-server.err.log",
  ".codex-server.out.log",
  ".codex-vite.err.log",
  ".codex-vite.out.log",
  ".codex-web.log",
  ".tmp-map-editor-api.err.log",
  ".tmp-map-editor-api.log",
  ".tmp-map-editor-vite.err.log",
  ".tmp-map-editor-vite.log",
];

function toAbsolute(relativePath) {
  return path.join(projectRoot, relativePath);
}

function safeRemoveDir(relativePath, removed) {
  const absolutePath = toAbsolute(relativePath);
  if (!fs.existsSync(absolutePath)) {
    return;
  }
  try {
    fs.rmSync(absolutePath, { recursive: true, force: true });
    removed.push(relativePath);
  } catch {
    // Ignore locked runtime folders so one open handle does not block the rest of cleanup.
  }
}

function safeRemoveFile(relativePath, removed) {
  const absolutePath = toAbsolute(relativePath);
  if (!fs.existsSync(absolutePath)) {
    return;
  }
  try {
    fs.rmSync(absolutePath, { force: true });
    removed.push(relativePath);
  } catch {
    // Ignore locked runtime files so cleanup can continue.
  }
}

function main() {
  const removedDirs = [];
  const removedFiles = [];

  removableDirs.forEach((dir) => safeRemoveDir(dir, removedDirs));
  removableFiles.forEach((file) => safeRemoveFile(file, removedFiles));

  const summary = {
    removedDirs,
    removedFiles,
  };

  process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`);
}

main();
