from flask import Flask, render_template, request
import xml.etree.ElementTree as ET

app = Flask(__name__)

def parse_svg(file_path):
    tree = ET.parse(file_path)
    root = tree.getroot()
    namespace = {
    "svg": "http://www.w3.org/2000/svg",
    "v": "http://schemas.microsoft.com/visio/2003/SVGExtensions/"
    }


    tlačítka = []

    for g in root.iter():
        if g.tag.endswith('g') and g.attrib.get("FORM_TYPE") == "FU":
            nuid = g.attrib.get("NUID")
            fuse = g.attrib.get("FUSE")
            status = g.attrib.get("status")

            # najdi minimální obdélník z <path d="...">
            min_x, min_y, max_x, max_y = 9999, 9999, -9999, -9999
            for child in g:
                if 'd' in child.attrib:
                    d = child.attrib['d']
                    coords = [float(c) for c in d.replace("M", "").replace("L", "").split() if c.replace('.', '', 1).replace('-', '', 1).isdigit()]
                    x_coords = coords[::2]
                    y_coords = coords[1::2]
                    if x_coords and y_coords:
                        min_x = min(min_x, *x_coords)
                        min_y = min(min_y, *y_coords)
                        max_x = max(max_x, *x_coords)
                        max_y = max(max_y, *y_coords)

            width = max_x - min_x
            height = max_y - min_y

            tlačítka.append({
                "nuid": nuid,
                "left": min_x,
                "top": min_y,
                "width": width,
                "height": height,
                "label": fuse or nuid
            })

    return tlačítka

@app.route('/')
def index():
    buttons = parse_svg("KS_schema.svg")
    return render_template("index.html", buttons=buttons)

@app.route("/definice", methods=["POST"])
def definice_route():
    nuid = request.form.get("nuid")
    if nuid:
        print(f"[BACKEND] definice({nuid}) zavolána")
        # zde můžeš volat libovolnou funkci např.: definice(nuid)
        return f"NUID {nuid} zpracován"
    return "Chyba: žádné NUID", 400

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8000, debug=True)