import adodbapi
import csv
import os

sdf_file = r"C:\Users\Sebastian Serfling\PycharmProjects\Balzer-WaagenDaten\App.sdf"
output_csv = os.path.join(os.path.dirname(sdf_file), "Weighing_LDB_recovery.csv")

print(f"📂 Versuche Wiederherstellung aus: {sdf_file}")

conn_str = (
    "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;"
    f"Data Source={sdf_file};Persist Security Info=False;"
)

try:
    conn = adodbapi.connect(conn_str)
    cursor = conn.cursor()
    print("✅ Verbindung erfolgreich.")

    # Versuche, alle Spaltennamen zu ermitteln
    try:
        cursor.execute("SELECT * FROM [Weighing_LDB] WHERE 1=0")
        columns = [col[0] for col in cursor.description]
        print(f"📋 Gefundene Spalten: {columns}")
    except Exception as e:
        print(f"⚠️ Fehler beim Lesen der Spalten: {e}")
        columns = []

    # Versuch, Spalte für Spalte zu lesen
    recovered_rows = []
    error_columns = []

    for col in columns:
        try:
            cursor.execute(f"SELECT TOP 5 [{col}] FROM [Weighing_LDB]")
            rows = cursor.fetchall()
            recovered_rows.append((col, [r[0] for r in rows]))
            print(f"✅ Spalte {col}: {len(rows)} Werte gelesen")
        except Exception as e:
            print(f"❌ Fehler in Spalte {col}: {e}")
            error_columns.append(col)

    if recovered_rows:
        print(f"\n💾 Schreibe Ergebnis in: {output_csv}")
        with open(output_csv, "w", newline="", encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerow(["Spalte", "Beispielwerte"])
            for col, vals in recovered_rows:
                writer.writerow([col, str(vals[:5])])
        print("✅ Teildaten erfolgreich exportiert.")

    if error_columns:
        print(f"\n⚠️ Problematische Spalten: {error_columns}")

    cursor.close()
    conn.close()
    print("\n🔚 Wiederherstellung abgeschlossen.")

except Exception as e:
    print(f"❌ Fehler beim Zugriff auf SDF: {e}")
