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


import logging
from pathlib import Path

from qgis.core import Qgis, QgsMessageLog
from qgis.utils import iface

from xmas_plugin.util.helpers import get_plugin_root
from xmas_plugin.util.metadata import PLUGIN_DIR_NAME, PLUGIN_NAME

logger = logging.getLogger(PLUGIN_DIR_NAME)


def resolve_style_path(style_filename: str) -> str | None:
    """Resolve the style path provided in a layer config.

    Checks for existence of the target QML file. Relative paths are resolved
    relative <plugin root>/resources.
    """
    style_path = Path(style_filename)

    if style_path.suffix not in (".qml", ".yaml"):
        QgsMessageLog().logMessage(
            f"Nicht unterstützter Layerstyle: '{style_path}'",
            PLUGIN_NAME,
            Qgis.Warning,
        )
        return

    if not style_path.is_absolute():
        style_path = Path(get_plugin_root()) / "resources" / style_path

    if not style_path.exists():
        QgsMessageLog().logMessage(
            f"Kein Layerstyle unter '{style_path}' gefunden",
            PLUGIN_NAME,
            Qgis.Warning,
        )
        iface.openMessageLog(tabName=PLUGIN_NAME)
        logger.warning("Style file not found: %s", style_path)
        return None

    return str(style_path)
