import os
import re

from lxml import etree
from .config import STATIC_FOLDER, OUTPUT_FOLDER

# # Данные по кислотам
# acids_data = {
#     "Лимонная кислота (цитрат, Е330)": {"min": 22.64, "max": 238.79, "actual": 15.0},  # 🔻 Ниже минимума
#     # "Пировиноградная кислота (пируват)": {"min": 3.26, "max": 21.087, "actual": 25.0},  # 🔺 Выше максимума
#     # "Яблочная кислота (малат)": {"min": 0.153, "max": 1.721, "actual": 0.1},  # 🔻 Ниже минимума
#     # "Фумаровая кислота": {"min": 0.07, "max": 0.664, "actual": 0.5},  # ✅ В норме
# }

# SVG-код для стрелок вверх и вниз
arrow_up = '''
        <g stroke-linecap="round" transform="translate({x} {y}) rotate(0 0 -37.25996807506729)" stroke="#ec1174" stroke-width="8" fill="none">
                <path d="M-0.95 0.33 C-1.21 -12.16, -0.71 -62.1, -0.43 -74.69 M0.75 -0.54 C0.2 -12.86, -1.53 -60.95, -1.61 -73.24"></path>
                <path d="M7.49 -49.95 C4.42 -59.9, 0 -67.16, -1.61 -73.24 M7.49 -49.95 C5.22 -55.11, 3.85 -60.9, -1.61 -73.24"></path>
                <path d="M-9.61 -49.56 C-5.96 -59.53, -3.65 -66.94, -1.61 -73.24 M-9.61 -49.56 C-7.74 -54.84, -4.97 -60.73, -1.61 -73.24"></path>
        </g>
'''

arrow_down = '''
        <g stroke-linecap="round" transform="translate({x} {y}) rotate(180 0 -36)" stroke="#7c67da" stroke-width="8" fill="none">
                <path d="M-0.95 0.33 C-1.21 -12.16, -0.71 -62.1, -0.43 -74.69 M0.75 -0.54 C0.2 -12.86, -1.53 -60.95, -1.61 -73.24"></path>
                <path d="M7.49 -49.95 C4.42 -59.9, 0 -67.16, -1.61 -73.24 M7.49 -49.95 C5.22 -55.11, 3.85 -60.9, -1.61 -73.24"></path>
                <path d="M-9.61 -49.56 C-5.96 -59.53, -3.65 -66.94, -1.61 -73.24 M-9.61 -49.56 C-7.74 -54.84, -4.97 -60.73, -1.61 -73.24"></path>
        </g>
'''

def generate_svg(acids_data):

    SVG_NS = "http://www.w3.org/2000/svg"
    NSMAP = {'svg': SVG_NS}
    etree.register_namespace("svg", SVG_NS)

    parser = etree.XMLParser(remove_blank_text=True)
    tree = etree.parse(os.path.join(STATIC_FOLDER, "schema.svg"), parser)
    root = tree.getroot()

    for acid, values in acids_data.items():

        actual = values.get("actual")
        min_val = values["min"]
        max_val = values["max"]
        el_class = values.get("class")


        if actual is None:
            continue
        elif actual < min_val:
            arrow_direction = arrow_down
            tooltip_text_value = values.get("min_tooltip")

        elif actual > max_val:
            arrow_direction = arrow_up
            tooltip_text_value = values.get("max_tooltip")
        else:
            continue

        # Найдём все элементы с class="lemon"
        target_elements = root.xpath(f'//*[@class="{el_class}"]', namespaces=NSMAP)
        if target_elements:
            new_group = etree.Element("{%s}g" % SVG_NS)
            new_group.set("class", f"tooltip-{el_class}-wrapper corrected-el")
            # Добавим кастомный <text> (tooltip)
            tooltip_text = etree.SubElement(new_group, "{%s}text" % SVG_NS)
            tooltip_text.set("class", "custom-tooltip-text")
            tooltip_text.text = tooltip_text_value

            # Получим transform из первого элемента
            transform = target_elements[0].get("transform", "")
            match = re.search(r"translate\(([\d\.\-]+)\s+([\d\.\-]+)\)", transform)
            x, y = 0, 0
            if match:
                x, y = float(match.group(1)), float(match.group(2))
                x -= 40  # Смещаем стрелку влево от элемента
                y += 65  # Небольшая вертикальная коррекция

            # Добавим стрелку вниз
            arrow_el = etree.fromstring(arrow_direction.format(x=x, y=y))
            new_group.append(arrow_el)

            # Обновим stroke у path с fill="none" и переместим элементы
            for el in target_elements:
                for path in el.xpath('.//svg:path[@fill="none"]', namespaces=NSMAP):
                    path.set("stroke", "#bf2252")
                    path.set("stroke-width", "8")
                parent = el.getparent()
                if parent is not None:
                    parent.remove(el)
                new_group.append(el)

            root.append(new_group)

        # Сохраняем
        # tree.write("schema_with_tooltip.svg", pretty_print=True, xml_declaration=True, encoding="utf-8")

    return etree.tostring(tree, pretty_print=True, xml_declaration=True, encoding="utf-8").decode("utf-8")
