import uuid
from datetime import datetime, timezone
from pathlib import Path
from requests import Session
from requests_pkcs12 import Pkcs12Adapter

# --- Konfigurace ---
PFX_FILE = r"C:\Users\vlado\PycharmProjects\Recepty\AMBSUKL214235369G_31DEC2024.pfx"
PFX_PASSWORD = "Vlado7309208104++"

API_USER = "e08c89c6-2b1a-4eba-8ed9-4e3e63618379"
API_PASS = "Buzalka@Vladimir2025"

UZIVATEL = "E08C89C6-2B1A-4EBA-8ED9-4E3E63618379"
PRACOVISTE = "00214235367"

ENDPOINT = "https://lekar-soap.erecept.sukl.cz/cuer/Lekar2"

PRIJMENI = "Buzalka"
JMENA = "Vladimír"
DATUM_NAROZENI = "1973-09-20"

POCET_ZNAKU_ATC = 7
POCET_MESICU =60

VYSTUP = Path(__file__).parent / "odpoved_lekovy_zaznam.xml"


def nacist_a_ulozit():
    sess = Session()
    sess.mount("https://", Pkcs12Adapter(
        pkcs12_filename=PFX_FILE,
        pkcs12_password=PFX_PASSWORD
    ))
    sess.auth = (API_USER, API_PASS)

    id_zpravy = str(uuid.uuid4())
    odeslano = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S+00:00")

    soap_body = (
        '<?xml version="1.0" encoding="UTF-8"?>'
        '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">'
        '<soapenv:Body>'
        f'<NacistLekovyZaznamLekarDotaz xmlns="http://www.sukl.cz/erp/201912">'
        f'<Doklad>'
        f'<Pristupujici><Uzivatel>{UZIVATEL}</Uzivatel><Pracoviste>{PRACOVISTE}</Pracoviste></Pristupujici>'
        f'<PocetZnakuATC>{POCET_ZNAKU_ATC}</PocetZnakuATC>'
        f'<PocetMesicu>{POCET_MESICU}</PocetMesicu>'
        f'<Pacient><Totoznost><Jmeno><Prijmeni>{PRIJMENI}</Prijmeni><Jmena>{JMENA}</Jmena></Jmeno>'
        f'<DatumNarozeni>{DATUM_NAROZENI}</DatumNarozeni></Totoznost></Pacient>'
        f'</Doklad>'
        f'<Zprava><ID_Zpravy>{id_zpravy}</ID_Zpravy><Verze>202501A</Verze>'
        f'<Odeslano>{odeslano}</Odeslano><SW_Klienta>MEDICUS_____</SW_Klienta></Zprava>'
        f'</NacistLekovyZaznamLekarDotaz>'
        '</soapenv:Body>'
        '</soapenv:Envelope>'
    )

    headers = {
        "Content-Type": 'text/xml; charset="UTF-8"',
        "SOAPAction": '"NacistLekovyZaznam"',
        "User-Agent": "Medicus"
    }

    print(f"POST {ENDPOINT} ...")
    resp = sess.post(ENDPOINT, data=soap_body.encode("utf-8"), headers=headers, timeout=30)
    print(f"HTTP {resp.status_code} | {len(resp.content)} bytů")

    if resp.status_code == 200:
        VYSTUP.write_text(resp.text, encoding="utf-8")
        print(f"Uloženo: {VYSTUP}")
    else:
        print("CHYBA — odpověď neuložena")
        print(resp.text)


if __name__ == "__main__":
    nacist_a_ulozit()
