import fs from "node:fs";
import path from "node:path";
import { PACKAGE_ROOT, readErpKitVersion } from "../util";

// Files that need renaming because they cause issues in the repo/pack.
// npm renames .gitignore during pack (npm/cli#5756).
// pnpm-workspace.yaml causes the template dir to be treated as a workspace member.
// prepack copies these to their safe names; scaffold time restores the originals.
const RENAME_MAP: Record<string, string> = {
  __dot__gitignore: ".gitignore",
  "__pnpm-workspace.yaml": "pnpm-workspace.yaml",
};

export function copyTemplateDir(
  srcDir: string,
  destDir: string,
  replacements: Record<string, string>,
  placeholderFiles: Set<string>,
  excludeDirs = new Set<string>(),
): void {
  for (const entry of fs.readdirSync(srcDir, { withFileTypes: true })) {
    const srcPath = path.join(srcDir, entry.name);
    const destName = RENAME_MAP[entry.name] ?? entry.name;
    const destPath = path.join(destDir, destName);

    if (entry.name === "node_modules") continue;
    if (excludeDirs.has(entry.name)) continue;

    if (entry.isDirectory()) {
      fs.mkdirSync(destPath, { recursive: true });
      copyTemplateDir(srcPath, destPath, replacements, placeholderFiles, excludeDirs);
    } else {
      if (fs.existsSync(destPath)) continue;
      fs.mkdirSync(path.dirname(destPath), { recursive: true });
      if (placeholderFiles.has(entry.name)) {
        let content = fs.readFileSync(srcPath, "utf-8");
        for (const [from, to] of Object.entries(replacements)) {
          content = content.replaceAll(from, to);
        }
        fs.writeFileSync(destPath, content);
      } else {
        fs.copyFileSync(srcPath, destPath);
      }
    }
  }
}

export function scaffoldModuleBoilerplate(moduleDir: string, moduleName: string): void {
  const templateDir = path.join(PACKAGE_ROOT, "templates", "scaffold", "module");
  const erpKitVersion = readErpKitVersion();
  const replacements = {
    "template-module": moduleName,
    '"workspace:*"': `"${erpKitVersion}"`,
  };
  const placeholderFiles = new Set(["package.json", "permissions.ts", "tailor.config.ts"]);
  copyTemplateDir(templateDir, moduleDir, replacements, placeholderFiles);
}

export function scaffoldAppBoilerplate(appDir: string, appName: string): void {
  const templateDir = path.join(PACKAGE_ROOT, "templates", "scaffold", "app");
  const erpKitVersion = readErpKitVersion();
  const replacements = {
    "template-app-frontend": `${appName}-frontend`,
    "template-app-backend": appName,
    "template-app": appName,
    '"workspace:*"': `"${erpKitVersion}"`,
  };
  const placeholderFiles = new Set(["package.json", "tailor.config.ts", "index.html"]);
  // docs are authored by skills (app-1 through app-4), not scaffolded.
  copyTemplateDir(templateDir, appDir, replacements, placeholderFiles, new Set(["docs"]));
}

export function scaffoldProjectBoilerplate(projectDir: string, projectName: string): void {
  const templateDir = path.join(PACKAGE_ROOT, "templates", "scaffold", "project");
  const erpKitVersion = readErpKitVersion();
  const replacements = {
    "template-project": projectName,
    '"workspace:*"': `"${erpKitVersion}"`,
  };
  const placeholderFiles = new Set(["package.json"]);
  copyTemplateDir(templateDir, projectDir, replacements, placeholderFiles);
}
