#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

function exists(file) {
  return fs.existsSync(file);
}

function read(file) {
  return fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
}

function report(kind, message) {
  console.log(`${kind}: ${message}`);
}

function main() {
  const skillDir = path.resolve(process.argv[2] || 'skills/audio-driven-video');
  const errors = [];
  const warnings = [];

  const required = [
    'SKILL.md',
    'agents/openai.yaml',
    'assets/template.html',
    'references/STYLE.md',
    'references/PIPELINE.md',
    'references/CLAUDE_CODE_PROMPTS.md',
    'scripts/create_project.js',
    'scripts/create_demo_audio.js',
    'scripts/validate_html.js',
    'scripts/validate_skill.js',
  ];

  for (const item of required) {
    if (!exists(path.join(skillDir, item))) errors.push(`Missing ${item}`);
  }

  const obsolete = [
    'references/PRESETS.md',
  ];
  for (const item of obsolete) {
    if (exists(path.join(skillDir, item))) errors.push(`Obsolete old-system file still present: ${item}`);
  }

  const skillMdPath = path.join(skillDir, 'SKILL.md');
  if (exists(skillMdPath)) {
    const skillMd = read(skillMdPath);
    const fm = skillMd.match(/^---\r?\n([\s\S]*?)\r?\n---/);
    if (!fm) errors.push('SKILL.md is missing YAML frontmatter.');
    else {
      if (!/^name:\s*audio-driven-video\s*$/m.test(fm[1])) errors.push('SKILL.md frontmatter name must be audio-driven-video.');
      if (!/^description:\s*\S/m.test(fm[1])) errors.push('SKILL.md frontmatter description is missing.');
    }
    const lines = skillMd.split(/\r?\n/).length;
    if (lines > 500) warnings.push(`SKILL.md is ${lines} lines; move details into references.`);
  }

  const openaiYamlPath = path.join(skillDir, 'agents/openai.yaml');
  if (exists(openaiYamlPath)) {
    const yaml = read(openaiYamlPath);
    if (!yaml.includes('display_name:')) errors.push('agents/openai.yaml missing interface.display_name.');
    if (!yaml.includes('$audio-driven-video')) errors.push('agents/openai.yaml default_prompt must mention $audio-driven-video.');
  }

  const templatePath = path.join(skillDir, 'assets/template.html');
  if (exists(templatePath)) {
    const html = read(templatePath);
    ['EDIT ZONE 1/2', 'const CUES', 'const SCENES', 'id="startBtn"', 'id="audio"', 'id="shot"', 'id="bg"'].forEach((needle) => {
      if (!html.includes(needle)) errors.push(`Template missing ${needle}`);
    });
    if (/const\s+PRESET\b|scene-hook|scene-flip|scene-data|scene-wordcloud/.test(html)) {
      errors.push('Template still contains old preset/fixed-scene system.');
    }
  }

  errors.forEach((message) => report('ERROR', message));
  warnings.forEach((message) => report('WARN', message));
  if (errors.length) process.exit(1);
  report('OK', `Skill package validated: ${skillDir}`);
}

main();
