#!/usr/bin/env node

import { spawnSync } from 'node:child_process';
import { existsSync, readdirSync, statSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';

const repoRoot = process.cwd();
const skillsRoot = path.join(repoRoot, '.github', 'skills');
const codexHome = process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
const validatorPath = path.join(
  codexHome,
  'skills',
  '.system',
  'skill-creator',
  'scripts',
  'quick_validate.py'
);

if (!existsSync(skillsRoot)) {
  console.error(`Skills directory not found: ${skillsRoot}`);
  process.exit(1);
}

if (!existsSync(validatorPath)) {
  console.error(`Skill validator not found: ${validatorPath}`);
  console.error('Install the Codex skill-creator system skill or set CODEX_HOME correctly.');
  process.exit(1);
}

const skillDirs = readdirSync(skillsRoot)
  .map((name) => path.join(skillsRoot, name))
  .filter((dir) => statSync(dir).isDirectory() && existsSync(path.join(dir, 'SKILL.md')))
  .sort();

if (skillDirs.length === 0) {
  console.log('No skills found to validate.');
  process.exit(0);
}

for (const skillDir of skillDirs) {
  const label = path.relative(repoRoot, skillDir);
  console.log(`Validating ${label}`);
  const result = spawnSync('python3', [validatorPath, skillDir], { stdio: 'inherit' });
  if (result.status !== 0) {
    process.exit(result.status ?? 1);
  }
}

console.log(`Validated ${skillDirs.length} skills.`);
