import chalk from "chalk";
import { scaffoldProjectBoilerplate } from "../generator/scaffold";
import { copySkills, copyWorkflows, setupSymlink, isAlreadyInitialized } from "./lib/distribute";

export function runInit(name: string, cwd: string): number {
  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 1;
  }

  const skills = copySkills(cwd);
  console.log(chalk.green(`  Copied ${skills.copied} skill files 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/`));
  }

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