#!/usr/bin/env node
/**
 * Script: Analisar reutilização de código
 * Busca componentes, hooks e services existentes antes de criar novos
 * Uso: node check-reuse.js [termo-de-busca]
 * Exemplo: node check-reuse.js user
 */

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

const [, , searchTerm] = process.argv;

if (!searchTerm) {
  console.error('❌ Termo de busca é obrigatório!');
  console.log('Uso: node check-reuse.js [termo-de-busca]');
  process.exit(1);
}

const srcPath = path.join(__dirname, '../../src');

// Buscar arquivos recursivamente
function findFiles(dir, pattern, results = []) {
  const files = fs.readdirSync(dir);
  
  files.forEach(file => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    
    if (stat.isDirectory() && !file.includes('node_modules')) {
      findFiles(filePath, pattern, results);
    } else if (file.toLowerCase().includes(pattern.toLowerCase())) {
      results.push(filePath.replace(srcPath, 'src'));
    }
  });
  
  return results;
}

console.log(`\n🔍 Buscando por: "${searchTerm}"\n`);

// Buscar componentes
const components = findFiles(path.join(srcPath, 'components'), searchTerm);
const featureComponents = findFiles(path.join(srcPath, 'features'), searchTerm)
  .filter(f => f.includes('/components/'));

// Buscar hooks
const hooks = findFiles(path.join(srcPath, 'hooks'), searchTerm);
const featureHooks = findFiles(path.join(srcPath, 'features'), searchTerm)
  .filter(f => f.includes('/hooks/'));

// Buscar services
const services = findFiles(path.join(srcPath, 'services'), searchTerm);
const featureServices = findFiles(path.join(srcPath, 'features'), searchTerm)
  .filter(f => f.includes('Service'));

// Exibir resultados
if (components.length > 0) {
  console.log('📦 Componentes Compartilhados:');
  components.forEach(c => console.log(`  - ${c}`));
  console.log('');
}

if (featureComponents.length > 0) {
  console.log('📦 Componentes de Features:');
  featureComponents.forEach(c => console.log(`  - ${c}`));
  console.log('');
}

if (hooks.length > 0 || featureHooks.length > 0) {
  console.log('🎣 Hooks:');
  [...hooks, ...featureHooks].forEach(h => console.log(`  - ${h}`));
  console.log('');
}

if (services.length > 0 || featureServices.length > 0) {
  console.log('🔌 Services:');
  [...services, ...featureServices].forEach(s => console.log(`  - ${s}`));
  console.log('');
}

const total = components.length + featureComponents.length + hooks.length + 
              featureHooks.length + services.length + featureServices.length;

if (total === 0) {
  console.log('❌ Nenhum arquivo encontrado.');
  console.log('✅ Pode criar novo componente/hook/service com esse nome.\n');
} else {
  console.log(`✅ Total encontrado: ${total} arquivos`);
  console.log(`⚠️  Verifique se pode reutilizar antes de criar novo!\n`);
}
