#!/usr/bin/env node

import { access, mkdir, rename, rm } from 'node:fs/promises';
import path from 'node:path';

const root = process.cwd();
const generated = path.join(root, 'apps', 'web', '.next');
const quarantineRoot = path.join(root, '.mosaic-test-work', 'generated-quarantine');

try {
  await access(generated);
} catch (error) {
  if (error.code === 'ENOENT') process.exit(0);
  throw error;
}

await mkdir(quarantineRoot, { recursive: true });
const quarantine = path.join(quarantineRoot, `web-next-${Date.now()}-${process.pid}`);
try {
  await rename(generated, quarantine);
} catch (error) {
  console.error(
    `MOSAIC_GENERATED_CLEAN_FAILED: could not quarantine apps/web/.next. Fix: sudo rm -rf '${generated}', then rerun pnpm preflight`,
  );
  throw error;
}

try {
  await rm(quarantine, { recursive: true, force: true });
} catch {
  console.warn(
    `Generated state was deactivated but could not be deleted; quarantined at ${quarantine}`,
  );
}
