"use strict";

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

const { PACKAGE_ROOT, GLOBAL_CLAUDE_DIR } = require("./constants");

/**
 * Deploy template-cli.js + bin/lib/ to ~/.claude/evolv-coder-kit/bin/.
 *
 * Skills invoke template-cli.js to resolve <PLACEHOLDER> tokens. When the
 * package is installed via npm tarball (not `npm i -g`), `$(npm root -g)`
 * does not contain it, and skills fall back to improvised sed which misses
 * YAML frontmatter. Deploying under $ECK_HOME makes it reachable regardless
 * of install method.
 *
 * @param {object} opts
 * @param {boolean} opts.overwrite
 * @param {boolean} opts.dryRun
 * @param {function} opts.copyDir         — fs-utils copyDir
 * @param {function} opts.computeFileChecksum
 * @param {function} opts.logSuccess
 * @returns {number} number of files copied/updated
 */
function deployTemplateCli({
  overwrite,
  dryRun,
  copyDir,
  computeFileChecksum,
  logSuccess,
}) {
  const binSrc = path.join(PACKAGE_ROOT, "bin", "template-cli.js");
  const libSrc = path.join(PACKAGE_ROOT, "bin", "lib");
  const binDest = path.join(
    GLOBAL_CLAUDE_DIR,
    "evolv-coder-kit",
    "bin",
    "template-cli.js",
  );
  const libDest = path.join(GLOBAL_CLAUDE_DIR, "evolv-coder-kit", "bin", "lib");

  if (!fs.existsSync(binSrc) || !fs.existsSync(libSrc)) return 0;

  let copied = 0;
  const binNeedsCopy =
    !fs.existsSync(binDest) ||
    computeFileChecksum(binSrc) !== computeFileChecksum(binDest);
  if (binNeedsCopy) {
    if (!dryRun) {
      fs.mkdirSync(path.dirname(binDest), { recursive: true });
      fs.copyFileSync(binSrc, binDest);
      fs.chmodSync(binDest, 0o755);
    }
    copied++;
  }
  const libResult = copyDir(libSrc, libDest, {
    overwrite,
    overwriteIfChanged: true,
    dryRun,
  });
  copied += (libResult.copied || 0) + (libResult.updated || 0);
  if (copied > 0) {
    logSuccess(
      `template-cli + lib ${dryRun ? "would be " : ""}installed to ~/.claude/evolv-coder-kit/bin/`,
    );
  }
  return copied;
}

module.exports = { deployTemplateCli };
