import mysql.connector
import os
from pathlib import Path

# ================= DB CONFIG =================
db_config = {
    'host': '127.0.0.1',
    'port': 3307,
    'user': 'root',
    'password': 'Vlado9674+',
    'database': 'ordinace'
}

# ================= PATHS =================
SCRIPT_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = SCRIPT_DIR.parent
ROOT_DIR = PROJECT_ROOT / "09305000"

print("Skript:", SCRIPT_DIR)
print("Projekt:", PROJECT_ROOT)
print("Data:", ROOT_DIR)

# ================= IMPORT =================
def hromadny_raw_import():
    conn = mysql.connector.connect(**db_config)
    cursor = conn.cursor()

    try:
        for root, dirs, files in os.walk(ROOT_DIR):
            for filename in files:
                if not filename.upper().startswith("KDAVKA"):
                    continue

                filepath = Path(root) / filename

                # -------- první řádek --------
                with open(filepath, "r", encoding="cp1250") as f:
                    first_line = f.readline().rstrip("\n")

                if not first_line.startswith("DP"):
                    continue

                fingerprint = first_line[:30].strip()

                # -------- kontrola duplicity --------
                cursor.execute(
                    "SELECT id_davky FROM davky WHERE identifikator = %s",
                    (fingerprint,)
                )
                if cursor.fetchone():
                    continue

                obdobi = first_line[20:26].strip()

                print(f"Importuji: {filename} → {fingerprint}")

                # -------- insert dávky --------
                cursor.execute(
                    "INSERT INTO davky (identifikator, obdobi) VALUES (%s, %s)",
                    (fingerprint, obdobi)
                )
                id_davky = cursor.lastrowid

                # -------- načtení všech vět --------
                vety_data = []

                with open(filepath, "r", encoding="cp1250") as f:
                    for poradi, line in enumerate(f, 1):
                        raw = line.rstrip("\n")
                        if not raw:
                            continue

                        vety_data.append((
                            id_davky,
                            raw[0],      # typ_vety
                            raw,         # obsah_radku
                            poradi       # poradi_v_souboru
                        ))

                # -------- hromadný INSERT --------
                cursor.executemany(
                    """
                    INSERT INTO vety
                    (id_davky, typ_vety, obsah_radku, poradi_v_souboru)
                    VALUES (%s, %s, %s, %s)
                    """,
                    vety_data
                )

                # -------- JEDEN UPDATE: vazba na A --------
                cursor.execute(
                    """
                    UPDATE vety v
                    JOIN vety a
                      ON a.id_davky = v.id_davky
                     AND a.typ_vety = 'A'
                     AND a.poradi_v_souboru <= v.poradi_v_souboru
                    SET v.id_dokladu_vazba = a.id_vety
                    WHERE v.id_davky = %s
                    """,
                    (id_davky,)
                )

                conn.commit()

        print("✅ Raw import dokončen.")

    finally:
        cursor.close()
        conn.close()


if __name__ == "__main__":
    hromadny_raw_import()
