#!/usr/bin/env node

import path from "node:path";
import { access } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { parseSkillFile, validateFrontmatter } from "./skill_metadata.mjs";

export async function validateSkill(skillPath) {
  const resolved = path.resolve(skillPath);
  const skillMdPath = path.join(resolved, "SKILL.md");

  try {
    await access(skillMdPath);
  } catch {
    return { valid: false, message: "SKILL.md not found" };
  }

  try {
    const { frontmatter } = await parseSkillFile(resolved);
    return validateFrontmatter(frontmatter);
  } catch (error) {
    return { valid: false, message: error instanceof Error ? error.message : String(error) };
  }
}

async function main(argv = process.argv) {
  if (argv.length !== 3) {
    process.stderr.write("Usage: node quick_validate.mjs <skill_directory>\n");
    process.exitCode = 1;
    return;
  }

  const result = await validateSkill(argv[2]);
  process.stdout.write(`${result.message}\n`);
  process.exitCode = result.valid ? 0 : 1;
}

const entryPath = fileURLToPath(import.meta.url);
if (process.argv[1] && path.resolve(process.argv[1]) === entryPath) {
  main().catch((error) => {
    process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
    process.exitCode = 1;
  });
}
