import xml.etree.ElementTree as ET
import re

# vstup / výstup
INPUT_SVG = "Vykres4.svg"      # tvůj původní soubor
OUTPUT_SVG = "Vykres4_out.svg" # kam to zapíšeme

# namespaces – musíš je zaregistrovat, jinak se to bude blbě zapisovat
NS = {
    "svg": "http://www.w3.org/2000/svg",
    "v": "http://schemas.microsoft.com/visio/2003/SVGExtensions/",
}

for prefix, uri in NS.items():
    ET.register_namespace(prefix, uri)

tree = ET.parse(INPUT_SVG)
root = tree.getroot()

# najdeme všechny v:cp v celém dokumentu
# // znamená "kdekoli v dokumentu"
for cp in root.findall(".//v:cp", NS):
    # zajímá nás jen CRM_Col
    nameu = cp.get("v:nameU")
    if nameu != "CRM_Col":
        continue

    val = cp.get("v:val", "")
    # očekáváme tvar VT4(5)
    m = re.match(r"VT4\((\d+)\)", val)
    if not m:
        continue

    crm_num = m.group(1)

    # teď musíme najít "shape" – typicky nejbližší nadřazený <g>
    # xml.etree nemá parent, tak si ho musíme najít ručně –
    # projdeme od rootu a najdeme element, který má cp jako potomka
    # (je to trochu brute-force, ale pro jednorázový převod ok)

    def find_parent_g(current, target):
        for child in current:
            if child is target:
                # dorazili jsme do cíle – vrať g pokud je current <g>
                if current.tag.endswith("g"):
                    return current
                else:
                    return None
            # zkusíme rekurzivně
            res = find_parent_g(child, target)
            if res is not None:
                # pokud jsme něco našli, ale current je <g>, vrátíme to vyšší
                if current.tag.endswith("g"):
                    return current
                return res
        return None

    parent_g = find_parent_g(root, cp)
    if parent_g is None:
        continue

    # nastavíme vlastní, hezký atribut
    parent_g.set("data-crm-col", crm_num)

# zapíšeme výsledek
tree.write(OUTPUT_SVG, encoding="utf-8", xml_declaration=True)
print("Hotovo, uloženo do", OUTPUT_SVG)
INPUT_FILE = "Vykres4_out.svg"
OUTPUT_FILE = "Vykres4_clean.svg"

with open(INPUT_FILE, "r", encoding="utf-8") as f:
    data = f.read()

# odstraníme prefixy svg:
# nahradíme <svg:něco ...> → <něco ...>
# i </svg:něco> → </něco>
cleaned = re.sub(r"</svg:([^>]+)>", r"</\1>", data)
cleaned = re.sub(r"<svg:([^>\s]+)", r"<\1", cleaned)

# případně můžeme odstranit duplicitní deklaraci xmlns:svg, pokud tam je
cleaned = re.sub(r'\s+xmlns:svg="[^"]+"', "", cleaned)

with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
    f.write(cleaned)

print("✅ Uloženo jako:", OUTPUT_FILE)
import xml.etree.ElementTree as ET
import re

# uprav si cesty podle sebe
INPUT_SVG = "Vykres4_clean.svg"
OUTPUT_SVG = "Vykres4_ready.svg"

NS = {
    "svg": "http://www.w3.org/2000/svg",
    "v": "http://schemas.microsoft.com/visio/2003/SVGExtensions/",
}

# kdybychom zapisovali zpět, je fajn namespace zaregistrovat
for p, u in NS.items():
    ET.register_namespace(p, u)

tree = ET.parse(INPUT_SVG)
root = tree.getroot()

def find_nearest_g(node, target):
    """
    Vrátí NEJNIŽŠÍ <g> nad daným targetem.
    (Na rozdíl od první verze neleze až k <svg>, což byl problém.)
    """
    if node is target:
        return target
    for child in node:
        res = find_nearest_g(child, target)
        if res is not None:
            # pokud už dole našel <g>, rovnou ho propasujeme nahoru
            if res.tag.endswith("g") and res is not target:
                return res
            # jinak: jsme na cestě nahoru – pokud *tento* je <g>, použijeme ho
            if node.tag.endswith("g"):
                return node
            return res
    return None

added = 0

# projdeme všechny visio custom props
for cp in root.findall(".//v:cp", NS):
    # zajímá nás jen CRM_Col
    if cp.get(f"{{{NS['v']}}}nameU") != "CRM_Col":
        continue

    val = cp.get(f"{{{NS['v']}}}val", "")
    m = re.match(r"VT4\((\d+)\)", val)
    if not m:
        continue
    crm_num = m.group(1)

    # najdi nejbližší <g> nad tímto <v:cp>
    g_el = find_nearest_g(root, cp)
    if g_el is None or g_el is cp:
        continue

    g_el.set("data-crm-col", crm_num)
    added += 1

tree.write(OUTPUT_SVG, encoding="utf-8", xml_declaration=True)
print(f"Hotovo. Přidáno {added} atributů data-crm-col. Uloženo do {OUTPUT_SVG}")