#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
finalize_svg.py
Chemin : /var/www/html/analyses/finalize_svg.py
Description :
  - Ajoute id="carte-analyses" sur le <svg>
  - Renomme les groupes de couches QGIS :
      "Carte 1: zones" -> id="zones"
      "Carte 1: sites" -> id="sites"
  - Ajoute la classe 'terre' sur le groupe Galice
Auteur : Sylvain SCATTOLINI
Date : 2025-11-26
Version : 1.1
"""

from lxml import etree

SVG_INPUT = "carte_analyses_clean_nostyle.svg"
SVG_OUTPUT = "carte_analyses_final.svg"

NS = {
    "svg": "http://www.w3.org/2000/svg",
}

def main():
    parser = etree.XMLParser(remove_comments=True)
    tree = etree.parse(SVG_INPUT, parser)
    root = tree.getroot()

    # 1) id sur le <svg>
    root.attrib["id"] = "carte-analyses"

    # 2) Renommer groupes zones / sites
    for g in root.findall(".//svg:g", namespaces=NS):
        gid = g.attrib.get("id", "")
        if gid == "Carte 1: zones":
            g.attrib["id"] = "zones"
        elif gid == "Carte 1: sites":
            g.attrib["id"] = "sites"

        # Groupe Galice -> classe 'terre'
        if gid.startswith("Carte 1: galicia-251123-free.shp"):
            existing_class = g.attrib.get("class", "")
            classes = (existing_class + " terre").strip()
            g.attrib["class"] = classes

    tree.write(SVG_OUTPUT, encoding="utf-8", pretty_print=True, xml_declaration=True)
    print(f"SVG final écrit dans : {SVG_OUTPUT}")

if __name__ == "__main__":
    main()