#!/usr/bin/env node
import {
  ERROR_MESSAGES
} from "../chunk-V43QDMYQ.js";
import {
  BaseCommand,
  EXIT_CODES
} from "../chunk-SRFNNOLC.js";
import {
  extractFrontmatter,
  printPluginValidationResult,
  validateAllPlugins,
  validatePlugin
} from "../chunk-ZECXM7LP.js";
import "../chunk-T4EXUIBY.js";
import {
  agentFrontmatterValidationSchema,
  agentYamlGenerationSchema,
  fileExists,
  getErrorMessage,
  log,
  metadataValidationSchema,
  pluginManifestSchema,
  projectSourceConfigSchema,
  readFile,
  skillFrontmatterValidationSchema,
  skillsMatrixConfigSchema,
  stackConfigValidationSchema,
  stacksConfigSchema
} from "../chunk-473YHDYQ.js";
import {
  CLAUDE_DIR,
  CLAUDE_SRC_DIR,
  STANDARD_FILES
} from "../chunk-FVN5PFFY.js";
import {
  init_esm_shims
} from "../chunk-DHET7RCE.js";

// src/cli/commands/validate.ts
init_esm_shims();
import { Args, Flags } from "@oclif/core";
import path2 from "path";

// src/cli/lib/schema-validator.ts
init_esm_shims();
import { sumBy } from "remeda";
import path from "path";
import { parse as parseYaml } from "yaml";
import fg from "fast-glob";
var VALIDATION_TARGETS = [
  {
    name: "Skills Matrix",
    schema: skillsMatrixConfigSchema,
    pattern: STANDARD_FILES.SKILLS_MATRIX_YAML,
    baseDir: "src/config"
  },
  {
    name: "Skill Metadata",
    schema: metadataValidationSchema,
    pattern: `**/${STANDARD_FILES.METADATA_YAML}`,
    baseDir: "src/skills"
  },
  {
    name: "Stack Skill Metadata",
    schema: metadataValidationSchema,
    pattern: `**/skills/**/${STANDARD_FILES.METADATA_YAML}`,
    baseDir: "src/stacks"
  },
  {
    name: "Stack Config",
    schema: stackConfigValidationSchema,
    pattern: `*/${STANDARD_FILES.CONFIG_YAML}`,
    baseDir: "src/stacks"
  },
  {
    name: "Agent Definition",
    schema: agentYamlGenerationSchema,
    pattern: `**/${STANDARD_FILES.AGENT_YAML}`,
    baseDir: "src/agents"
  },
  {
    name: "Skill Frontmatter",
    schema: skillFrontmatterValidationSchema,
    pattern: `**/${STANDARD_FILES.SKILL_MD}`,
    baseDir: "src/skills",
    extractor: extractFrontmatter
  },
  {
    name: "Stack Skill Frontmatter",
    schema: skillFrontmatterValidationSchema,
    pattern: `**/skills/**/${STANDARD_FILES.SKILL_MD}`,
    baseDir: "src/stacks",
    extractor: extractFrontmatter
  },
  {
    name: "Stacks Config",
    schema: stacksConfigSchema,
    pattern: "stacks.yaml",
    baseDir: "config"
  },
  {
    name: "Project Source Config",
    schema: projectSourceConfigSchema,
    pattern: STANDARD_FILES.CONFIG_YAML,
    baseDir: CLAUDE_SRC_DIR
  },
  {
    name: "Project Skill Metadata",
    schema: metadataValidationSchema,
    pattern: `*/${STANDARD_FILES.METADATA_YAML}`,
    baseDir: `${CLAUDE_DIR}/skills`
  },
  {
    name: "Project Skill Frontmatter",
    schema: skillFrontmatterValidationSchema,
    pattern: `*/${STANDARD_FILES.SKILL_MD}`,
    baseDir: `${CLAUDE_DIR}/skills`,
    extractor: extractFrontmatter
  },
  {
    name: "Project Agent Frontmatter",
    schema: agentFrontmatterValidationSchema,
    pattern: "*.md",
    baseDir: `${CLAUDE_DIR}/agents`,
    extractor: extractFrontmatter
  },
  {
    name: "Plugin Manifest",
    schema: pluginManifestSchema,
    pattern: `*/${STANDARD_FILES.PLUGIN_JSON}`,
    baseDir: `${CLAUDE_DIR}/plugins`,
    extractor: (content) => JSON.parse(content)
  }
];
function formatZodErrors(error) {
  return error.issues.map((issue) => {
    const path3 = issue.path.join(".");
    if (issue.code === "unrecognized_keys") {
      return `Unrecognized key: "${issue.keys.join('", "')}"`;
    }
    return path3 ? `${path3}: ${issue.message}` : issue.message;
  });
}
async function validateFile(filePath, schema, extractor) {
  try {
    if (!await fileExists(filePath)) {
      return { valid: false, errors: [`File not found: ${filePath}`] };
    }
    const content = await readFile(filePath);
    let parsed;
    if (extractor) {
      parsed = extractor(content);
      if (parsed === null) {
        return {
          valid: false,
          errors: ["Failed to extract content (no valid frontmatter found)"]
        };
      }
    } else {
      parsed = parseYaml(content);
    }
    const result = schema.safeParse(parsed);
    if (result.success) {
      return { valid: true, errors: [] };
    }
    return { valid: false, errors: formatZodErrors(result.error) };
  } catch (error) {
    const message = getErrorMessage(error);
    return { valid: false, errors: [`Failed to parse content: ${message}`] };
  }
}
async function validateTarget(target, rootDir = process.cwd()) {
  const baseDir = path.join(rootDir, target.baseDir);
  const pattern = path.join(baseDir, target.pattern);
  const files = await fg(pattern, { absolute: true });
  const result = {
    schemaName: target.name,
    valid: true,
    totalFiles: files.length,
    validFiles: 0,
    invalidFiles: []
  };
  if (files.length === 0) {
    return result;
  }
  for (const file of files) {
    const validation = await validateFile(file, target.schema, target.extractor);
    const relativePath = path.relative(rootDir, file);
    if (validation.valid) {
      result.validFiles++;
    } else {
      result.valid = false;
      result.invalidFiles.push({
        file: relativePath,
        errors: validation.errors
      });
    }
  }
  return result;
}
async function validateAllSchemas(rootDir = process.cwd()) {
  const results = [];
  for (const target of VALIDATION_TARGETS) {
    const result = await validateTarget(target, rootDir);
    results.push(result);
  }
  const summary = {
    totalSchemas: results.length,
    totalFiles: sumBy(results, (r) => r.totalFiles),
    validFiles: sumBy(results, (r) => r.validFiles),
    invalidFiles: sumBy(results, (r) => r.invalidFiles.length)
  };
  return {
    valid: results.every((r) => r.valid),
    results,
    summary
  };
}
function printValidationResults(result) {
  log("\n  Schema Validation Summary:");
  log("  \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
  log(`  Total schemas checked: ${result.summary.totalSchemas}`);
  log(`  Total files: ${result.summary.totalFiles}`);
  log(`  Valid: ${result.summary.validFiles}`);
  log(`  Invalid: ${result.summary.invalidFiles}`);
  for (const schemaResult of result.results) {
    if (schemaResult.totalFiles === 0) continue;
    const status = schemaResult.valid ? "\u2713" : "\u2717";
    log(
      `
  ${status} ${schemaResult.schemaName}: ${schemaResult.validFiles}/${schemaResult.totalFiles} valid`
    );
    if (schemaResult.invalidFiles.length > 0) {
      for (const file of schemaResult.invalidFiles) {
        log(`
    ${file.file}:`);
        file.errors.forEach((e) => log(`      - ${e}`));
      }
    }
  }
  if (result.valid) {
    log("\n  \u2713 All schemas validated successfully\n");
  } else {
    log("\n  \u2717 Validation failed\n");
  }
}

// src/cli/commands/validate.ts
var Validate = class _Validate extends BaseCommand {
  static summary = "Validate YAML files against schemas or validate compiled plugins";
  static description = "Validates skill/agent YAML files against JSON schemas, or validates compiled plugin structure and content. Without arguments, validates all YAML files in the current directory against their schemas. With a path argument or --plugins flag, validates plugin(s) instead.";
  static examples = [
    {
      description: "Validate all YAML schemas",
      command: "<%= config.bin %> <%= command.id %>"
    },
    {
      description: "Validate a specific plugin",
      command: "<%= config.bin %> <%= command.id %> ./path/to/plugin"
    },
    {
      description: "Validate all plugins in a directory",
      command: "<%= config.bin %> <%= command.id %> ./plugins --all"
    },
    {
      description: "Validate plugins with verbose output",
      command: "<%= config.bin %> <%= command.id %> --plugins --verbose"
    }
  ];
  static args = {
    path: Args.string({
      description: "Path to plugin or plugins directory to validate",
      required: false
    })
  };
  static flags = {
    ...BaseCommand.baseFlags,
    verbose: Flags.boolean({
      char: "v",
      description: "Enable verbose logging",
      default: false
    }),
    all: Flags.boolean({
      char: "a",
      description: "Validate all plugins in directory",
      default: false
    }),
    plugins: Flags.boolean({
      char: "p",
      description: "Validate plugins instead of schemas",
      default: false
    })
  };
  async run() {
    const { args, flags } = await this.parse(_Validate);
    if (args.path || flags.plugins) {
      await this.validatePlugins(args.path, flags.verbose, flags.all);
    } else {
      await this.validateSchemas();
    }
  }
  async validateSchemas() {
    this.log("");
    this.log("Validating all schemas");
    this.log("");
    try {
      const result = await validateAllSchemas();
      const summary = result.valid ? `Done: ${result.summary.validFiles}/${result.summary.totalFiles} files valid` : `Done: ${result.summary.invalidFiles} invalid files`;
      this.log(summary);
      printValidationResults(result);
      if (!result.valid) {
        this.exit(EXIT_CODES.ERROR);
      }
    } catch (error) {
      const message = getErrorMessage(error);
      this.error(`${ERROR_MESSAGES.VALIDATION_FAILED}: ${message}`, { exit: EXIT_CODES.ERROR });
    }
  }
  async validatePlugins(pluginPath, verbose, all) {
    const targetPath = pluginPath ? path2.resolve(pluginPath) : process.cwd();
    if (all) {
      await this.validateAllPluginsInDirectory(targetPath, verbose);
    } else {
      await this.validateSinglePlugin(targetPath, verbose);
    }
  }
  async validateAllPluginsInDirectory(targetPath, verbose) {
    this.log("");
    this.log(`Validating all plugins in: ${targetPath}`);
    this.log("");
    try {
      const result = await validateAllPlugins(targetPath);
      const summary = result.valid ? `Done: ${result.summary.valid}/${result.summary.total} plugins valid` : `Done: ${result.summary.invalid} invalid plugins`;
      this.log(summary);
      this.log("");
      this.log("  Plugin Validation Summary:");
      this.log("  -------------------------");
      this.log(`  Total plugins: ${result.summary.total}`);
      this.log(`  Valid: ${result.summary.valid}`);
      this.log(`  Invalid: ${result.summary.invalid}`);
      this.log(`  With warnings: ${result.summary.withWarnings}`);
      for (const { name, result: pluginResult } of result.results) {
        printPluginValidationResult(name, pluginResult, verbose);
      }
      if (result.valid) {
        this.log("");
        this.logSuccess("All plugins validated successfully");
        this.log("");
      } else {
        this.log("");
        this.error(ERROR_MESSAGES.VALIDATION_FAILED, { exit: EXIT_CODES.ERROR });
      }
    } catch (error) {
      const message = getErrorMessage(error);
      this.error(`${ERROR_MESSAGES.VALIDATION_FAILED}: ${message}`, { exit: EXIT_CODES.ERROR });
    }
  }
  async validateSinglePlugin(targetPath, _verbose) {
    this.log("");
    this.log(`Validating plugin: ${targetPath}`);
    this.log("");
    try {
      const result = await validatePlugin(targetPath);
      const summary = result.valid ? "Done: Plugin is valid" : "Done: Plugin has errors";
      this.log(summary);
      printPluginValidationResult(path2.basename(targetPath), result, true);
      if (result.valid && result.warnings.length === 0) {
        this.log("");
        this.logSuccess("Plugin validated successfully");
        this.log("");
      } else if (result.valid) {
        this.log("");
        this.logWarning("Plugin valid with warnings");
        this.log("");
      } else {
        this.log("");
        this.error(ERROR_MESSAGES.VALIDATION_FAILED, { exit: EXIT_CODES.ERROR });
      }
    } catch (error) {
      const message = getErrorMessage(error);
      this.error(`${ERROR_MESSAGES.VALIDATION_FAILED}: ${message}`, { exit: EXIT_CODES.ERROR });
    }
  }
};
export {
  Validate as default
};
//# sourceMappingURL=validate.js.map