#!/usr/bin/env ts-node
/**
 * Sync Enums - Backend to Frontend
 *
 * Este script sincroniza automaticamente las constantes y enums del backend
 * al frontend, manteniendo el principio SSOT (Single Source of Truth).
 *
 * Ejecutar: npm run sync:enums
 *
 * @author Architecture-Analyst
 * @date 2025-12-12
 */

import * as fs from 'fs';
import * as path from 'path';

// =============================================================================
// CONFIGURACION
// =============================================================================

const BACKEND_CONSTANTS_DIR = path.resolve(__dirname, '../../backend/src/shared/constants');
const FRONTEND_CONSTANTS_DIR = path.resolve(__dirname, '../../frontend/web/src/shared/constants');

// Archivos a sincronizar
const FILES_TO_SYNC = [
  'enums.constants.ts',
  'api.constants.ts',
];

// Header para archivos generados
const GENERATED_HEADER = `/**
 * AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
 *
 * Este archivo es generado automaticamente desde el backend.
 * Cualquier cambio sera sobreescrito en la proxima sincronizacion.
 *
 * Fuente: backend/src/shared/constants/
 * Generado: ${new Date().toISOString()}
 *
 * Para modificar, edita el archivo fuente en el backend
 * y ejecuta: npm run sync:enums
 */

`;

// =============================================================================
// FUNCIONES
// =============================================================================

function ensureDirectoryExists(dir: string): void {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
    console.log(`📁 Created directory: ${dir}`);
  }
}

function processContent(content: string): string {
  // Remover imports que no aplican al frontend
  let processed = content
    // Remover imports de Node.js
    .replace(/import\s+\*\s+as\s+\w+\s+from\s+['"]fs['"];?\n?/g, '')
    .replace(/import\s+\*\s+as\s+\w+\s+from\s+['"]path['"];?\n?/g, '')
    // Remover comentarios de @module backend
    .replace(/@module\s+@shared\/constants\//g, '@module shared/constants/')
    // Mantener 'as const' para inferencia de tipos
    ;

  return GENERATED_HEADER + processed;
}

function syncFile(filename: string): void {
  const sourcePath = path.join(BACKEND_CONSTANTS_DIR, filename);
  const destPath = path.join(FRONTEND_CONSTANTS_DIR, filename);

  if (!fs.existsSync(sourcePath)) {
    console.log(`⚠️  Source file not found: ${sourcePath}`);
    return;
  }

  const content = fs.readFileSync(sourcePath, 'utf-8');
  const processedContent = processContent(content);

  fs.writeFileSync(destPath, processedContent);
  console.log(`✅ Synced: ${filename}`);
}

function generateIndexFile(): void {
  const indexContent = `${GENERATED_HEADER}
// Re-export all constants
export * from './enums.constants';
export * from './api.constants';
`;

  const indexPath = path.join(FRONTEND_CONSTANTS_DIR, 'index.ts');
  fs.writeFileSync(indexPath, indexContent);
  console.log(`✅ Generated: index.ts`);
}

function main(): void {
  console.log('🔄 Syncing constants from Backend to Frontend...\n');
  console.log(`Source: ${BACKEND_CONSTANTS_DIR}`);
  console.log(`Target: ${FRONTEND_CONSTANTS_DIR}\n`);

  // Asegurar que el directorio destino existe
  ensureDirectoryExists(FRONTEND_CONSTANTS_DIR);

  // Sincronizar cada archivo
  for (const file of FILES_TO_SYNC) {
    syncFile(file);
  }

  // Generar archivo index
  generateIndexFile();

  console.log('\n✅ Sync completed successfully!');
  console.log('\nRecuerda importar las constantes desde:');
  console.log('  import { ROLES, PROJECT_STATUS, API_ROUTES } from "@/shared/constants";');
}

main();
