#!/usr/bin/env node
// Convert agent-skills to symlinks for sync with ECC repo
// And add more prompt templates
"use strict";
var fs = require('fs');
var path = require('path');

var AGENTS_DIR = path.resolve(__dirname, '../agents');
var SKILLS_DIR = path.resolve(process.env.HOME, '.agents/skills');
var PROMPTS_DIR = path.resolve(process.env.HOME, '.pi/agent/prompts');
var ECC_SKILLS_DIR = path.resolve(__dirname, '../skills');

// === Part 1: Convert to symlinks ===
console.log('=== Converting agent-skills to symlinks ===\n');
var converted = 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;
  
  // Derive agent name from skill name (ecc-planner -> planner)
  var agentName = item.replace(/^ecc-/, '') + '.md';
  var agentFile = path.join(AGENTS_DIR, agentName);
  
  if (!fs.existsSync(agentFile)) return; // not from an agent
  
  // Remove dir and SKILL.md, create symlink
  var bakDir = skillDir + '.bak';
  if (!fs.existsSync(bakDir)) {
    // Read current content to preserve it
    var content = fs.readFileSync(skillFile, 'utf8');
    
    // Remove dir, recreate as symlink to agents/
    fs.rmSync(skillDir, { recursive: true, force: true });
    fs.symlinkSync(AGENTS_DIR, SKILLS_DIR + '/' + item, 'junction');
    converted++;
    console.log('  [SYMLINK] ' + item + ' -> agents/');
  }
});

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

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

var MORE_TEMPLATES = {
  'ecc-refactor-clean': {
    description: 'ECC Refactor Clean - 清理无效代码、简化冗余逻辑',
    'argument-hint': '[目标目录/文件]',
    body: '# Refactor & Clean\n\nIdentify and remove dead code, simplify complex logic, and improve code quality.\n\n## Process\n1. **Scan** - Find unused exports, dead code paths, redundant abstractions\n2. **Analyze** - Verify removal won't break anything\n3. **Clean** - Remove dead code, simplify logic\n4. **Verify** - Tests still pass, build still succeeds\n\nTarget: $@'
  },
  'ecc-learn': {
    description: 'ECC Learn - 从当前会话中提取模式和经验',
    body: '# Learn from Session\n\nExtract patterns, insights, and reusable knowledge from the current session.\n\n## Process\n1. **Review** - What was accomplished in this session?\n2. **Extract** - Identify patterns, configs, commands worth saving\n3. **Document** - Save as a note or skill reference\n4. **Share** - Optional: add to project AGENTS.md or CLAUDE.md'
  },
  'ecc-checkpoint': {
    description: 'ECC Checkpoint - 保存当前验证状态快照',
    'argument-hint': '[检查点名称]',
    body: '# Checkpoint\n\nSave the current verification state before proceeding.\n\n## Check\n1. All tests passing\n2. Build succeeds\n3. Lint clean\n4. Type check passes\n5. Security scan clean\n\nLabel: $@'
  },
  'ecc-quality-gate': {
    description: 'ECC Quality Gate - 质量门禁：测试/构建/类型检查/安全检查',
    'argument-hint': '[路径]',
    body: '# Quality Gate\n\nRun comprehensive quality checks before merging.\n\n## Gates\n1. **Test** - All tests pass (80%+ coverage)\n2. **Build** - Build succeeds\n3. **Type** - Type checking passes\n4. **Lint** - Linting clean\n5. **Security** - No vulnerabilities\n6. **Review** - Code reviewed\n\nPath: $@'
  }
};

var added = 0;
Object.keys(MORE_TEMPLATES).forEach(function(name) {
  var config = MORE_TEMPLATES[name];
  var filePath = path.join(PROMPTS_DIR, name + '.md');
  
  if (fs.existsSync(filePath)) {
    console.log('  [SKIP] ' + name + ' - already exists');
    return;
  }
  
  var fm = '---\ndescription: ' + config.description + '\n';
  if (config['argument-hint']) {
    fm += 'argument-hint: ' + config['argument-hint'] + '\n';
  }
  fm += '---\n\n';
  
  var content = fm + config.body + '\n';
  fs.writeFileSync(filePath, content, 'utf8');
  console.log('  [OK] ' + name);
  added++;
});

console.log('\nAdded ' + added + ' prompt templates\n');

// === Part 3: Summary ===
console.log('=== Final Summary ===');
console.log('ECC skills (via settings): 249');
console.log('Agent-skills (symlinked): ' + fs.readdirSync(SKILLS_DIR).filter(function(f) {
  return fs.statSync(path.join(SKILLS_DIR, f)).isDirectory() || fs.statSync(path.join(SKILLS_DIR, f)).isSymbolicLink();
}).length);
console.log('Prompt templates: ' + fs.readdirSync(PROMPTS_DIR).filter(function(f) { return f.endsWith('.md'); }).length);
