import path from "node:path";
import chalk from "chalk";
import { PACKAGE_ROOT, readErpKitVersion } from "../../util";
import { type CommandResult, success, silentFailure } from "../lib/command-result";
import { copyTemplateDir } from "../lib/copy-template-dir";
import {
  copySkills,
  copyWorkflows,
  copyActions,
  setupSymlink,
  isAlreadyInitialized,
} from "../lib/distribute";

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);
}

export function runInit(name: string, cwd: string): CommandResult {
  console.log(chalk.bold("erp-kit init\n"));

  if (isAlreadyInitialized(cwd)) {
    console.log(
      chalk.yellow("Already initialized. Use `erp-kit update` to refresh framework resources."),
    );
    return silentFailure();
  }

  const skills = copySkills(path.join(cwd, ".agents", "skills"));
  console.log(chalk.green(`  Copied ${skills.copied} skills to .agents/skills/`));

  const symlink = setupSymlink(cwd);
  if (symlink === "linked") {
    console.log(chalk.green("  .claude/skills -> .agents/skills/ (linked)"));
  } else if (symlink === "copied") {
    console.log(
      chalk.yellow("  .claude/skills (copied — re-run `erp-kit update skills` after changes)"),
    );
  } else if (symlink === "skipped_directory") {
    console.log(chalk.yellow("  Skipped .claude/skills (directory exists, not a symlink)"));
  }

  const workflows = copyWorkflows(cwd);
  if (workflows.copied > 0) {
    console.log(chalk.green(`  Copied ${workflows.copied} workflow(s) to .github/workflows/`));
  }

  const actions = copyActions(cwd);
  if (actions.copied > 0) {
    console.log(chalk.green(`  Copied ${actions.copied} action file(s) to .github/actions/`));
  }

  scaffoldProjectBoilerplate(cwd, name);
  console.log(chalk.green("  Scaffolded project structure"));

  console.log(chalk.bold.green("\nDone! Run `erp-kit check` to validate your docs."));
  return success();
}
