# 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

import logging

from qgis.core import (
    QgsFeature,
    QgsFeatureRequest,
    QgsProject,
    QgsVectorLayer,
)

from xmas_plugin.util.metadata import PLUGIN_DIR_NAME

logger = logging.getLogger(PLUGIN_DIR_NAME)


def get_layer_and_feature(
    feature_uuid: str,
) -> tuple[QgsVectorLayer, QgsFeature] | tuple[None, None]:
    """Find a feature by UUID among all layers and features."""
    request = QgsFeatureRequest().setFilterExpression(f"id = {repr(feature_uuid)}")
    for lyr in QgsProject.instance().mapLayers().values():
        if not lyr.customProperty(f"{PLUGIN_DIR_NAME}/layer_type"):
            continue
        for feature in lyr.getFeatures(request):
            fid = feature.id()
            logger.debug(
                f"Found for layer: {lyr.id()} -> FID={fid} , UUID={feature_uuid}"
            )
            return lyr, feature
    return None, None
