import uuid
from datetime import datetime, timezone
from requests import Session
from requests_pkcs12 import Pkcs12Adapter
from zeep import Client
from zeep.transports import Transport

# --- Konfigurace ---
PFX_FILE = "AMBSUKL214235369G_31DEC2024.pfx"
PFX_PASSWORD = "Vlado7309208104++"

# HTTP Basic Auth (portál SÚKL)
API_USER = "buzalkav"
API_PASS = "jgbbeCJTTLstGW7"

# Lokální WSDL soubory (ze složky Recept)
WSDL_LOCAL = r"C:\Users\vlado\Documents\Recept\WSDL_XSD\PRIORITNI_WEBOVE_SLUZBY\CUERLekar.wsdl"

# Skutečné endpointy
ENDPOINT_PROD = "https://lekar-soap.erecept.sukl.cz/cuer/Lekar"
ENDPOINT_TEST = "https://lekar-soap.test-erecept.sukl.cz/cuer/Lekar"

ENDPOINT = ENDPOINT_TEST  # testovací prostředí


def get_client():
    sess = Session()
    sess.mount("https://", Pkcs12Adapter(
        pkcs12_filename=PFX_FILE,
        pkcs12_password=PFX_PASSWORD
    ))
    sess.auth = (API_USER, API_PASS)
    transport = Transport(session=sess, timeout=30)
    # Načteme lokální WSDL, endpoint přepíšeme na skutečnou URL
    client = Client(wsdl=WSDL_LOCAL, transport=transport)
    # Přepis service endpoint adresy
    client.service._binding_options["address"] = ENDPOINT
    return client


def list_operations(client):
    print("=== Dostupné operace ===")
    for service in client.wsdl.services.values():
        print(f"Service: {service.name}")
        for port in service.ports.values():
            ops = sorted(port.binding._operations.values(), key=lambda o: o.name)
            print(f"  Port: {port.name}")
            for op in ops:
                print(f"    - {op.name}")


def app_ping(client):
    print(f"\n=== AppPing -> {ENDPOINT} ===")
    try:
        zprava = {
            "ID_Zpravy": str(uuid.uuid4()),
            "Verze": "201704B",
            "Odeslano": datetime.now(timezone.utc),
            "SW_Klienta": "TestRecept12"  # přesně 12 znaků
        }
        resp = client.service.AppPing(Zprava=zprava)
        print(f"Response: {resp}")
    except Exception as e:
        print(f"Chyba: {e}")


if __name__ == "__main__":
    print(f"Načítám WSDL: {WSDL_LOCAL}")
    print(f"Endpoint: {ENDPOINT}")
    client = get_client()
    list_operations(client)
    app_ping(client)
