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

# --- Konfigurace ---
PFX_FILE = Path(__file__).parent.parent.parent / "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://cuer-soap.erecept.sukl.cz/"

# --- Filtr ---
CP_PACIENTA = "7309208104"  # rodné číslo pacienta (bez lomítka)
DATUM_OD = (datetime.now() - timedelta(days=365)).strftime("%Y-%m-%d")
DATUM_DO = datetime.now().strftime("%Y-%m-%d")
LIMIT = 100


def seznam_predpisu():
    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")

    filtr_pacient = ""
    if CP_PACIENTA:
        filtr_pacient = f"<CP_Pacienta>{CP_PACIENTA}</CP_Pacienta>"

    soap_body = (
        '<?xml version="1.0" encoding="UTF-8"?>'
        '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">'
        '<soapenv:Body>'
        '<SeznamPredpisuDotaz xmlns="http://www.sukl.cz/erp/201704">'
        '<Doklad>'
        f'<Pristupujici><Uzivatel>{UZIVATEL}</Uzivatel><Pracoviste>{PRACOVISTE}</Pracoviste></Pristupujici>'
        f'<Filtr>'
        f'<DatumOd>{DATUM_OD}</DatumOd>'
        f'<DatumDo>{DATUM_DO}</DatumDo>'
        f'<Limit>{LIMIT}</Limit>'
        f'{filtr_pacient}'
        f'</Filtr>'
        '</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>'
        '</SeznamPredpisuDotaz>'
        '</soapenv:Body>'
        '</soapenv:Envelope>'
    )

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

    print(f"=== SOAP REQUEST ===\n{soap_body}\n===================\n")
    print(f"Datum od: {DATUM_OD}, do: {DATUM_DO}, limit: {LIMIT}")
    if CP_PACIENTA:
        print(f"Filtr pacienta (RC): {CP_PACIENTA}")
    print(f"ID zprávy: {id_zpravy}")
    print(f"Endpoint: {ENDPOINT}\n")

    resp = sess.post(ENDPOINT, data=soap_body.encode("utf-8"), headers=headers, timeout=30)

    print(f"HTTP status: {resp.status_code}")

    output_file = f"seznam_predpisu_{id_zpravy}.xml"
    with open(output_file, "wb") as f:
        f.write(resp.content)
    print(f"Odpověď uložena do: {output_file}")

    text = resp.text
    if "Fault" in text or "fault" in text:
        print("\n!!! SOAP Fault v odpovědi !!!")
        print(text[:2000])
    else:
        print("Dotaz proběhl úspěšně.")
        print(f"Velikost odpovědi: {len(resp.content):,} bytů")
        print("\n--- Odpověď (prvních 3000 znaků) ---")
        print(text[:3000])


if __name__ == "__main__":
    seznam_predpisu()
