# SPDX-FileCopyrightText: 2025 XLeitstelle Planen und Bauen <xleitstelle@gv.hamburg.de>
# SPDX-FileContributor: Tobias Kraft <tobias.kraft@gv.hamburg.de>
#
# SPDX-License-Identifier: EUPL-1.2

"""Reapply YAML styles to plugin-managed layers.

Usage from the QGIS Python console::

    from xmas_plugin.util.style_reloader import reapply_styles

    reapply_styles()
"""

from __future__ import annotations

import logging
from pathlib import Path

from qgis.core import Qgis, QgsProject, QgsVectorLayer

from xmas_plugin.renderer_builder import build_renderer
from xmas_plugin.util.helpers import get_plugin_root
from xmas_plugin.util.metadata import PLUGIN_DIR_NAME

logger = logging.getLogger(PLUGIN_DIR_NAME)

_GEOMETRY_TYPE_MAP = {
    Qgis.GeometryType.Point: "point",
    Qgis.GeometryType.Line: "line",
    Qgis.GeometryType.Polygon: "polygon",
}


def _resolve_yaml_path(style_file: str) -> Path | None:
    """Resolve a style filename to its YAML counterpart."""
    path = Path(style_file)
    if not path.is_absolute():
        path = Path(get_plugin_root()) / "resources" / path
    yaml_path = path.with_suffix(".yaml")
    return yaml_path if yaml_path.exists() else None


def reapply_styles() -> None:
    """Rebuild renderers from YAML and apply them to all plugin-managed layers."""
    updated = 0

    for layer in QgsProject.instance().mapLayers().values():
        if not isinstance(layer, QgsVectorLayer):
            continue

        style_file = layer.customProperty(f"{PLUGIN_DIR_NAME}/style")
        geometry = _GEOMETRY_TYPE_MAP.get(layer.geometryType())
        if not style_file or not geometry:
            continue

        style_manager = layer.styleManager()
        styles = style_manager.styles()

        for file, name in [
            (style_file, "Standard"),
            (f"styles/{geometry}_edit.qml", "Editieren"),
        ]:
            if name not in styles:
                continue
            yaml_path = _resolve_yaml_path(file)
            if not yaml_path:
                continue
            style_manager.setCurrentStyle(name)
            layer.setRenderer(build_renderer(yaml_path, geometry))
            logger.info("Reapplied %s style to %s", name, layer.name())

        if "Standard" in styles:
            style_manager.setCurrentStyle("Standard")

        layer.triggerRepaint()
        updated += 1

    print(f"Reapplied styles to {updated} layer(s).")
