/**
 * import_medications.js
 *
 * Importiert Medikamente aus einer Word-Datei (.docx)
 * und speichert sie normalisiert in MySQL:
 * - medications
 * - medication_forms
 * - medication_variants
 *
 * JEDE Kombination aus
 *   Medikament × Darreichungsform × Dosierung × Packung
 * wird als eigener Datensatz gespeichert.
 */

const mammoth = require("mammoth");
const mysql = require("mysql2/promise");
const path = require("path");

/* ==============================
   KONFIGURATION
   ============================== */

// 🔹 Pfad zur Word-Datei (exakt!)
const WORD_FILE = path.join(
    __dirname,
    "MEDIKAMENTE 228.02.2024  docx.docx"
);

// 🔹 MySQL Zugangsdaten
const DB_CONFIG = {
    host: "85.215.63.122",
    user: "praxisuser",
    password: "praxisuser",
    database: "praxissoftware"
};

/* ==============================
   HAUPTFUNKTION
   ============================== */

async function importMedications() {
    console.log("📄 Lese Word-Datei …");

    // 1️⃣ Word-Datei lesen
    const result = await mammoth.extractRawText({ path: WORD_FILE });

    // 2️⃣ Text → saubere Zeilen
    const lines = result.value
        .split("\n")
        .map(l => l.trim())
        .filter(l => l.length > 0);

    console.log(`📑 ${lines.length} Zeilen gefunden`);

    // 3️⃣ DB verbinden
    const db = await mysql.createConnection(DB_CONFIG);

    let currentMedication = null;

    // 4️⃣ Zeilen verarbeiten
    for (let i = 0; i < lines.length; i++) {
        const line = lines[i];

        /* ------------------------------
           Medikamentenname erkennen
           (keine Zahlen → Name)
        ------------------------------ */
        if (!/\d/.test(line)) {
            currentMedication = line;
            await insertMedication(db, currentMedication);
            continue;
        }

        /* ------------------------------
           Sicherheit: keine Basis
        ------------------------------ */
        if (!currentMedication) {
            console.warn("⚠️ Überspringe Zeile ohne Medikament:", line);
            continue;
        }

        /* ------------------------------
           Dosierungen splitten
           z.B. "50mg / 100mg"
        ------------------------------ */
        const dosages = line
            .split("/")
            .map(d => d.trim())
            .filter(d => d.length > 0);

        /* ------------------------------
           Packungen splitten
           z.B. "30 Comp. / 100 Comp."
        ------------------------------ */
        const rawPackage = lines[i + 1] || "";
        const packages = rawPackage
            .split("/")
            .map(p => p.trim())
            .filter(p => p.length > 0);

        if (packages.length === 0) {
            console.warn("⚠️ Keine Packung für:", currentMedication, line);
            continue;
        }

        /* ------------------------------
           Darreichungsform ermitteln
        ------------------------------ */
        const form = detectForm(rawPackage);

        /* ------------------------------
           JEDE Kombination speichern
        ------------------------------ */
        for (const dosage of dosages) {
            for (const packageInfo of packages) {
                await insertVariant(
                    db,
                    currentMedication,
                    dosage,
                    form,
                    packageInfo
                );
            }
        }

        i++; // Packungszeile überspringen
    }

    await db.end();
    console.log("✅ Import abgeschlossen");
}

/* ==============================
   HILFSFUNKTIONEN
   ============================== */

async function insertMedication(db, name) {
    await db.execute(
        "INSERT IGNORE INTO medications (name) VALUES (?)",
        [name]
    );
}

async function insertVariant(db, medicationName, dosage, formName, packageInfo) {

    // Medikament-ID holen
    const [[med]] = await db.execute(
        "SELECT id FROM medications WHERE name = ?",
        [medicationName]
    );

    if (!med) {
        console.warn("⚠️ Medikament nicht gefunden:", medicationName);
        return;
    }

    // Darreichungsform anlegen falls neu
    await db.execute(
        "INSERT IGNORE INTO medication_forms (name) VALUES (?)",
        [formName]
    );

    const [[form]] = await db.execute(
        "SELECT id FROM medication_forms WHERE name = ?",
        [formName]
    );

    if (!form) {
        console.warn("⚠️ Darreichungsform nicht gefunden:", formName);
        return;
    }

    // Variante speichern
    await db.execute(
        `INSERT INTO medication_variants
         (medication_id, form_id, dosage, package)
         VALUES (?, ?, ?, ?)`,
        [
            med.id,
            form.id,
            normalizeDosage(dosage),
            normalizePackage(packageInfo)
        ]
    );
}

/* ==============================
   NORMALISIERUNG
   ============================== */

function normalizeDosage(text) {
    return text
        .replace(/\s+/g, " ")
        .replace(/mg/gi, " mg")
        .replace(/ml/gi, " ml")
        .trim();
}

function normalizePackage(text) {
    return text
        .replace(/\s+/g, " ")
        .replace(/comp\.?/gi, "Comp.")
        .replace(/tabl\.?/gi, "Tbl.")
        .trim();
}

/* ==============================
   DARREICHUNGSFORM ERKENNEN
   ============================== */

function detectForm(text) {
    if (!text) return "Unbekannt";

    const t = text.toLowerCase();

    if (t.includes("tabl") || t.includes("comp")) return "Tabletten";
    if (t.includes("caps")) return "Kapseln";
    if (t.includes("saft") || t.includes("ml")) return "Saft";
    if (t.includes("creme") || t.includes("salbe")) return "Creme";
    if (t.includes("inj")) return "Injektion";

    return "Unbekannt";
}

/* ==============================
   START
   ============================== */

importMedications().catch(err => {
    console.error("❌ Fehler beim Import:", err);
});
