import { Treatment } from '../types/treatments';
import { VarrometerTreatment, TimePerHive } from '../types/varrometer';

export const loadTreatmentsFromCSV = async (): Promise<Treatment[]> => {
  try {
    const response = await fetch('/data/treatments_extended.csv');
    const csvText = await response.text();
    
    console.log('CSV text first 200 chars:', csvText.substring(0, 200));
    
    // Obtener las líneas del CSV, excluyendo la cabecera
    const rows = csvText.split('\n')
      .map(row => row.trim())
      .filter(row => row && !row.startsWith('Name;'));

    console.log('Número total de filas en CSV:', rows.length);
    
    // Depuración: mostrar la primera fila
    if (rows.length > 0) {
      console.log('Primera fila:', rows[0]);
      console.log('Número de columnas en primera fila:', rows[0].split(';').length);
      
      // Mostrar los primeros valores de la primera fila
      const firstRowColumns = rows[0].split(';').map(col => col.trim());
      console.log('Primeros 5 valores de la primera fila:', firstRowColumns.slice(0, 5));
      
      // Verificar específicamente el método de aplicación (columna 16)
      if (firstRowColumns.length > 16) {
        console.log('Método de aplicación (columna 16):', firstRowColumns[16]);
      } else {
        console.log('No hay suficientes columnas para el método de aplicación');
      }
    }

    const treatments = rows.map(row => {
      const columns = row.split(';').map(col => col.trim());
      
      // Verificar que tenemos suficientes columnas
      if (columns.length < 50) {
        console.warn('Fila con columnas insuficientes:', row);
        return null;
      }

      const [
        name, type, efficacy, duration, implementation, temperatureMin, temperatureMax,
        humidityRequirements, equipmentNeeded, colonyConditions, safetyEquipment,
        environmentalPrecautions, storageRequirements, withdrawalPeriod, residueRisks,
        incompatibilities, applicationMethod, numberOfApplications, daysBetweenApplications,
        totalDuration, bestTime, weatherConditions, activeIngredient, manufacturer,
        registrationNumber, costCategory, resistanceRisk, sideEffects, organicCompatible,
        availability, jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec,
        dadant, kenyan, langstroth, warre, wbc
      ] = columns;

      console.log(`Procesando tratamiento: ${name}`);
      console.log(`Método de aplicación para ${name}:`, applicationMethod);
      console.log(`Valores mensuales para ${name}:`, { jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec });
      console.log(`Tipos de colmena para ${name}:`, { dadant, kenyan, langstroth, warre, wbc });

      // Mapear colonyStrengthRequirement basado en colonyConditions
      const getColonyStrength = (conditions: string): 'strong' | 'weak' | 'any' => {
        const conditionsLower = conditions.toLowerCase();
        if (conditionsLower.includes('strong')) {
          return 'strong';
        } else if (conditionsLower.includes('any')) {
          return 'any';
        } else {
          return 'weak';  // Por defecto weak para núcleos y colonias débiles
        }
      };

      const mapAvailability = (availability: string): 'veterinary' | 'pharmacy' => {
        const lower = availability.toLowerCase();
        if (lower === 'veterinary') return 'veterinary';
        return 'pharmacy';  // Por defecto, si está disponible o no especificado, asumimos farmacia
      };

      const mapCostCategory = (cost: string): 'low' | 'medium' | 'high' => {
        const lower = cost.toLowerCase();
        if (lower.includes('high')) return 'high';
        if (lower.includes('medium')) return 'medium';
        return 'low';  // Por defecto low
      };

      const treatment: Treatment = {
        id: name.toLowerCase().replace(/\s+/g, '-'),
        name,
        type,
        efficacy,
        duration,  // Mantener por compatibilidad
        timeRequired: duration,  // Usar el mismo valor por ahora
        realTimeRequired: columns[columns.length - 1] || '0',  // Añadido
        implementation,
        totalDuration,
        temperatureMin: parseFloat(temperatureMin) || 0,
        temperatureMax: parseFloat(temperatureMax) || 0,
        humidityRequirements,
        equipmentNeeded,
        colonyConditions,
        colonyStrengthRequirement: getColonyStrength(colonyConditions),
        safetyEquipment,
        environmentalPrecautions,
        storageRequirements,
        withdrawalPeriod,
        residueRisks,
        incompatibilities,
        applicationMethod,
        numberOfApplications: parseInt(numberOfApplications) || 0,
        daysBetweenApplications: parseInt(daysBetweenApplications) || 0,
        bestTime,
        weatherConditions,
        activeIngredient,
        manufacturer,
        registrationNumber,
        costCategory: mapCostCategory(costCategory),  // Mapeado a los valores correctos
        resistanceRisk,
        sideEffects,
        organicCompatible: organicCompatible.toLowerCase() === 'yes',
        varroaTolerant: columns[columns.length - 2]?.toLowerCase() === 'yes',  // Añadido
        availability: mapAvailability(availability),  // Mapeado a los valores correctos
        seasonCompatibility: {
          spring: bestTime.toLowerCase().includes('spring'),
          summer: bestTime.toLowerCase().includes('summer'),
          autumn: bestTime.toLowerCase().includes('autumn'),
          winter: bestTime.toLowerCase().includes('winter')
        },
        jan: jan.toLowerCase() || 'no',
        feb: feb.toLowerCase() || 'no',
        mar: mar.toLowerCase() || 'no',
        apr: apr.toLowerCase() || 'no',
        may: may.toLowerCase() || 'no',
        jun: jun.toLowerCase() || 'no',
        jul: jul.toLowerCase() || 'no',
        aug: aug.toLowerCase() || 'no',
        sep: sep.toLowerCase() || 'no',
        oct: oct.toLowerCase() || 'no',
        nov: nov.toLowerCase() || 'no',
        dec: dec.toLowerCase() || 'no',
        dadant: dadant.toLowerCase() || 'no',
        kenyan: kenyan.toLowerCase() || 'no',
        langstroth: langstroth.toLowerCase() || 'no',
        warre: warre.toLowerCase() || 'no',
        wbc: wbc.toLowerCase() || 'no'
      };

      return treatment;
    }).filter(Boolean) as Treatment[];

    console.log('Tratamientos cargados:', treatments.length);
    return treatments;
  } catch (error) {
    console.error('Error loading treatments:', error);
    return [];
  }
};

export const mapTreatment = (treatment: Treatment): VarrometerTreatment => {
  return {
    id: treatment.id,
    name: treatment.name,
    type: treatment.type,
    effectiveness: parseInt(treatment.efficacy) || 0,
    duration: treatment.duration,
    applicationTime: parseInt(treatment.duration) || 0,
    temperatureMin: parseInt(treatment.temperatureMin.toString()) || 20,
    temperatureMax: parseInt(treatment.temperatureMax.toString()) || 30,
    activeSubstance: treatment.activeIngredient,
    description: treatment.description || '',
    cost: treatment.costCategory === 'high' ? 'Alto' : treatment.costCategory === 'medium' ? 'Medio' : 'Bajo',
    availability: treatment.availability,
    restrictions: treatment.restrictions || '',
    advantages: [],
    disadvantages: [],
    environmentalPrecautions: treatment.environmentalPrecautions || '',
    manufacturer: treatment.manufacturer || ''
  };
};

export function convertToVarrometerTreatment(treatment: Treatment): VarrometerTreatment {
  return mapTreatment(treatment);
}
