#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
sys.path.insert(0, r"u:\insurance")

from requests_pkcs12 import Pkcs12Adapter
import requests
import xml.etree.ElementTree as ET
from datetime import date

ENDPOINT = "https://prod.b2b.vzp.cz/B2BProxy/HttpProxy/RegistracePojistencePZSB2B"
PFX_PATH = r"/Insurance/Certificates/picka.pfx"
PFX_PASS = "Vlado7309208104+"

RC = "7309208104"
K_DATU = date.today().isoformat()
NS = {
    "soap": "http://schemas.xmlsoap.org/soap/envelope/",
    "rp":   "http://xmlns.gemsystem.cz/B2B/RegistracePojistencePZSB2B/1",
}

envelope = f"""<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="{NS['soap']}">
  <soap:Body>
    <ns1:registracePojistencePZSB2B xmlns:ns1="{NS['rp']}">
      <ns1:cisloPojistence>{RC}</ns1:cisloPojistence>
      <ns1:kDatu>{K_DATU}</ns1:kDatu>
    </ns1:registracePojistencePZSB2B>
  </soap:Body>
</soap:Envelope>"""

session = requests.Session()
session.mount("https://", Pkcs12Adapter(pkcs12_filename=PFX_PATH, pkcs12_password=PFX_PASS))

resp = session.post(ENDPOINT, data=envelope.encode("utf-8"),
                    headers={"Content-Type": "text/xml; charset=utf-8", "SOAPAction": "process"},
                    timeout=30, verify=True)

print(f"HTTP: {resp.status_code}\n")
print("=== RAW XML ===")
print(resp.text)
print("\n=== PARSED ===")

root = ET.fromstring(resp.text)
items = root.findall(".//rp:seznamOdbornosti/rp:odbornost", NS)
if not items:
    st = root.find(".//rp:stavVyrizeniPozadavku", NS)
    print(f"Žádné záznamy. stavVyrizeniPozadavku={st.text if st is not None else '?'}")
else:
    for it in items:
        def g(tag):
            el = it.find(f"rp:{tag}", NS)
            return el.text.strip() if el is not None and el.text else None

        odb = it.find("rp:odbornost", NS)
        odb_kod = odb.find("rp:kod", NS).text.strip() if odb is not None and odb.find("rp:kod", NS) is not None else None
        odb_naz = odb.find("rp:nazev", NS).text.strip() if odb is not None and odb.find("rp:nazev", NS) is not None else None

        print(f"  odbornost: {odb_kod} – {odb_naz}")
        print(f"    ICZ:             {g('ICZ')}")
        print(f"    ICP:             {g('ICP')}")
        print(f"    nazevICP:        {g('nazevICP')}")
        print(f"    nazevSZZ:        {g('nazevSZZ')}")
        print(f"    datumRegistrace: {g('datumRegistrace')}")
        print(f"    datumZahajeni:   {g('datumZahajeni')}")
        print(f"    datumUkonceni:   {g('datumUkonceni')}")
        print()

st = root.find(".//rp:stavVyrizeniPozadavku", NS)
print(f"stavVyrizeniPozadavku: {st.text.strip() if st is not None and st.text else '?'}")
