#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import Ajv from 'ajv';
import addFormats from 'ajv-formats';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

function main() {
  const args = process.argv.slice(2);
  
  if (args.includes('--help') || args.includes('-h')) {
    console.log('Usage: node bin/validate-agents.js [agents-file-path]');
    process.exit(0);
  }

  const defaultPath = path.join(process.cwd(), 'content/.morph/config/agents.json');
  const agentsPath = args[0] || defaultPath;
  const schemaPath = path.join(__dirname, '../content/.morph/schemas/agent.schema.json');

  if (!fs.existsSync(agentsPath)) {
    console.error('Error: agents.json not found at', agentsPath);
    process.exit(1);
  }

  if (!fs.existsSync(schemaPath)) {
    console.error('Error: Schema not found at', schemaPath);
    process.exit(1);
  }

  try {
    const schema = JSON.parse(fs.readFileSync(schemaPath, 'utf-8'));
    const agents = JSON.parse(fs.readFileSync(agentsPath, 'utf-8'));

    const ajv = new Ajv({ allErrors: true, verbose: true, strict: true });
    addFormats(ajv);

    const validate = ajv.compile(schema);
    const valid = validate(agents);

    console.log('\n=== MORPH-SPEC Agent Validator ===\n');
    console.log('Version:', agents.version || 'unknown');
    console.log('Core Agents:', agents.agents?.core?.length || 0);
    console.log('Specialist Agents:', agents.agents?.specialists?.length || 0);

    if (valid) {
      console.log('\n✓ Validation PASSED\n');
      process.exit(0);
    } else {
      console.log('\n✗ Validation FAILED\n');
      console.log('Errors:');
      validate.errors.forEach((err, i) => {
        console.log(`${i + 1}. ${err.instancePath || '/'}: ${err.message}`);
        if (err.params) {
          console.log('   Params:', JSON.stringify(err.params));
        }
      });
      console.log('');
      process.exit(1);
    }
  } catch (error) {
    console.error('Error:', error.message);
    process.exit(1);
  }
}

main();
