#!/usr/bin/env node

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

const args = process.argv.slice(2);
const command = args[0];
const os = require('os');

// Parse flags
const isGlobal = args.includes('--global') || args.includes('-g');

const platformIndex = args.findIndex(arg => arg === '--platform' || arg === '-p');
let selectedPlatform = 'all';
if (platformIndex !== -1 && args[platformIndex + 1]) {
  selectedPlatform = args[platformIndex + 1].toLowerCase();
}

const PLATFORMS = {
  claude: path.join(os.homedir(), '.claude'),
  gemini: path.join(os.homedir(), '.gemini', 'antigravity'),
  'antigravity-2.0': path.join(os.homedir(), '.gemini', 'antigravity'),
  'antigravity-ide': path.join(os.homedir(), '.gemini', 'antigravity-ide')
};

// Helper: safely parse JSON by stripping line & block comments
const parseJsonSafe = (str) => {
  const cleanStr = str.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '$1');
  return JSON.parse(cleanStr);
};

// Helper: recursive copy
const copyDir = (src, dest) => {
  fs.mkdirSync(dest, { recursive: true });
  fs.readdirSync(src).forEach((file) => {
    const srcFile = path.join(src, file);
    const destFile = path.join(dest, file);
    if (fs.lstatSync(srcFile).isDirectory()) {
      copyDir(srcFile, destFile);
    } else {
      fs.copyFileSync(srcFile, destFile);
    }
  });
};

// Helper: recursive remove
const removeDir = (targetPath) => {
  if (fs.existsSync(targetPath)) {
    fs.rmSync(targetPath, { recursive: true, force: true });
  }
};

const getTargetDirectories = (platform) => {
  const targets = [];
  if (platform === 'all') {
    const seenDirs = new Set();
    Object.entries(PLATFORMS).forEach(([name, dir]) => {
      if (!seenDirs.has(dir)) {
        seenDirs.add(dir);
        targets.push({ name, dir });
      }
    });
  } else if (PLATFORMS[platform]) {
    targets.push({ name: platform, dir: PLATFORMS[platform] });
  } else {
    console.error(`❌ Unsupported platform: "${platform}". Supported platforms are: ${Object.keys(PLATFORMS).join(', ')}, all`);
    process.exit(1);
  }
  return targets;
};

const source = path.join(__dirname, '../.agent');

if (command === 'init') {
  if (isGlobal) {
    console.log(`🚀 Initializing global Vibe Coding Kit templates (platform: ${selectedPlatform})...`);
    const targets = getTargetDirectories(selectedPlatform);
    
    let successCount = 0;
    targets.forEach(({ name, dir }) => {
      if (!fs.existsSync(dir)) {
        console.log(`Creating directory for ${name}: ${dir}`);
        fs.mkdirSync(dir, { recursive: true });
      }
      
      try {
        // Copy each file/folder from source into target dir
        fs.readdirSync(source).forEach((item) => {
          const itemSrc = path.join(source, item);
          const itemDest = path.join(dir, item);
          
          if (fs.lstatSync(itemSrc).isDirectory()) {
            copyDir(itemSrc, itemDest);
          } else {
            if (item === 'mcp_config.json' && fs.existsSync(itemDest)) {
              try {
                const srcData = fs.readFileSync(itemSrc, 'utf8');
                const destData = fs.readFileSync(itemDest, 'utf8');
                const srcJson = parseJsonSafe(srcData);
                const destJson = parseJsonSafe(destData);

                destJson.mcpServers = destJson.mcpServers || {};
                srcJson.mcpServers = srcJson.mcpServers || {};

                Object.assign(destJson.mcpServers, srcJson.mcpServers);

                fs.writeFileSync(itemDest, JSON.stringify(destJson, null, 2), 'utf8');
                console.log(`   ✨ Merged MCP servers into existing ${itemDest}`);
              } catch (err) {
                console.warn(`   ⚠️ Failed to merge MCP config at ${itemDest}, overwriting instead:`, err.message);
                fs.copyFileSync(itemSrc, itemDest);
              }
            } else {
              fs.copyFileSync(itemSrc, itemDest);
            }
          }
        });
        console.log(`   ✅ Successfully installed in ${name} (${dir})`);
        successCount++;
      } catch (err) {
        console.error(`   ❌ Failed to install in ${name}:`, err.message);
      }
    });
    
    if (successCount > 0) {
      console.log('\n🌌 Global Vibe Coding templates successfully installed!');
    } else {
      process.exit(1);
    }
  } else {
    console.log('🚀 Initializing local Vibe Coding Kit...');
    const target = path.join(process.cwd(), '.agent');

    if (fs.existsSync(target)) {
      console.warn('⚠️ .agent directory already exists.');
      console.log('If you want to update your skills, you can manually copy from the kit or delete the folder and re-run init.');
      process.exit(1);
    }

    try {
      copyDir(source, target);
      console.log('✅ Vibe Coding templates successfully installed!');
      console.log('\nNext steps:\n1. Open your project in your favorite Agentic IDE or Terminal.\n2. Start vibecoding with /plan or /create!');
    } catch (err) {
      console.error('❌ Failed to initialize:', err.message);
      process.exit(1);
    }
  }
} else if (command === 'remove') {
  if (isGlobal) {
    console.log(`🧹 Removing global Vibe Coding Kit templates (platform: ${selectedPlatform})...`);
    const targets = getTargetDirectories(selectedPlatform);
    
    targets.forEach(({ name, dir }) => {
      if (!fs.existsSync(dir)) {
        console.log(`ℹ️ Directory for ${name} (${dir}) does not exist, skipping.`);
        return;
      }
      
      try {
        // Delete only the items that match the kit's .agent folder contents
        fs.readdirSync(source).forEach((item) => {
          const itemSrc = path.join(source, item);
          const itemDest = path.join(dir, item);
          if (!fs.existsSync(itemDest)) return;

          const stats = fs.lstatSync(itemSrc);
          if (stats.isDirectory()) {
            // For subdirectories, recursively delete only the specific sub-items present in the kit
            // to avoid wiping out the user's other folders (e.g. custom skills)
            fs.readdirSync(itemSrc).forEach((subItem) => {
              const subItemDest = path.join(itemDest, subItem);
              if (fs.existsSync(subItemDest)) {
                removeDir(subItemDest);
              }
            });
            // If the folder is now empty, we can clean it up
            try {
              if (fs.readdirSync(itemDest).length === 0) {
                fs.rmdirSync(itemDest);
              }
            } catch (e) {
              // ignore
            }
          } else {
            // For files at the root of .agent, selectively remove if it is mcp_config.json
            if (item === 'mcp_config.json') {
              try {
                const srcData = fs.readFileSync(itemSrc, 'utf8');
                const destData = fs.readFileSync(itemDest, 'utf8');
                const srcJson = parseJsonSafe(srcData);
                const destJson = parseJsonSafe(destData);

                if (srcJson.mcpServers && destJson.mcpServers) {
                  Object.keys(srcJson.mcpServers).forEach((key) => {
                    delete destJson.mcpServers[key];
                  });

                  if (Object.keys(destJson.mcpServers).length === 0) {
                    fs.unlinkSync(itemDest);
                  } else {
                    fs.writeFileSync(itemDest, JSON.stringify(destJson, null, 2), 'utf8');
                  }
                } else {
                  fs.unlinkSync(itemDest);
                }
              } catch (err) {
                removeDir(itemDest);
              }
            } else {
              removeDir(itemDest);
            }
          }
        });
        console.log(`   ✅ Successfully removed from ${name} (${dir})`);
      } catch (err) {
        console.error(`   ❌ Failed to remove from ${name}:`, err.message);
      }
    });
    console.log('\n🧹 Global cleanup complete.');
  } else {
    console.log('🚀 Removing local Vibe Coding Kit...');
    const target = path.join(process.cwd(), '.agent');
    
    if (!fs.existsSync(target)) {
      console.warn('⚠️ No local .agent directory found.');
      process.exit(1);
    }
    
    try {
      removeDir(target);
      console.log('✅ Local Vibe Coding templates successfully removed!');
    } catch (err) {
      console.error('❌ Failed to remove local templates:', err.message);
      process.exit(1);
    }
  }
} else if (command === 'sync') {
  const syncScript = path.join(__dirname, '../scripts/sync-vibe-kit.sh');
  
  if (!fs.existsSync(syncScript)) {
    console.error('❌ Sync command is only available in the development repository.');
    console.log('To update your kit, please run: npm update -g @edwardyinacademy/vibe-coding-kit');
    process.exit(1);
  }

  console.log('🔄 Syncing Vibe Coding Kit with latest upstreams...');
  try {
    execSync(`bash ${syncScript}`, { stdio: 'inherit' });
    console.log('✅ Sync complete!');
  } catch (err) {
    console.error('❌ Sync failed:', err.message);
    process.exit(1);
  }
} else {
  console.log('🌌 Vibe Coding Kit CLI');
  console.log('Usage:');
  console.log('  vibe-coding init                  - Initialize local .agent templates in the current directory');
  console.log('  vibe-coding init --global         - Initialize global templates for all supported platforms (Claude/Gemini/Antigravity-IDE)');
  console.log('  vibe-coding init -g -p claude     - Initialize global templates specifically for Claude Code');
  console.log('  vibe-coding init -g -p gemini     - Initialize global templates specifically for Gemini/Antigravity 2.0');
  console.log('  vibe-coding init -g -p antigravity-ide - Initialize global templates specifically for Antigravity-IDE');
  console.log('  vibe-coding remove                - Remove local .agent directory from current directory');
  console.log('  vibe-coding remove --global       - Remove global templates from all platforms');
  console.log('  vibe-coding remove -g -p gemini   - Remove global templates specifically for Gemini/Antigravity 2.0');
  console.log('  vibe-coding remove -g -p antigravity-ide - Remove global templates specifically for Antigravity-IDE');
  console.log('  vibe-coding sync                  - Sync the kit with latest upstreams');
}
