#!/usr/bin/env node
/**
 * One-off port helper — rewrites next/* imports in template-vite/ to
 * the @/lib/next-compat shim (or, for next/dynamic, to React.lazy).
 *
 * Run from packages/ui/template-vite root:
 *   node scripts/port-next-imports.mjs
 *
 * The script is idempotent: running twice leaves files unchanged. It is
 * intentionally conservative — only rewrites import lines, never logic.
 */

import { readFile, writeFile } from "node:fs/promises"
import { glob } from "node:fs/promises"
import path from "node:path"

const ROOT = path.resolve(import.meta.dirname, "..")

const REWRITES = [
  // Default `Link` import — `import Link from "next/link"` → `import { Link } from "@/lib/next-compat"`
  {
    re: /import\s+Link\s+from\s+["']next\/link["']/g,
    to: 'import { Link } from "@/lib/next-compat"',
  },
  // Named imports from next/navigation — keep the named list, swap source
  {
    re: /from\s+["']next\/navigation["']/g,
    to: 'from "@/lib/next-compat"',
  },
]

async function main() {
  const patterns = ["**/*.ts", "**/*.tsx"]
  const files = []
  for (const pattern of patterns) {
    for await (const f of glob(pattern, { cwd: ROOT })) {
      if (
        f.startsWith("node_modules/") ||
        f.startsWith("dist/") ||
        f.includes("/.next-compat") ||
        f === "lib/next-compat.tsx" ||
        f.startsWith("scripts/")
      ) {
        continue
      }
      files.push(f)
    }
  }

  let changed = 0
  for (const rel of files) {
    const abs = path.join(ROOT, rel)
    const src = await readFile(abs, "utf8")
    let out = src
    for (const { re, to } of REWRITES) {
      out = out.replace(re, to)
    }
    if (out !== src) {
      await writeFile(abs, out, "utf8")
      changed += 1
      console.log(`  ✓ ${rel}`)
    }
  }
  console.log(`\nport-next-imports: ${changed} file(s) updated.`)
}

main().catch(err => {
  console.error("port-next-imports failed:", err)
  process.exit(1)
})
