import mongoose from 'mongoose';
import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
import dotenv from 'dotenv';
import { ProtocolModel } from './infrastructure/database/models/ProtocolModel';
import { ClinicalProtocol } from './domain/entities/ClinicalProtocol';

dotenv.config();

const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/codigo0';
const PROTOCOLS_DIR = path.join(__dirname, '../../frontend/public/protocols');

async function migrate() {
  try {
    console.log('🚀 Iniciando migración de protocolos YAML a MongoDB...');
    await mongoose.connect(MONGODB_URI);
    console.log('✅ Conectado a MongoDB');

    function normalizeItems(items: any[] | undefined): string[] {
      if (!items) return [];
      return items.map(item => {
        if (typeof item === 'string') return item;
        if (typeof item === 'object' && item !== null) {
          const entries = Object.entries(item);
          if (entries.length > 0) {
            const [key, value] = entries[0];
            return `${key}: ${value}`;
          }
        }
        return String(item);
      });
    }
    const folders = fs.readdirSync(PROTOCOLS_DIR);
    let totalMigrated = 0;

    for (const folder of folders) {
      const folderPath = path.join(PROTOCOLS_DIR, folder);
      if (!fs.statSync(folderPath).isDirectory()) continue;

      const files = fs.readdirSync(folderPath).filter(f => f.endsWith('.yaml'));
      
      for (const file of files) {
        const filePath = path.join(folderPath, file);
        const content = fs.readFileSync(filePath, 'utf8');
        const data = yaml.load(content) as any;

        if (!data.id) {
          data.id = file.replace('.yaml', '');
        }

        // Normalizar items en pasos
        if (data.pasos) {
          data.pasos = data.pasos.map((p: any) => ({
            ...p,
            items: normalizeItems(p.items)
          }));
        }

        // Normalizar items en fases
        if (data.fases) {
          data.fases = data.fases.map((f: any) => ({
            ...f,
            items: normalizeItems(f.items)
          }));
        }

        // Normalizar equipamiento
        if (data.equipamiento) {
          data.equipamiento = normalizeItems(data.equipamiento);
        }

        // Upsert
        await ProtocolModel.findOneAndUpdate(
          { id: data.id },
          data,
          { upsert: true, new: true, setDefaultsOnInsert: true }
        );

        console.log(`   📄 Migrado: [${folder}] ${data.titulo} (${data.id})`);
        totalMigrated++;
      }
    }

    console.log(`\n🎉 Migración completada. Total: ${totalMigrated} protocolos.`);
  } catch (error) {
    console.error('❌ Error durante la migración:', error);
  } finally {
    await mongoose.disconnect();
    process.exit();
  }
}

migrate();
