// src/commands/create-skill.ts
import { Command } from "commander";
import * as path from "path";
import * as fs from "fs";
import YAML from "yaml";

// src/skill/schema.ts
import { z } from "zod";
var SkillPhaseSchema = z.object({
  name: z.string(),
  description: z.string(),
  required: z.boolean().default(true)
});
var SkillCliSchema = z.object({
  command: z.string(),
  args: z.array(
    z.object({
      name: z.string(),
      description: z.string(),
      required: z.boolean().default(false)
    })
  ).default([])
});
var SkillMcpSchema = z.object({
  tool: z.string(),
  input: z.record(z.string())
});
var SkillStateSchema = z.object({
  persistent: z.boolean().default(false),
  files: z.array(z.string()).default([])
});
var ALLOWED_TRIGGERS = [
  "manual",
  "on_pr",
  "on_commit",
  "on_new_feature",
  "on_bug_fix",
  "on_refactor",
  "on_project_init",
  "on_review"
];
var ALLOWED_PLATFORMS = ["claude-code", "gemini-cli"];
var ALLOWED_COGNITIVE_MODES = [
  "adversarial-reviewer",
  "constructive-architect",
  "meticulous-implementer",
  "diagnostic-investigator",
  "advisory-guide",
  "meticulous-verifier"
];
var SkillMetadataSchema = z.object({
  name: z.string().regex(/^[a-z][a-z0-9-]*$/, "Name must be lowercase with hyphens"),
  version: z.string().regex(/^\d+\.\d+\.\d+$/, "Version must be semver format"),
  description: z.string(),
  cognitive_mode: z.string().regex(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/, "Cognitive mode must be kebab-case").optional(),
  triggers: z.array(z.enum(ALLOWED_TRIGGERS)),
  platforms: z.array(z.enum(ALLOWED_PLATFORMS)),
  tools: z.array(z.string()),
  cli: SkillCliSchema.optional(),
  mcp: SkillMcpSchema.optional(),
  type: z.enum(["rigid", "flexible"]),
  phases: z.array(SkillPhaseSchema).optional(),
  state: SkillStateSchema.default({}),
  depends_on: z.array(z.string()).default([])
});

// src/output/logger.ts
import chalk from "chalk";
var logger = {
  info: (message) => console.log(chalk.blue("i"), message),
  success: (message) => console.log(chalk.green("v"), message),
  warn: (message) => console.log(chalk.yellow("!"), message),
  error: (message) => console.error(chalk.red("x"), message),
  dim: (message) => console.log(chalk.dim(message)),
  // For JSON output mode
  raw: (data) => console.log(JSON.stringify(data, null, 2))
};

// src/utils/errors.ts
var ExitCode = {
  SUCCESS: 0,
  VALIDATION_FAILED: 1,
  ERROR: 2
};
var CLIError = class extends Error {
  exitCode;
  constructor(message, exitCode = ExitCode.ERROR) {
    super(message);
    this.name = "CLIError";
    this.exitCode = exitCode;
  }
};
function formatError(error) {
  if (error instanceof CLIError) {
    return `Error: ${error.message}`;
  }
  if (error instanceof Error) {
    return `Error: ${error.message}`;
  }
  return `Error: ${String(error)}`;
}
function handleError(error) {
  const message = formatError(error);
  console.error(message);
  const exitCode = error instanceof CLIError ? error.exitCode : ExitCode.ERROR;
  process.exit(exitCode);
}

// src/commands/create-skill.ts
var KEBAB_CASE_RE = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
function buildSkillYaml(opts) {
  const doc = {
    name: opts.name,
    version: "0.1.0",
    description: opts.description,
    cognitive_mode: opts.cognitiveMode ?? "constructive-architect",
    triggers: ["manual"],
    platforms: ["claude-code"],
    tools: ["Read", "Grep", "Glob", "Edit", "Write", "Bash"],
    type: "flexible",
    state: {
      persistent: false,
      files: []
    },
    depends_on: []
  };
  return doc;
}
function buildSkillMd(opts) {
  const mode = opts.cognitiveMode ?? "constructive-architect";
  const readsSection = opts.reads && opts.reads.length > 0 ? opts.reads.map((r) => `- \`${r}\``).join("\n") : "- _No read patterns specified_";
  const producesLine = opts.produces ? `- \`${opts.produces}\`` : "- _No output specified_";
  const preChecksSection = opts.preChecks && opts.preChecks.length > 0 ? opts.preChecks.map((c) => `- \`${c}\``).join("\n") : "- _None_";
  const postChecksSection = opts.postChecks && opts.postChecks.length > 0 ? opts.postChecks.map((c) => `- \`${c}\``).join("\n") : "- _None_";
  return `# ${opts.name}

> Cognitive Mode: ${mode}

${opts.description}

## When to Use

- [Describe when this skill should be invoked]
- [Describe the trigger conditions]

## Context Assembly

### Reads
${readsSection}

### Produces
${producesLine}

## Deterministic Checks

### Pre-checks
${preChecksSection}

### Post-checks
${postChecksSection}

## Process

1. [Describe the step-by-step process]
2. [Add additional steps as needed]

## Harness Integration

This skill integrates with the harness engineering workflow. It can be invoked via:

\`\`\`bash
harness skill run ${opts.name}
\`\`\`

## Success Criteria

- [Define what a successful execution looks like]
- [Add measurable criteria]

## Examples

\`\`\`bash
harness skill run ${opts.name}
\`\`\`
`;
}
function generateSkillFiles(opts) {
  if (!KEBAB_CASE_RE.test(opts.name)) {
    throw new CLIError(
      `Invalid skill name "${opts.name}". Must be kebab-case (e.g., my-skill).`,
      ExitCode.VALIDATION_FAILED
    );
  }
  if (opts.cognitiveMode && !ALLOWED_COGNITIVE_MODES.includes(opts.cognitiveMode)) {
    throw new CLIError(
      `Invalid cognitive mode "${opts.cognitiveMode}". Allowed: ${ALLOWED_COGNITIVE_MODES.join(", ")}`,
      ExitCode.VALIDATION_FAILED
    );
  }
  const baseDir = opts.outputDir ?? path.join(process.cwd(), "agents", "skills", "claude-code");
  const skillDir = path.join(baseDir, opts.name);
  if (fs.existsSync(skillDir)) {
    throw new CLIError(`Skill directory already exists: ${skillDir}`, ExitCode.VALIDATION_FAILED);
  }
  fs.mkdirSync(skillDir, { recursive: true });
  const skillYaml = buildSkillYaml(opts);
  const skillYamlPath = path.join(skillDir, "skill.yaml");
  fs.writeFileSync(skillYamlPath, YAML.stringify(skillYaml));
  const skillMd = buildSkillMd(opts);
  const skillMdPath = path.join(skillDir, "SKILL.md");
  fs.writeFileSync(skillMdPath, skillMd);
  return { skillYamlPath, skillMdPath };
}
function createCreateSkillCommand() {
  const command = new Command("create-skill").description("Scaffold a new skill with skill.yaml and SKILL.md").requiredOption("--name <name>", "Skill name (kebab-case)").requiredOption("--description <desc>", "Skill description").option(
    "--cognitive-mode <mode>",
    `Cognitive mode (${ALLOWED_COGNITIVE_MODES.join(", ")})`,
    "constructive-architect"
  ).option("--reads <patterns...>", "File patterns the skill reads").option("--produces <output>", "What the skill produces").option("--pre-checks <commands...>", "Pre-check commands").option("--post-checks <commands...>", "Post-check commands").action(async (opts, cmd) => {
    const globalOpts = cmd.optsWithGlobals();
    try {
      const result = generateSkillFiles({
        name: opts.name,
        description: opts.description,
        cognitiveMode: opts.cognitiveMode,
        reads: opts.reads,
        produces: opts.produces,
        preChecks: opts.preChecks,
        postChecks: opts.postChecks
      });
      if (!globalOpts.quiet) {
        logger.success(`Created skill "${opts.name}"`);
        logger.info(`  ${result.skillYamlPath}`);
        logger.info(`  ${result.skillMdPath}`);
      }
      if (globalOpts.json) {
        logger.raw({
          name: opts.name,
          files: [result.skillYamlPath, result.skillMdPath]
        });
      }
    } catch (error) {
      if (error instanceof CLIError) {
        if (globalOpts.json) {
          console.log(JSON.stringify({ error: error.message }));
        } else {
          logger.error(error.message);
        }
        process.exit(error.exitCode);
      }
      throw error;
    }
  });
  return command;
}

export {
  ExitCode,
  CLIError,
  handleError,
  logger,
  SkillMetadataSchema,
  generateSkillFiles,
  createCreateSkillCommand
};
