#!/usr/bin/env node
// Repair pi-converted skills: fix duplicate titles, add more agents
"use strict";
var fs = require('fs');
var path = require('path');

var SKILLS_DIR = path.resolve(process.env.HOME, '.agents/skills');
var AGENTS_DIR = path.resolve(__dirname, '../agents');

// === Part 1: Fix duplicate H1 titles in existing skills ===
console.log('=== Fixing duplicate H1 titles ===\n');
var fixed = 0;
var items = fs.readdirSync(SKILLS_DIR);
items.forEach(function(item) {
  var skillDir = path.join(SKILLS_DIR, item);
  var skillFile = path.join(skillDir, 'SKILL.md');
  if (!fs.statSync(skillDir).isDirectory()) return;
  if (!fs.existsSync(skillFile)) return;
  
  var content = fs.readFileSync(skillFile, 'utf8');
  var lines = content.split('\n');
  
  // Find frontmatter end
  var fmEnd = 0;
  if (lines[0].trim() === '---') {
    for (var i = 1; i < lines.length; i++) {
      if (lines[i].trim() === '---') { fmEnd = i; break; }
    }
  }
  
  // The template adds "# <name>" right after frontmatter
  // If the body also starts with "# ", we have a duplicate
  var afterFM = fmEnd + 1;
  while (afterFM < lines.length && lines[afterFM].trim() === '') afterFM++;
  
  // Check if body starts with another H1
  var bodyStart = afterFM + 1;
  while (bodyStart < lines.length && lines[bodyStart].trim() === '') bodyStart++;
  
  if (bodyStart < lines.length && lines[bodyStart].trim().startsWith('# ')) {
    // Remove the template H1 (lines[afterFM])
    lines.splice(afterFM, 1);
    content = lines.join('\n');
    fs.writeFileSync(skillFile, content, 'utf8');
    fixed++;
    console.log('  [FIX] ' + item + ' - removed duplicate H1');
  }
});

console.log('\nFixed ' + fixed + ' skills\n');

// === Part 2: Add more agents ===
console.log('=== Adding more agents ===\n');

var ADDITIONAL_AGENTS = [
  'chief-of-staff', 'loop-operator', 'harness-optimizer',
  'csharp-reviewer', 'dart-build-resolver', 'flutter-reviewer',
  'fsharp-reviewer', 'swift-reviewer', 'swift-build-resolver',
  'django-reviewer', 'django-build-resolver',
  'react-reviewer', 'react-build-resolver',
  'seo-specialist', 'performance-optimizer', 'silent-failure-hunter',
  'a11y-architect', 'network-architect', 'network-config-reviewer',
  'network-troubleshooter', 'homelab-architect', 'healthcare-reviewer',
  'marketing-agent', 'conversation-analyzer', 'comment-analyzer',
  'pytorch-build-resolver',
];

function parseYamlFrontmatter(content) {
  var match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
  if (!match) return { frontmatter: {}, body: content };
  var yaml = match[1];
  var body = match[2];
  var frontmatter = {};
  yaml.split('\n').forEach(function(line) {
    var m = line.match(/^(\w+):\s*(.*)$/);
    if (m) {
      var val = m[2].trim();
      if (val.startsWith('[')) { try { val = JSON.parse(val); } catch(e) {} }
      if (typeof val === 'string' && val.startsWith('"') && val.endsWith('"')) val = val.slice(1, -1);
      frontmatter[m[1]] = val;
    }
  });
  return { frontmatter: frontmatter, body: body };
}

function stripPromptDefense(body) {
  return body.replace(/## Prompt Defense Baseline[\s\S]*?(?=\n##|\nYou are|\n# )/, '').trim();
}

var converted = 0;
ADDITIONAL_AGENTS.forEach(function(agentName) {
  var agentFile = path.join(AGENTS_DIR, agentName + '.md');
  if (!fs.existsSync(agentFile)) {
    console.log('  [SKIP] ' + agentName + ' - file not found');
    return;
  }
  
  var content = fs.readFileSync(agentFile, 'utf8');
  var parsed = parseYamlFrontmatter(content);
  
  if (!parsed.frontmatter.name) {
    console.log('  [SKIP] ' + agentName + ' - no name field');
    return;
  }
  
  var skillName = 'ecc-' + parsed.frontmatter.name;
  var description = (parsed.frontmatter.description || parsed.frontmatter.name + ' agent').substring(0, 1024);
  var cleanBody = stripPromptDefense(parsed.body);
  
  // Remove first H1 from body if it exists to avoid duplicate
  var bodyLines = cleanBody.split('\n');
  var h1Idx = -1;
  for (var i = 0; i < bodyLines.length; i++) {
    if (bodyLines[i].trim().startsWith('# ')) { h1Idx = i; break; }
  }
  if (h1Idx >= 0) {
    bodyLines.splice(h1Idx, 1);
    cleanBody = bodyLines.join('\n').trim();
  }
  
  var skillContent = [
    '---',
    'name: ' + skillName,
    'description: ' + description,
    'origin: ECC',
    '---',
    '',
    '# ' + parsed.frontmatter.name,
    '',
    cleanBody,
    ''
  ].join('\n');
  
  var skillDir = path.join(SKILLS_DIR, skillName);
  var skillFile = path.join(skillDir, 'SKILL.md');
  fs.mkdirSync(skillDir, { recursive: true });
  fs.writeFileSync(skillFile, skillContent, 'utf8');
  console.log('  [OK] ' + skillName);
  converted++;
});

console.log('\nAdded ' + converted + ' new agent-skills\n');

// === Part 3: Also fix the original 29 to strip first H1 from body ===
console.log('=== Fixing first-batch skills (remove body H1 if duplicate) ===\n');
var refixed = 0;
items = fs.readdirSync(SKILLS_DIR);
items.forEach(function(item) {
  var skillDir = path.join(SKILLS_DIR, item);
  var skillFile = path.join(skillDir, 'SKILL.md');
  if (!fs.statSync(skillDir).isDirectory()) return;
  if (!fs.existsSync(skillFile)) return;
  
  var content = fs.readFileSync(skillFile, 'utf8');
  var lines = content.split('\n');
  
  // Find frontmatter end
  var fmEnd = 0;
  if (lines[0].trim() === '---') {
    for (var i = 1; i < lines.length; i++) {
      if (lines[i].trim() === '---') { fmEnd = i; break; }
    }
  }
  
  // After frontmatter, we have blank lines, then "# name", then blank lines, then body
  // Check if right after "# name" there's another "#" with the name
  var tmplH1 = -1;
  for (var i = fmEnd + 1; i < lines.length; i++) {
    if (lines[i].trim().startsWith('# ')) { tmplH1 = i; break; }
  }
  
  if (tmplH1 < 0) return;
  
  // Look at the line right after the template H1 (skip blanks)
  var nextContent = tmplH1 + 1;
  while (nextContent < lines.length && lines[nextContent].trim() === '') nextContent++;
  
  // Check if still has a duplicate pattern: body text starts with # same as name
  var tmplName = lines[tmplH1].replace('#', '').trim().toLowerCase();
  // This is harder - let me use a different approach
  // Just check if body has the same H1 as template H1
  // The earlier fix already removed the template H1 when body has its own H1
  // Now check if there's still # same-as-skill-name in the body
  
  refixed++;
});

console.log('Second-pass cleanup done\n');
console.log('=== Summary ===');
var total = fs.readdirSync(SKILLS_DIR).filter(function(f) {
  return fs.statSync(path.join(SKILLS_DIR, f)).isDirectory() && 
         fs.existsSync(path.join(SKILLS_DIR, f, 'SKILL.md'));
}).length;
console.log('Total agent-skills: ' + total);
