import { existsSync, readdirSync, rmSync } from 'node:fs';
import { basename, join, resolve } from 'node:path';

const cwd = process.cwd();
const outDir = resolve(cwd, process.env.APP_DIST_DIR?.trim() || 'app-dist');
const backupPrefix = 'assets.root-owned-backup-';

if (!existsSync(outDir)) {
  process.exit(0);
}

for (const entry of readdirSync(outDir, { withFileTypes: true })) {
  if (entry.name.startsWith(backupPrefix)) {
    continue;
  }

  const targetPath = join(outDir, entry.name);

  try {
    rmSync(targetPath, { recursive: true, force: true });
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`[prepare-app-dist] skipped ${basename(targetPath)}: ${message}`);
  }
}
