#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
kdojelekar_20250101.py
======================
Jednorázový skript: vybere pacienty registrované k 01.01.2025
a dotáže se VZP B2B na jejich registrujícího lékaře k tomuto datu.
Výsledky uloží do stejných MySQL tabulek jako týdenní skript
(vzp_registrace_lekari, vzp_registrace_raw) s k_datu = 2025-01-01.

Resumovatelný — přeskočí pacienty, kteří již mají raw XML pro k_datu=2025-01-01.
"""

import sys
import time
from pathlib import Path
from datetime import date

PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

from Knihovny.vzpb2b_client import VZPB2BClient
from Knihovny.mysql_db import connect_mysql
from Knihovny.medicus_db import get_medicus_connection

# ── KONFIGURACE ───────────────────────────────────────────────────────────────

K_DATU     = date(2025, 1, 1)
API_PAUSE  = 2

PFX_PATH   = Path(__file__).resolve().parent.parent / "Certificates" / "picka.pfx"
PFX_PASS   = "Vlado7309208104+"
ODBORNOSTI = None   # None = bez filtru odborností

# ── INIT ──────────────────────────────────────────────────────────────────────

vzp   = VZPB2BClient("prod", str(PFX_PATH), PFX_PASS)
mysql = connect_mysql()

# ── PACIENTI Z MEDICUS (registrovaní k 01.01.2025) ───────────────────────────

import fdb, socket

computer_name = socket.gethostname().upper()
dsn_map = {
    "LEKAR":  r"localhost:M:\medicus\data\medicus.fdb",
    "SESTRA": r"192.168.1.10:m:\medicus\data\medicus.fdb",
    "LENOVO": r"192.168.1.10:m:\medicus\data\medicus.fdb",
}
dsn = dsn_map.get(computer_name, r"localhost:c:\medicus 3\data\medicus.fdb")
fb_conn = fdb.connect(dsn=dsn, user="SYSDBA", password="masterkey", charset="win1250")
fb_cur  = fb_conn.cursor()

fb_cur.execute("""
    SELECT kar.rodcis, kar.prijmeni, kar.jmeno, kar.poj
    FROM kar
    WHERE kar.vyrazen = 'N'
      AND kar.rodcis IS NOT NULL
      AND kar.rodcis <> ''
      AND EXISTS (
          SELECT r.id FROM registr r
          JOIN icp i ON r.idicp = i.idicp
          WHERE r.idpac = kar.idpac
            AND r.datum <= ?
            AND (r.datum_zruseni IS NULL OR r.datum_zruseni >= ?)
            AND r.priznak IN ('V', 'D', 'A')
            AND i.icp = '09305001'
            AND i.odb = '001'
      )
    ORDER BY kar.prijmeni, kar.rodcis
""", (K_DATU.isoformat(), K_DATU.isoformat()))

cols     = [d[0].strip().lower() for d in fb_cur.description]
pacienti = [dict(zip(cols, row)) for row in fb_cur.fetchall()]
fb_conn.close()

print(f"Pacientu registrovanych k {K_DATU}: {len(pacienti)}")

# ── RESUME: přeskočit již hotové ─────────────────────────────────────────────

with mysql.cursor() as cur:
    cur.execute("SELECT rc FROM vzp_registrace_raw WHERE k_datu = %s", (K_DATU,))
    hotove = {row[0] for row in cur.fetchall()}

pacienti = [p for p in pacienti if (p.get("rodcis") or "").strip() not in hotove]
print(f"Zbyvá zpracovat: {len(pacienti)} ({len(hotove)} již hotovo)\n")

# ── BATCH ─────────────────────────────────────────────────────────────────────

call_count = 0

for i, pac in enumerate(pacienti):
    rc       = (pac.get("rodcis") or "").strip()
    prijmeni = (pac.get("prijmeni") or "").strip()
    jmeno    = (pac.get("jmeno") or "").strip()

    if not rc:
        continue

    if call_count > 0:
        time.sleep(API_PAUSE)
    call_count += 1

    print(f"[{i+1}/{len(pacienti)}] {prijmeni} {jmeno} ({rc}) ...", end=" ", flush=True)

    try:
        xml     = vzp.registrace_lekare(rc=rc, k_datu=K_DATU.isoformat(), odbornosti=ODBORNOSTI)
        zaznamy = vzp.parse_registrace_lekare(xml)
    except Exception as e:
        print(f"CHYBA: {e}")
        continue

    print(f"{len(zaznamy)} lekar(u)")

    for z in zaznamy:
        print(f"    {z['kod_odbornosti']}: {z['nazev_lekare']} / {z['nazev_zzz']}"
              f"  [{z['datum_zahajeni']} - {z['datum_ukonceni']}]")

    if not zaznamy:
        print("    (zadny lekar v zadne odbornosti)")

    with mysql.cursor() as cur:
        cur.execute("""
            INSERT INTO vzp_registrace_raw (rc, k_datu, raw_xml)
            VALUES (%s, %s, %s)
            ON DUPLICATE KEY UPDATE raw_xml=VALUES(raw_xml)
        """, (rc, K_DATU, xml))

    with mysql.cursor() as cur:
        for z in zaznamy:
            cur.execute("""
                INSERT INTO vzp_registrace_lekari
                    (rc, prijmeni, jmeno, k_datu, kod_odbornosti, ma_lekare,
                     ICZ, ICP, nazev_lekare, nazev_zzz,
                     poj_kod, poj_zkratka,
                     datum_registrace, datum_zahajeni, datum_ukonceni,
                     stav_vyrizeni)
                VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
                ON DUPLICATE KEY UPDATE
                    prijmeni=VALUES(prijmeni), jmeno=VALUES(jmeno),
                    ma_lekare=VALUES(ma_lekare),
                    ICZ=VALUES(ICZ), ICP=VALUES(ICP),
                    nazev_lekare=VALUES(nazev_lekare), nazev_zzz=VALUES(nazev_zzz),
                    poj_kod=VALUES(poj_kod), poj_zkratka=VALUES(poj_zkratka),
                    datum_registrace=VALUES(datum_registrace),
                    datum_zahajeni=VALUES(datum_zahajeni),
                    datum_ukonceni=VALUES(datum_ukonceni),
                    stav_vyrizeni=VALUES(stav_vyrizeni)
            """, (
                rc, prijmeni, jmeno, K_DATU, z["kod_odbornosti"], 1 if z["ma_lekare"] else 0,
                z["ICZ"], z["ICP"], z["nazev_lekare"], z["nazev_zzz"],
                z["poj_kod"], z["poj_zkratka"],
                z["datum_registrace"], z["datum_zahajeni"], z["datum_ukonceni"],
                z["stav_vyrizeni"],
            ))

print(f"\nHotovo. VZP dotazu: {call_count}")
mysql.close()
