"use strict";

/**
 * cmd-scaffold.js — qa-stlc scaffold
 *
 * Writes the embedded Healix QA framework boilerplate into a new project directory
 * and performs post-scaffold customisation (project name replacement, etc.).
 * All framework files are bundled in boilerplate-bundle.js — no filesystem
 * dependency on the boilerplate/ directory at runtime.
 *
 * Usage:
 *   qa-stlc scaffold                          # scaffold into ./my-qa-project
 *   qa-stlc scaffold --name acme-tests        # custom project name
 *   qa-stlc scaffold --dir /path/to/target    # custom output directory
 *   qa-stlc scaffold --no-install             # skip npm install
 */

const fs     = require("fs");
const path   = require("path");
const cp     = require("child_process");

const BUNDLE = require("./boilerplate-bundle");

/**
 * Write all bundle entries to the target directory.
 * Skips entries whose content is empty (directory markers like .gitkeep).
 */
function writeBundleToDir(bundle, dest) {
  for (const [relPath, content] of Object.entries(bundle)) {
    const destPath = path.join(dest, relPath);
    fs.mkdirSync(path.dirname(destPath), { recursive: true });
    if (relPath.endsWith(".gitkeep")) {
      // Just ensure the directory exists — don't write .gitkeep files
      continue;
    }
    fs.writeFileSync(destPath, content, "utf-8");
  }
}

/**
 * Replace all occurrences of a string in a file (binary-safe via Buffer → string).
 */
function replaceInFile(filePath, search, replacement) {
  try {
    const content = fs.readFileSync(filePath, "utf-8");
    if (!content.includes(search)) return;
    fs.writeFileSync(filePath, content.split(search).join(replacement), "utf-8");
  } catch {
    // Binary or unreadable files — skip silently
  }
}

/**
 * Walk a directory and apply replaceInFile to every text file.
 */
function replaceInDir(dir, search, replacement) {
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    const fullPath = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      replaceInDir(fullPath, search, replacement);
    } else if (entry.isFile()) {
      replaceInFile(fullPath, search, replacement);
    }
  }
}

module.exports = async function scaffold(options) {
  const projectName = options.name  || "my-qa-project";
  const targetDir   = path.resolve(options.dir || projectName);
  const runInstall  = options.install !== false;

  // Guard: target must not already exist (or be empty)
  if (fs.existsSync(targetDir)) {
    const entries = fs.readdirSync(targetDir).filter(f => f !== ".git");
    if (entries.length > 0) {
      console.error(`\n  ❌  Target directory is not empty: ${targetDir}`);
      console.error(`     Use --dir to choose a different location.\n`);
      process.exit(1);
    }
  }

  console.log(`\n  🚀  Scaffolding QA framework boilerplate`);
  console.log(`      Name   : ${projectName}`);
  console.log(`      Target : ${targetDir}\n`);

  // 1. Write embedded bundle
  console.log("  📁  Writing framework files…");
  writeBundleToDir(BUNDLE, targetDir);

  // 2. Replace {{PROJECT_NAME}} placeholder
  console.log("  ✏️   Applying project name…");
  replaceInDir(targetDir, "{{PROJECT_NAME}}", projectName);

  // 3. Copy .env.example → .env (if not already present)
  const envExample = path.join(targetDir, ".env.example");
  const envFile    = path.join(targetDir, ".env");
  if (fs.existsSync(envExample) && !fs.existsSync(envFile)) {
    fs.copyFileSync(envExample, envFile);
    console.log("  📋  Created .env from .env.example");
  }

  // 4. npm install
  if (runInstall) {
    console.log("  📦  Installing npm dependencies (this may take a minute)…");
    try {
      cp.execSync("npm install", { cwd: targetDir, stdio: "inherit" });
    } catch {
      console.warn("\n  ⚠️   npm install exited with an error — check output above.\n");
    }
  }

  // 5. Print next steps
  console.log("");
  console.log("  ✅  Scaffold complete!\n");
  console.log("  Next steps:");
  console.log(`    cd ${path.relative(process.cwd(), targetDir) || "."}`);
  if (!runInstall) console.log("    npm install");
  console.log("    npx playwright install chromium");
  console.log("    # Edit .env — set BASE_URL and (optionally) AI_API_KEY");
  console.log("    npm test");
  console.log("");
  console.log("  To add a new page:");
  console.log("    cp src/templates/_template.feature        src/test/features/my-page.feature");
  console.log("    cp src/templates/_template.locators.ts    src/locators/my-page.locators.ts");
  console.log("    cp src/templates/_template.steps.ts       src/test/steps/my-page.steps.ts");
  console.log("    cp src/templates/_TemplatePage.ts         src/pages/MyPage.ts");
  console.log("");
  console.log("  Docs: https://github.com/your-org/stlc-agents#scaffold");
  console.log("");
};
