#!/usr/bin/env node
/* eslint-env node */

// Ensure dev-time Next.js manifests exist to avoid noisy ENOENT errors
import { mkdirSync, existsSync, writeFileSync, rmSync } from "fs";
import { join } from "path";
import { URL } from "node:url";
/* global console */

const root = new URL("..", import.meta.url).pathname; // apps/portal
const nextDir = join(root, ".next");
const routesManifestPath = join(nextDir, "routes-manifest.json");
const serverDir = join(nextDir, "server");
const vendorChunksDir = join(serverDir, "vendor-chunks");
const webpackRuntimePath = join(serverDir, "webpack-runtime.js");

try {
  // Ensure .next exists
  mkdirSync(nextDir, { recursive: true });

  // Proactively clear stale vendor chunks to avoid version-mismatch runtime errors
  // e.g. Cannot find module './vendor-chunks/zod@x.y.z.js'
  try {
    if (existsSync(vendorChunksDir)) {
      rmSync(vendorChunksDir, { recursive: true, force: true });
      console.log("[dev-prep] Cleared .next/server/vendor-chunks");
    }
    if (existsSync(webpackRuntimePath)) {
      rmSync(webpackRuntimePath);
      console.log("[dev-prep] Removed .next/server/webpack-runtime.js to force regeneration");
    }
  } catch (e) {
    console.warn("[dev-prep] Failed to clear vendor-chunks:", e?.message || e);
  }
  if (!existsSync(routesManifestPath)) {
    const minimalManifest = {
      version: 5,
      pages404: true,
      basePath: "",
      redirects: [],
      rewrites: { beforeFiles: [], afterFiles: [], fallback: [] },
      headers: [],
    };
    writeFileSync(routesManifestPath, JSON.stringify(minimalManifest, null, 2));

    console.log("[dev-prep] Created minimal .next/routes-manifest.json");
  }
} catch (err) {
  console.warn("[dev-prep] Failed to prepare Next dev files:", err?.message || err);
}
