import uuid
from datetime import datetime, timezone
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/Lekar"
NAMESPACE  = "http://www.sukl.cz/erp/201704"

# --- ID receptu ---
# Alfanumerický kód receptu, např. PPIBVF93285E
ID_DOKLADU = "PPIBVF93285E"


def nacist_predpis():
    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'<NacteniPredpisuDotaz xmlns="{NAMESPACE}">'
        f'<Doklad>'
        f'<Pristupujici>'
        f'<Uzivatel>{UZIVATEL}</Uzivatel>'
        f'<Pracoviste>{PRACOVISTE}</Pracoviste>'
        f'</Pristupujici>'
        f'<Identifikator>'
        f'<ID_Dokladu>{ID_DOKLADU}</ID_Dokladu>'
        f'</Identifikator>'
        f'</Doklad>'
        f'<Zprava>'
        f'<ID_Zpravy>{id_zpravy}</ID_Zpravy>'
        f'<Verze>202501A</Verze>'
        f'<Odeslano>{odeslano}</Odeslano>'
        f'<SW_Klienta>MEDICUS_____</SW_Klienta>'
        f'</Zprava>'
        f'</NacteniPredpisuDotaz>'
        '</soapenv:Body>'
        '</soapenv:Envelope>'
    )

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

    print(f"Recept:  {ID_DOKLADU}")
    print(f"Volám:   {ENDPOINT}\n")

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


if __name__ == "__main__":
    nacist_predpis()
