import chalk from "chalk";
import { copySkills, copyWorkflows, refreshCopiedSkills } from "./lib/distribute";

export const VALID_RESOURCES = ["skills", "workflows"] as const;
export type Resource = (typeof VALID_RESOURCES)[number];

export function runUpdate(cwd: string, resources: string[]): number {
  console.log(chalk.bold("erp-kit update\n"));

  const selected: Set<Resource> =
    resources.length === 0
      ? new Set(VALID_RESOURCES)
      : new Set(
          resources.filter((r): r is Resource =>
            (VALID_RESOURCES as readonly string[]).includes(r),
          ),
        );

  if (selected.size === 0) {
    console.error(chalk.red(`Invalid resource. Valid: ${VALID_RESOURCES.join(", ")}`));
    return 1;
  }

  if (selected.has("skills")) {
    const result = copySkills(cwd);
    if (result.removed > 0) {
      console.log(chalk.green(`  Removed ${result.removed} stale erp-kit-* skills`));
    }
    console.log(chalk.green(`  Copied ${result.copied} skill files to .agents/skills/`));
    if (refreshCopiedSkills(cwd)) {
      console.log(chalk.green(`  Refreshed .claude/skills/ (copy)`));
    }
  }

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

  console.log(chalk.bold.green("\nDone!"));
  return 0;
}
