#!/usr/bin/env python3
"""
Medizinische Gesundheitsdatenbank Initialisierung
Erstellt SQLite-Datenbank mit Tabellen: dokumente, laborwerte, medikamente
"""

import sqlite3
import os

DB_PATH = os.path.expanduser('~/Gesundheit/health_data.db')

def init_database():
    """Initialisiert die SQLite-Datenbank mit erforderlichen Tabellen."""
    
    # Datenbank-Verbindung erstellen
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    
    try:
        # Tabelle: dokumente
        cursor.execute('''
        CREATE TABLE IF NOT EXISTS dokumente (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            datei_name TEXT NOT NULL,
            dateipfad TEXT NOT NULL,
            daten_typ TEXT NOT NULL CHECK (daten_typ IN ('pdf', 'image')),
            upload_datum TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            groessekbytes INTEGER,
            status TEXT DEFAULT 'neu' CHECK (status IN ('neu', 'eingearbeitet', 'archiviert')),
            verarbeite_datum TIMESTAMP,
            extrahierte_inhalte TEXT,
            FOREIGN KEY (status) REFERENCES dokumente_status
        )
        ''')
        
        # Tabelle: laborwerte
        cursor.execute('''
        CREATE TABLE IF NOT EXISTS laborwerte (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            dokument_id INTEGER,
            parameter_name TEXT NOT NULL,
            wert TEXT NOT NULL,
            einheit TEXT,
            reference_min TEXT,
            reference_max TEXT,
            einheiten TEXT,
            bemerking TEXT,
            ermittlung_datum TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (dokument_id) REFERENCES dokumente(id)
        )
        ''')
        
        # Tabelle: medikamente
        cursor.execute('''
        CREATE TABLE IF NOT EXISTS medikamente (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            dokument_id INTEGER,
            medikament_name TEXT NOT NULL,
            dosierung TEXT,
            anwendungsform TEXT,
            erhaltungsform TEXT,
            ermittlung_datum TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (dokument_id) REFERENCES dokumente(id)
        )
        ''')
        
        # Tabelle: dokumente_status
        cursor.execute('''
        CREATE TABLE IF NOT EXISTS dokumente_status (
            status TEXT PRIMARY KEY
        )
        ''')
        
        # Status-Einträge
        for status in ['neu', 'eingearbeitet', 'archiviert']:
            cursor.execute('INSERT OR IGNORE INTO dokumente_status (status) VALUES (?)', (status,))
        
        conn.commit()
        
        print(f"✅ Datenbank initialisiert: {DB_PATH}")
        print(f"   - Tabelle dokumente: {'ERSTELLT' if cursor.execute('SELECT name FROM sqlite_master WHERE type=\"table\" AND name=\"dokumente\"').fetchone() else 'EXISTIEREND'}")
        print(f"   - Tabelle laborwerte: {'ERSTELLT' if cursor.execute('SELECT name FROM sqlite_master WHERE type=\"table\" AND name=\"laborwerte\"').fetchone() else 'EXISTIEREND'}")
        print(f"   - Tabelle medikamente: {'ERSTELLT' if cursor.execute('SELECT name FROM sqlite_master WHERE type=\"table\" AND name=\"medikamente\"').fetchone() else 'EXISTIEREND'}")
        
    except Exception as e:
        print(f"❌ Fehler bei Datenbank-Initialisierung: {e}")
        raise
    finally:
        conn.close()

if __name__ == '__main__':
    init_database()