#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Doplní jméno a příjmení do vzp_stav_pojisteni
podle Medicusu tam, kde jsou NULL.
Bez volání VZP.
Bez změny jiných dat.
"""

import sys
from pathlib import Path

# ==========================================
# PROJECT ROOT (import fix)
# ==========================================
PROJECT_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

import pymysql
from knihovny.medicus_db import MedicusDB

# ==========================================
# CONFIGURATION
# ==========================================
MEDICUS_HOST = "192.168.1.4"
MEDICUS_DB_PATH = r"z:\Medicus 3\data\MEDICUS.FDB"

MYSQL_CONFIG = {
    "host": "192.168.1.76",
    "port": 3307,
    "user": "root",
    "password": "Vlado9674+",
    "database": "medevio",
    "charset": "utf8mb4",
    "autocommit": True
}

# ==========================================
# INIT CONNECTIONS
# ==========================================
print("Connecting to Medicus...")
medicus = MedicusDB(MEDICUS_HOST, MEDICUS_DB_PATH)

print("Connecting to MySQL...")
mysql = pymysql.connect(
    cursorclass=pymysql.cursors.DictCursor,
    **MYSQL_CONFIG
)

# ==========================================
# FETCH REGISTERED PATIENTS
# ==========================================
print("Loading registered patients from Medicus...")
patients = medicus.get_active_registered_patients(as_dict=True)

print(f"Loaded {len(patients)} patients")

# ==========================================
# UPDATE MYSQL
# ==========================================
updated_rows = 0

with mysql.cursor() as cur:
    for p in patients:
        rc = p["rodcis"]
        jmeno = p.get("jmeno")
        prijmeni = p.get("prijmeni")

        if not rc or not jmeno or not prijmeni:
            continue

        cur.execute("""
            UPDATE vzp_stav_pojisteni
            SET
                jmeno = COALESCE(jmeno, %s),
                prijmeni = COALESCE(prijmeni, %s)
            WHERE rc = %s
              AND (jmeno IS NULL OR prijmeni IS NULL)
        """, (jmeno, prijmeni, rc))

        if cur.rowcount > 0:
            updated_rows += cur.rowcount

mysql.close()
medicus.close()

print(f"\n✅ Hotovo. Aktualizováno {updated_rows} řádků ve vzp_stav_pojisteni.")
