"""
Prehled lekoveho zaznamu pacienta z MySQL.

Zobrazuje:
  1. Lekare, kteri pacientovi predepsali leky (sestupne podle poctu predpisu)
  2. Vsechny predpisy od zadaneho data — s nazvem VYDANEHO leku (ne predepsaneho)

Nastaveni:
  RODNE_CISLO  ... rodne cislo pacienta (cifry, bez lomitka)
  DATUM_OD     ... predpisy od tohoto data ve formatu DD.MM.RRRR (None = vsechny)
"""

from datetime import date, datetime
import sys
import fdb
import pymysql
import pymysql.cursors



def odbornost_z_icp(icp):
    """Vrati nazev odbornosti podle ICP (plny 8-znakovy kod) z tabulky vzp_pracoviste."""
    if not icp:
        return ""
    return ODBORNOST.get(icp, f"odb. {icp[-3:]}")

# ── NASTAVENÍ ─────────────────────────────────────────────────────────────────
RODNE_CISLO = "440802/018"      # funguje s lomitkem i bez: 7309208104 nebo 730920/8104
DATUM_OD    = "01.01.2025"      # None = vsechny predpisy
# ─────────────────────────────────────────────────────────────────────────────

FB = dict(
    dsn     = r"localhost:c:\medicus 3\data\medicus.fdb",
    user    = "SYSDBA",
    password= "masterkey",
    charset = "win1250",
)



DB = dict(
    host        = "192.168.1.76",
    user        = "root",
    password    = "Vlado9674+",
    database    = "medicus",
    charset     = "utf8mb4",
    cursorclass = pymysql.cursors.DictCursor,
)
def _nacti_odbornosti():
    """Nacteni odbornosti z MySQL: vzp_pracoviste JOIN odbornost (aktualne platne ICP)."""
    conn = pymysql.connect(**DB)
    try:
        with conn.cursor(pymysql.cursors.Cursor) as cur:
            cur.execute("""
                SELECT vp.icp, o.nazev
                FROM vzp_pracoviste vp
                JOIN odbornost o ON o.kod = vp.odbornost
                WHERE CURDATE() BETWEEN vp.platnost_od AND vp.platnost_do
                ORDER BY vp.platnost_od DESC
            """)
            result = {}
            for icp, nazev in cur.fetchall():
                result.setdefault(icp, nazev)
            return result
    finally:
        conn.close()

ODBORNOST = _nacti_odbornosti()



SEP  = "-" * 110
SEP2 = "-" * 165


def parse_datum(s, nazev):
    try:
        return datetime.strptime(s, "%d.%m.%Y").date()
    except (ValueError, TypeError):
        sys.exit(f"Nespravny format data '{nazev}': '{s}'. Pouzijte DD.MM.RRRR.")


def normalizuj_rc(rc):
    """Odstrani lomitko a mezery z rodneho cisla."""
    return rc.replace("/", "").replace(" ", "").strip()


def najdi_v_firebirdu(rodne_cislo):
    """Vrati prijmeni, jmeno a datum narozeni z Medicusu podle rodneho cisla."""
    rc = normalizuj_rc(rodne_cislo)
    conn = fdb.connect(**FB)
    try:
        cur = conn.cursor()
        cur.execute(
            "SELECT KAR.PRIJMENI, KAR.JMENO, KAR.DATNAR "
            "FROM KAR WHERE KAR.RODCIS = ?",
            (rc,)
        )
        row = cur.fetchone()
        if not row:
            sys.exit(f"Rodne cislo '{rodne_cislo}' nenalezeno v Medicusu.")
        return {"prijmeni": row[0].strip(), "jmeno": row[1].strip(), "datnar": row[2]}
    finally:
        conn.close()


def najdi_pacienty(cur, prijmeni, datum_narozeni):
    cur.execute(
        "SELECT id, prijmeni, jmena, datum_narozeni "
        "FROM pacient WHERE prijmeni = %s AND datum_narozeni = %s",
        (prijmeni, datum_narozeni),
    )
    return cur.fetchall()


def tiskni_lekare(cur, pacient_id, prijmeni, jmena, datum_narozeni):
    cur.execute(
        """
        SELECT pr.prijmeni, pr.jmena,
               pr.icp,
               CONCAT(pr.pzs_nazev, ', ', pr.ulice, ', ', pr.psc, ' ', pr.mesto) AS adresa,
               COUNT(*) AS pocet_predpisu
        FROM zprava z
        JOIN predpis p         ON p.zprava_id     = z.id
        JOIN predepisujici pr  ON pr.lekar_kod     = p.kod_predepisujiciho
        WHERE z.pacient_id = %s
        GROUP BY pr.lekar_kod, pr.prijmeni, pr.jmena, pr.icp, pr.pzs_nazev, pr.ulice, pr.psc, pr.mesto
        ORDER BY pocet_predpisu DESC
        """,
        (pacient_id,),
    )
    rows = cur.fetchall()

    print(f"\n{SEP}")
    print(f"  PACIENT: {prijmeni} {jmena}  |  nar. {datum_narozeni.strftime('%d.%m.%Y')}")
    print(SEP)
    print(f"\nPREDEPISUJICI LEKARI:")
    print(f"{'#':<4} {'Lekar':<30} {'Odbornost':<25} {'Pracoviste a adresa':<50} {'Predpisu':>8}")
    print(SEP)
    for i, r in enumerate(rows, 1):
        lekar    = f"{r['prijmeni']} {r['jmena']}"
        odb      = odbornost_z_icp(r['icp'])
        print(f"{i:<4} {lekar:<30} {odb:<25} {r['adresa']:<50} {r['pocet_predpisu']:>8}")
    if not rows:
        print("  Zadne predpisy nenalezeny.")


def tiskni_predpisy(cur, pacient_id, datum_od):
    podminka = "AND p.datum_vystaveni >= %s" if datum_od else ""
    params   = (pacient_id, datum_od) if datum_od else (pacient_id,)

    cur.execute(
        f"""
        SELECT p.datum_vystaveni,
               COALESCE(v.nazev, p.nazev) AS vydany_lek,
               v.nazev IS NULL            AS nevyzvednuto,
               p.atc,
               p.navod,
               pr.prijmeni,
               pr.jmena,
               pr.icp,
               CONCAT(pr.pzs_nazev, ', ', pr.ulice, ', ', pr.psc, ' ', pr.mesto) AS adresa
        FROM zprava z
        JOIN predpis p         ON p.zprava_id     = z.id
        JOIN predepisujici pr  ON pr.lekar_kod     = p.kod_predepisujiciho
        LEFT JOIN vydej v      ON v.id_lp_predpis  = p.id_lp_predpis
        WHERE z.pacient_id = %s
        {podminka}
        ORDER BY p.datum_vystaveni DESC
        """,
        params,
    )
    rows = cur.fetchall()

    od_text = f"od {datum_od.strftime('%d.%m.%Y')}" if datum_od else "vse"
    print(f"\nVSECHNY PREDPISY ({od_text}) — celkem {len(rows)}:")
    print(f"{'#':<4} {'Datum':<12} {'Vydany lek':<30} {'ATC':<8} {'Navod':<20} {'Lekar':<25} {'Odbornost':<22} Adresa")
    print(SEP2)
    for i, r in enumerate(rows, 1):
        datum  = r["datum_vystaveni"].strftime("%d.%m.%Y")
        lekar  = f"{r['prijmeni']} {r['jmena']}"
        lek    = (r["vydany_lek"] or "")[:28]
        if r["nevyzvednuto"]:
            lek = f"{lek} *NV"
        navod  = (r["navod"]      or "")[:19]
        atc    = (r["atc"]        or "")
        odb    = odbornost_z_icp(r["icp"])[:21]
        print(f"{i:<4} {datum:<12} {lek:<30} {atc:<8} {navod:<20} {lekar:<25} {odb:<22} {r['adresa']}")
    if not rows:
        print("  Zadne predpisy nenalezeny.")
    print()


def main():
    datum_od = parse_datum(DATUM_OD, "DATUM_OD") if DATUM_OD else None

    # 1. Najdi pacienta v Medicusu (Firebird) podle rodneho cisla
    fb_pac = najdi_v_firebirdu(RODNE_CISLO)
    prijmeni       = fb_pac["prijmeni"]
    datum_narozeni = fb_pac["datnar"]

    print(f"\nFirebird: nalezen {prijmeni} {fb_pac['jmeno']}  nar. {datum_narozeni}")

    # 2. Dotaz do MySQL
    conn = pymysql.connect(**DB)
    try:
        with conn.cursor() as cur:
            pacienti = najdi_pacienty(cur, prijmeni, datum_narozeni)

            if not pacienti:
                print(f"Pacient '{prijmeni}' nar. {datum_narozeni} nema zaznam v MySQL (lekovy zaznam nebyl stazeny).")
                return

            for pac in pacienti:
                tiskni_lekare(cur, pac["id"], pac["prijmeni"], pac["jmena"], pac["datum_narozeni"])
                tiskni_predpisy(cur, pac["id"], datum_od)
    finally:
        conn.close()


if __name__ == "__main__":
    main()
