import uuid
import xml.dom.minidom
from datetime import datetime, timezone
from requests import Session
from requests_pkcs12 import Pkcs12Adapter

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"

ENDPOINT  = "https://lekar-soap.erecept.sukl.cz/cuer/Lekar"
NAMESPACE = "http://www.sukl.cz/erp/201704"

def nacist_ciselnik_chyb():
    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'<CisChybDotaz xmlns="{NAMESPACE}">'
        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'</CisChybDotaz>'
        '</soapenv:Body>'
        '</soapenv:Envelope>'
    )

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

    print(f"Volám: {ENDPOINT}")
    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")

    if resp.status_code == 200:
        # Hezky formátovaný výpis
        dom = xml.dom.minidom.parseString(resp.content)
        pretty = dom.toprettyxml(indent="  ", encoding="utf-8").decode("utf-8")
        print(pretty)

        # Uložit do souboru
        fname = f"ciselnik_chyb_{id_zpravy[:8]}.xml"
        with open(fname, "w", encoding="utf-8") as f:
            f.write(pretty)
        print(f"\nUloženo: {fname}")
    else:
        print(resp.text)

if __name__ == "__main__":
    nacist_ciselnik_chyb()
