#!/usr/bin/env node
import {
  LOCAL_DEFAULTS,
  computeSkillFolderHash,
  detectInstallation,
  loadConfig,
  loadConfigTypesDataInBackground,
  regenerateConfigTypes,
  resolveAuthor
} from "./chunk-TZXYBG3R.js";
import {
  BaseCommand,
  EXIT_CODES
} from "./chunk-VR3CDXDT.js";
import {
  directoryExists,
  ensureDir,
  fileExists,
  getErrorMessage,
  verbose,
  writeFile
} from "./chunk-LWXRUR6B.js";
import {
  CLI_BIN_NAME,
  DEFAULT_VERSION,
  KEBAB_CASE_PATTERN,
  LOCAL_SKILLS_PATH,
  PLUGIN_MANIFEST_DIR,
  SKILLS_DIR_PATH,
  SKILL_CATEGORIES_PATH,
  SKILL_RULES_PATH,
  STANDARD_FILES
} from "./chunk-6OWHQ7HM.js";
import {
  init_esm_shims
} from "./chunk-DHET7RCE.js";

// src/cli/commands/new/skill.ts
init_esm_shims();
import { Args, Flags } from "@oclif/core";
import path from "path";
function validateSkillName(name) {
  if (!name || name.trim() === "") {
    return "Skill name is required";
  }
  if (!KEBAB_CASE_PATTERN.test(name)) {
    return "Skill name must be kebab-case (lowercase letters, numbers, and hyphens, starting with a letter)";
  }
  return null;
}
function toTitleCase(kebabCase) {
  return kebabCase.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
}
function generateSkillMd(name) {
  const titleName = toTitleCase(name);
  return `---
name: ${name}
description: Brief description of this skill
---

# ${titleName}

> **Quick Guide:** Add a brief summary of what this skill teaches.

---

<critical_requirements>

## CRITICAL: Before Using This Skill

**(Add critical requirements here)**

</critical_requirements>

---

**When to use:**

- Add use cases here

**Key patterns covered:**

- Add patterns here

---

<patterns>

## Core Patterns

### Pattern 1: Example Pattern

Add your patterns here.

</patterns>

---

<critical_reminders>

## CRITICAL REMINDERS

**(Repeat critical requirements here)**

</critical_reminders>
`;
}
function generateMetadataYaml(name, author, category, contentHash, domain) {
  const titleName = toTitleCase(name);
  return `custom: true
domain: ${domain}
category: ${category}
author: "${author}"
displayName: ${titleName}
slug: ${name}
cliDescription: Brief description
usageGuidance: Use when <guidance>.
contentHash: ${contentHash}
tags:
  - local
  - custom
`;
}
var DEFAULT_CATEGORY_ORDER = 99;
var CATEGORIES_TS_COMMENT = "// Skill category definitions";
var RULES_TS_COMMENT = "// Skill rules configuration";
function formatTsExport(comment, data) {
  const body = JSON.stringify(data, null, 2);
  return `${comment}
export default ${body};
`;
}
function buildCategoryEntry(category, domain) {
  const categoryPart = category.includes("-") ? category.slice(category.indexOf("-") + 1) : category;
  const entry = {
    id: category,
    displayName: toTitleCase(categoryPart),
    description: `Skills for ${toTitleCase(categoryPart)}`,
    exclusive: true,
    required: false,
    order: DEFAULT_CATEGORY_ORDER,
    custom: true
  };
  entry.domain = domain;
  return entry;
}
function generateSkillCategoriesTs(category, domain) {
  const entry = buildCategoryEntry(category, domain);
  const data = {
    version: DEFAULT_VERSION,
    categories: {
      [category]: entry
    }
  };
  return formatTsExport(CATEGORIES_TS_COMMENT, data);
}
function generateSkillRulesTs() {
  const data = {
    version: DEFAULT_VERSION,
    relationships: {
      conflicts: [],
      discourages: [],
      recommends: [],
      requires: [],
      alternatives: []
    }
  };
  return formatTsExport(RULES_TS_COMMENT, data);
}
var NewSkill = class _NewSkill extends BaseCommand {
  static summary = "Create a new local skill with proper structure";
  static description = "Create a new local skill scaffold with SKILL.md and metadata.yaml files";
  static args = {
    name: Args.string({
      description: "Name of the skill to create (kebab-case)",
      required: true
    })
  };
  static flags = {
    ...BaseCommand.baseFlags,
    author: Flags.string({
      char: "a",
      description: "Author identifier (e.g., @myhandle)",
      required: false
    }),
    category: Flags.string({
      char: "c",
      description: "Skill category",
      default: LOCAL_DEFAULTS.CATEGORY
    }),
    domain: Flags.string({
      char: "d",
      description: "Domain for the skill (e.g., web, api, cli)",
      required: false
    }),
    force: Flags.boolean({
      char: "f",
      description: "Overwrite existing skill directory",
      default: false
    }),
    output: Flags.string({
      char: "o",
      description: "Output directory for the skill (overrides marketplace detection)"
    })
  };
  async run() {
    const { args, flags } = await this.parse(_NewSkill);
    const projectDir = process.cwd();
    if (!flags.output) {
      const installation = await detectInstallation(projectDir);
      if (!installation) {
        this.error(`No installation found. Run '${CLI_BIN_NAME} init' first.`, {
          exit: EXIT_CODES.ERROR
        });
      }
    }
    const configTypesReady = flags.output ? null : loadConfigTypesDataInBackground(flags.source, projectDir);
    this.log("");
    this.log("Create New Skill");
    this.log("");
    const validationError = validateSkillName(args.name);
    if (validationError) {
      this.error(validationError, { exit: EXIT_CODES.INVALID_ARGS });
    }
    let author = flags.author;
    if (!author) {
      author = await resolveAuthor(projectDir) || LOCAL_DEFAULTS.AUTHOR;
    }
    const category = flags.category;
    const domain = flags.domain ?? LOCAL_DEFAULTS.DOMAIN;
    let skillsBasePath;
    if (flags.output) {
      skillsBasePath = path.resolve(flags.output);
    } else {
      const marketplacePath = path.join(projectDir, PLUGIN_MANIFEST_DIR, "marketplace.json");
      if (await fileExists(marketplacePath)) {
        this.log(`Detected marketplace context, creating skill in ${SKILLS_DIR_PATH}/`);
        skillsBasePath = path.join(projectDir, SKILLS_DIR_PATH);
      } else {
        skillsBasePath = path.join(projectDir, LOCAL_SKILLS_PATH);
      }
    }
    const skillDir = path.join(skillsBasePath, args.name);
    if (await directoryExists(skillDir)) {
      if (!flags.force) {
        this.error(`Skill directory already exists: ${skillDir}
Use --force to overwrite.`, {
          exit: EXIT_CODES.ERROR
        });
      }
      this.warn(`Overwriting existing skill at ${skillDir}`);
    }
    this.log(`Skill name: ${args.name}`);
    this.log(`Author: ${author}`);
    this.log(`Category: ${category}`);
    this.log(`Directory: ${skillDir}`);
    this.log("");
    this.log("Creating skill files...");
    try {
      const skillMdContent = generateSkillMd(args.name);
      const skillMdPath = path.join(skillDir, STANDARD_FILES.SKILL_MD);
      const metadataPath = path.join(skillDir, STANDARD_FILES.METADATA_YAML);
      await writeFile(skillMdPath, skillMdContent);
      const contentHash = await computeSkillFolderHash(skillDir);
      const metadataContent = generateMetadataYaml(
        args.name,
        author,
        category,
        contentHash,
        domain
      );
      await writeFile(metadataPath, metadataContent);
      this.log("");
      this.logSuccess(`Created ${STANDARD_FILES.SKILL_MD} at ${skillMdPath}`);
      this.logSuccess(`Created ${STANDARD_FILES.METADATA_YAML} at ${metadataPath}`);
      if (!flags.output) {
        const marketplacePath = path.join(projectDir, PLUGIN_MANIFEST_DIR, "marketplace.json");
        if (await fileExists(marketplacePath)) {
          try {
            await this.updateConfigFiles(projectDir, args.name, category, domain);
          } catch (error) {
            this.warn(`Could not update config files: ${getErrorMessage(error)}`);
          }
        }
      }
      if (configTypesReady) {
        try {
          await regenerateConfigTypes(projectDir, configTypesReady, {
            extraSkillIds: [args.name],
            extraDomains: [domain],
            extraCategories: [category]
          });
        } catch (error) {
          this.warn(
            `Could not update ${STANDARD_FILES.CONFIG_TYPES_TS}: ${getErrorMessage(error)}`
          );
        }
      }
      this.log("");
      this.log(
        `Skill created successfully! Run '${CLI_BIN_NAME} compile' to include it in your agents.`
      );
      this.log("");
    } catch (error) {
      this.handleError(error);
    }
  }
  async updateConfigFiles(projectRoot, skillName, category, domain) {
    const categoriesPath = path.join(projectRoot, SKILL_CATEGORIES_PATH);
    const rulesPath = path.join(projectRoot, SKILL_RULES_PATH);
    if (await fileExists(categoriesPath)) {
      const parsed = await loadConfig(categoriesPath) ?? {};
      const categories = parsed.categories ?? {};
      if (!categories[category]) {
        categories[category] = buildCategoryEntry(category, domain);
        parsed.categories = categories;
        await writeFile(categoriesPath, formatTsExport(CATEGORIES_TS_COMMENT, parsed));
        verbose(`Added category '${category}' to ${SKILL_CATEGORIES_PATH}`);
      }
    } else {
      await ensureDir(path.dirname(categoriesPath));
      await writeFile(categoriesPath, generateSkillCategoriesTs(category, domain));
      verbose(`Created ${SKILL_CATEGORIES_PATH}`);
    }
    if (!await fileExists(rulesPath)) {
      await ensureDir(path.dirname(rulesPath));
      await writeFile(rulesPath, generateSkillRulesTs());
      verbose(`Created ${SKILL_RULES_PATH}`);
    }
  }
};

export {
  validateSkillName,
  toTitleCase,
  generateSkillMd,
  generateMetadataYaml,
  generateSkillCategoriesTs,
  generateSkillRulesTs,
  NewSkill
};
//# sourceMappingURL=chunk-RO6LX3UV.js.map