#!/usr/bin/env node
// Convert ECC agents to pi-compatible skills
"use strict";
const fs = require('fs');
const path = require('path');

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

const AGENTS_TO_CONVERT = [
  'planner', 'architect', 'code-reviewer', 'security-reviewer',
  'tdd-guide', 'build-error-resolver', 'e2e-runner', 'refactor-cleaner',
  'doc-updater', 'docs-lookup', 'code-simplifier', 'code-explorer', 'code-architect',
  'go-reviewer', 'go-build-resolver', 'python-reviewer',
  'java-reviewer', 'java-build-resolver', 'kotlin-reviewer',
  'kotlin-build-resolver', 'rust-reviewer', 'rust-build-resolver',
  'typescript-reviewer', 'cpp-reviewer', 'cpp-build-resolver',
  'database-reviewer', 'fastapi-reviewer',
  'mle-reviewer', 'harmonyos-app-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();
}

function agentToSkill(agentName) {
  var filePath = path.join(AGENTS_DIR, agentName + '.md');
  if (!fs.existsSync(filePath)) {
    console.error('  [SKIP] ' + agentName + '.md not found');
    return null;
  }
  
  var content = fs.readFileSync(filePath, 'utf8');
  var parsed = parseYamlFrontmatter(content);
  
  if (!parsed.frontmatter.name) {
    console.error('  [SKIP] ' + agentName + ' has no name');
    return null;
  }
  
  var skillName = 'ecc-' + parsed.frontmatter.name;
  var description = parsed.frontmatter.description || (parsed.frontmatter.name + ' agent');
  description = description.substring(0, 1024);
  
  var cleanBody = stripPromptDefense(parsed.body);
  
  var skillContent = [
    '---',
    'name: ' + skillName,
    'description: ' + description,
    'origin: ECC',
    '---',
    '',
    '# ' + parsed.frontmatter.name,
    '',
    cleanBody,
    ''
  ].join('\n');
  
  return { skillName: skillName, content: skillContent };
}

// Main
console.log('Converting ECC agents to pi skills...\n');

var converted = 0;
var skipped = 0;

AGENTS_TO_CONVERT.forEach(function(agentName) {
  var result = agentToSkill(agentName);
  if (!result) { skipped++; return; }
  
  var skillDir = path.join(PI_SKILLS_DIR, result.skillName);
  var skillFile = path.join(skillDir, 'SKILL.md');
  
  fs.mkdirSync(skillDir, { recursive: true });
  fs.writeFileSync(skillFile, result.content, 'utf8');
  
  console.log('  [OK] ' + result.skillName + ' -> ' + skillFile);
  converted++;
});

console.log('\nDone! ' + converted + ' converted, ' + skipped + ' skipped.');
console.log('Skills installed to: ' + PI_SKILLS_DIR);
