#!/usr/bin/env node

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

/**
 * Script to handle .gitignore template files for npm packaging
 * 
 * Usage:
 * - npm run pre-package: Copies .gitignore files to .gitignore.template
 * - npm run post-publish: Removes .gitignore.template files
 * - npm run post-install: Renames .gitignore.template back to .gitignore
 */

const templatesDir = path.join(__dirname, '..', 'src', 'templates');
const distTemplatesDir = path.join(__dirname, '..', 'dist', 'templates');

function findGitignoreFiles(dir) {
  const gitignoreFiles = [];
  
  function walk(currentDir) {
    if (!fs.existsSync(currentDir)) return;
    
    const files = fs.readdirSync(currentDir);
    
    for (const file of files) {
      const filePath = path.join(currentDir, file);
      const stat = fs.statSync(filePath);
      
      if (stat.isDirectory()) {
        walk(filePath);
      } else if (file === '.gitignore') {
        gitignoreFiles.push(filePath);
      }
    }
  }
  
  walk(dir);
  return gitignoreFiles;
}

function findGitignoreTemplateFiles(dir) {
  const templateFiles = [];
  
  function walk(currentDir) {
    if (!fs.existsSync(currentDir)) return;
    
    const files = fs.readdirSync(currentDir);
    
    for (const file of files) {
      const filePath = path.join(currentDir, file);
      const stat = fs.statSync(filePath);
      
      if (stat.isDirectory()) {
        walk(filePath);
      } else if (file === '.gitignore.template') {
        templateFiles.push(filePath);
      }
    }
  }
  
  walk(dir);
  return templateFiles;
}

function copyGitignoreToTemplate() {
  console.log('📦 Pre-package: Converting .gitignore files to .gitignore.template files...');
  
  // Handle both src and dist directories
  const directories = [templatesDir, distTemplatesDir];
  let totalFiles = 0;
  
  for (const dir of directories) {
    if (!fs.existsSync(dir)) continue;
    
    const gitignoreFiles = findGitignoreFiles(dir);
    
    for (const gitignoreFile of gitignoreFiles) {
      const templateFile = gitignoreFile + '.template';
      
      try {
        fs.copyFileSync(gitignoreFile, templateFile);
        console.log(`✅ Copied: ${path.relative(process.cwd(), gitignoreFile)} → ${path.relative(process.cwd(), templateFile)}`);
        totalFiles++;
      } catch (error) {
        console.error(`❌ Failed to copy ${gitignoreFile}:`, error.message);
      }
    }
  }
  
  console.log(`📦 Pre-package complete: ${totalFiles} .gitignore files converted to .template files`);
}

function removeTemplateFiles() {
  console.log('🧹 Post-publish: Removing .gitignore.template files...');
  
  // Handle both src and dist directories
  const directories = [templatesDir, distTemplatesDir];
  let totalFiles = 0;
  
  for (const dir of directories) {
    if (!fs.existsSync(dir)) continue;
    
    const templateFiles = findGitignoreTemplateFiles(dir);
    
    for (const templateFile of templateFiles) {
      try {
        fs.unlinkSync(templateFile);
        console.log(`🗑️  Removed: ${path.relative(process.cwd(), templateFile)}`);
        totalFiles++;
      } catch (error) {
        console.error(`❌ Failed to remove ${templateFile}:`, error.message);
      }
    }
  }
  
  console.log(`🧹 Post-publish complete: ${totalFiles} .gitignore.template files removed`);
}

function convertTemplateToGitignore() {
  console.log('🔄 Post-install: Converting .gitignore.template files back to .gitignore...');
  
  // Only handle dist directory for post-install
  const templateFiles = findGitignoreTemplateFiles(distTemplatesDir);
  let totalFiles = 0;
  
  for (const templateFile of templateFiles) {
    const gitignoreFile = templateFile.replace('.template', '');
    
    try {
      fs.renameSync(templateFile, gitignoreFile);
      console.log(`✅ Converted: ${path.relative(process.cwd(), templateFile)} → ${path.relative(process.cwd(), gitignoreFile)}`);
      totalFiles++;
    } catch (error) {
      console.error(`❌ Failed to convert ${templateFile}:`, error.message);
    }
  }
  
  console.log(`🔄 Post-install complete: ${totalFiles} .gitignore.template files converted back to .gitignore`);
}

// Parse command line arguments
const command = process.argv[2];

switch (command) {
  case 'pre-package':
    copyGitignoreToTemplate();
    break;
  case 'post-publish':
    removeTemplateFiles();
    break;
  case 'post-install':
    convertTemplateToGitignore();
    break;
  default:
    console.error('Usage: node handle-gitignore-templates.js <pre-package|post-publish|post-install>');
    process.exit(1);
}