import fs from 'fs';
import os from 'os';
import readline from 'readline';
import path from 'path';

export function runSetup() {
  const homedir = os.homedir();
  const shells = ['.bashrc', '.zshrc', '.bash_profile'];
  let foundFile = null;

  for (const file of shells) {
    const filePath = path.join(homedir, file);
    if (fs.existsSync(filePath)) {
      foundFile = filePath;
      break;
    }
  }

  if (!foundFile) {
    console.log('No se encontró ningún archivo .bashrc, .zshrc ni .bash_profile');
    return;
  }

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  rl.question(`¿Deseas agregar el hook de autofix a ${path.basename(foundFile)}? (y/N): `, answer => {
    if (answer.toLowerCase() === 'y') {
      const code = `\n# Autofix CLI hook\ntrap 'autofix "$BASH_COMMAND"' DEBUG\n`;
      fs.appendFileSync(foundFile, code);
      console.log(`✅  Hook agregado a ${foundFile}. Reinicia tu terminal para aplicar los cambios.`);
    } else {
      console.log('❌  Instalación cancelada.');
    }
    rl.close();
  });
}
