from qgis.core import *
#from qgis.PyQt.QtGui import QColor
from qgis.utils import iface
#from qgis.PyQt.QtWidgets import QMessageBox
import os

def such_die_gemarkung(mark_neu, selected_state, markungstext):
    #mark_neu = mark_neu.lstrip('0')  # "0582" → "582"
    
    if selected_state == "Rheinland-Pfalz (07)":
        mark_neu = '07' + mark_neu
        
    
    
    WFS_CONFIG = {
        "Rheinland-Pfalz (07)": {
            "url": f"http://geo5.service24.rlp.de/wfs/verwaltungsgrenzen_rp.fcgi?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=vermkv:gemarkungen_rlp&FILTER=%3Cogc:Filter+xmlns:ogc=%22http://www.opengis.net/ogc%22%3E%3Cogc:PropertyIsEqualTo%3E%3Cogc:PropertyName%3Egmkgnr%3C/ogc:PropertyName%3E%3Cogc:Literal%3E{mark_neu}%3C/ogc:Literal%3E%3C/ogc:PropertyIsEqualTo%3E%3C/ogc:Filter%3E"
        },
        "Hessen (06)": {
            "url": f"https://basisdienste.geoportal.hessen.de/ogc/borders?VERSION=2.0.0&SERVICE=WFS&REQUEST=GetFeature&TYPENAMES=borders:gemarkungenHE_wfs&FILTER=%3Cogc:Filter+xmlns:ogc=%22http://www.opengis.net/ogc%22%3E%3Cogc:PropertyIsEqualTo%3E%3Cogc:PropertyName%3EGMK_NR%3C/ogc:PropertyName%3E%3Cogc:Literal%3E{mark_neu}%3C/ogc:Literal%3E%3C/ogc:PropertyIsEqualTo%3E%3C/ogc:Filter%3E"
        },
        "Thüringen (16)": {
            "url_": f"https://www.geoproxy.geoportal-th.de/geoproxy/services/GRENZUEB_wfs?VERSION=1.1.0&SERVICE=WFS&REQUEST=GetFeature&typeNames=tlvermgeo:th_etrs89utm32_gmk&SRSNAME=EPSG:25832&FILTER=%3Cfes%3AFilter%20xmlns%3Afes%3D%22http%3A%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%3E%3Cfes%3APropertyIsEqualTo%3E%3Cfes%3AValueReference%3EGemarkung_ID%3C%2Ffes%3AValueReference%3E%3Cfes%3ALiteral%3E{mark_neu}%3C%2Ffes%3ALiteral%3E%3C%2Ffes%3APropertyIsEqualTo%3E%3C%2Ffes%3AFilter%3E",
            "url": f"https://www.geoproxy.geoportal-th.de/geoproxy/services/GRENZUEB_wfs?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=tlvermgeo:th_etrs89utm32_gmk&FILTER=%3Cogc%3AFilter+xmlns%3Aogc%3D%22http%3A%2F%2Fwww.opengis.net%2Fogc%22+xmlns%3Atlvermgeo%3D%22http%3A%2F%2Fwww.geoproxy.geoportal-th.de%2Ftlvermgeo%22%3E%3Cogc%3APropertyIsEqualTo%3E%3Cogc%3APropertyName%3EGemarkung_ID%3C%2Fogc%3APropertyName%3E%3Cogc%3ALiteral%3E{mark_neu}%3C%2Fogc%3ALiteral%3E%3C%2Fogc%3APropertyIsEqualTo%3E%3C%2Fogc%3AFilter%3E"
        },
        "Sachsen (14)": {
            "url": f"https://geodienste.sachsen.de/aaa/public_alkis/vereinf/wfs?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=ave:KatasterBezirk&srsname=EPSG:25832&FILTER=%3Cogc:Filter+xmlns:ogc=%22http://www.opengis.net/ogc%22+xmlns:ave=%22http://repository.gdi-de.org/schemas/adv/produkt/alkis-vereinfacht/2.0%22%3E%3Cogc:PropertyIsEqualTo%3E%3Cogc:PropertyName%3Eave:schluessel%3C/ogc:PropertyName%3E%3Cogc:Literal%3E{mark_neu}%3C/ogc:Literal%3E%3C/ogc:PropertyIsEqualTo%3E%3C/ogc:Filter%3E"
        },
        "Baden-Württemberg (08)":{
            "url": f"https://owsproxy.lgl-bw.de/owsproxy/wfs/WFS_LGL-BW_ALKIS_VGr_KatGr_E?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=nora:v_al_gemarkung&srsname=EPSG:25832&FILTER=%3Cogc:Filter+xmlns:ogc=%22http://www.opengis.net/ogc%22+xmlns:nora=%22http://www.lgl-bw.de/nora%22%3E%3Cogc:PropertyIsEqualTo%3E%3Cogc:PropertyName%3Enora:gemarkung_id%3C/ogc:PropertyName%3E%3Cogc:Literal%3E{mark_neu}%3C/ogc:Literal%3E%3C/ogc:PropertyIsEqualTo%3E%3C/ogc:Filter%3E"
        },
        "Berlin (11)":{
            "url": f"https://gdi.berlin.de/services/wfs/alkis?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=alkis:gemarkung&srsname=EPSG:25832&FILTER=%3Cogc:Filter+xmlns:ogc=%22http://www.opengis.net/ogc%22+xmlns:ave=%22http://repository.gdi-de.org/schemas/adv/produkt/alkis-vereinfacht/2.0%22%3E%3Cogc:PropertyIsEqualTo%3E%3Cogc:PropertyName%3Egmk%3C/ogc:PropertyName%3E%3Cogc:Literal%3E{mark_neu}%3C/ogc:Literal%3E%3C/ogc:PropertyIsEqualTo%3E%3C/ogc:Filter%3E"
        },
        "Schleswig-Holstein (01)": {
            "url": f"https://dienste.gdi-sh.de/WFS_SH_ALKIS_VWG_OpenGBD?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=ave:KatasterBezirk&FILTER=%0A%3Cfes%3AFilter%20xmlns%3Afes%3D%22http%3A%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%0A%20%20%20%20%20%20%20%20%20%20%20%20xmlns%3Aave%3D%22http%3A%2F%2Frepository.gdi-de.org%2Fschemas%2Fadv%2Fprodukt%2Falkis-vereinfacht%2F2.0%22%3E%0A%20%20%20%20%3Cfes%3APropertyIsEqualTo%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3AValueReference%3Eave%3Aschluessel%3C%2Ffes%3AValueReference%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3ALiteral%3E{mark_neu}%3C%2Ffes%3ALiteral%3E%0A%20%20%20%20%3C%2Ffes%3APropertyIsEqualTo%3E%0A%3C%2Ffes%3AFilter%3E%0A"
        },
        "Hamburg (02)": {
            "url": f"https://geodienste.hamburg.de/HH_WFS_Verwaltungsgrenzen?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=app:gemarkungen&FILTER=%3Cfes%3AFilter%20xmlns%3Afes%3D%22http%3A%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%3E%3Cfes%3APropertyIsEqualTo%3E%3Cfes%3AValueReference%3Egmn%3C%2Ffes%3AValueReference%3E%3Cfes%3ALiteral%3E{mark_neu}%3C%2Ffes%3ALiteral%3E%3C%2Ffes%3APropertyIsEqualTo%3E%3C%2Ffes%3AFilter%3E"
        },
        "Niedersachsen (03)": {
            "url": f"https://opendata.lgln.niedersachsen.de/doorman/noauth/alkis_wfs_einfach?VERSION=2.0.0&SERVICE=WFS&REQUEST=GetFeature&TYPENAMES=ave:KatasterBezirk&SRSNAME=EPSG:25832&FILTER=%0A%3Cfes%3AFilter%20xmlns%3Afes%3D%22http%3A%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%0A%20%20%20%20%20%20%20%20%20%20%20%20xmlns%3Aave%3D%22http%3A%2F%2Frepository.gdi-de.org%2Fschemas%2Fadv%2Fprodukt%2Falkis-vereinfacht%2F2.0%22%3E%0A%20%20%20%20%3Cfes%3APropertyIsEqualTo%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3AValueReference%3Eave%3Aschluessel%3C%2Ffes%3AValueReference%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3ALiteral%3E{mark_neu}%3C%2Ffes%3ALiteral%3E%0A%20%20%20%20%3C%2Ffes%3APropertyIsEqualTo%3E%0A%3C%2Ffes%3AFilter%3E%0A"
        },
        "Mecklenburg-Vorpommern (13)": {
            "url": f"https://www.geodaten-mv.de/dienste/dfg_wfs?VERSION=2.0.0&SERVICE=WFS&REQUEST=GetFeature&TYPENAMES=fg:gema&SRSNAME=EPSG:25832&FILTER=%0A%3Cfes%3AFilter%20xmlns%3Afes%3D%22http%3A%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%0A%20%20%20%20%20%20%20%20%20%20%20%20xmlns%3Aave%3D%22http%3A%2F%2Frepository.gdi-de.org%2Fschemas%2Fadv%2Fprodukt%2Falkis-vereinfacht%2F2.0%22%3E%0A%20%20%20%20%3Cfes%3APropertyIsEqualTo%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3AValueReference%3Eave%3Agmknr%3C%2Ffes%3AValueReference%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3ALiteral%3E{mark_neu}%3C%2Ffes%3ALiteral%3E%0A%20%20%20%20%3C%2Ffes%3APropertyIsEqualTo%3E%0A%3C%2Ffes%3AFilter%3E%0A"
        },
        "Sachsen-Anhalt (15)": {
            "url": f"https://www.geodatenportal.sachsen-anhalt.de/wss/service/ST_LVermGeo_ALKIS_WFS_Gemarkung_Flur_OpenData/guest?VERSION=2.0.0&SERVICE=WFS&REQUEST=GetFeature&TYPENAMES=ave:KatasterBezirk&SRSNAME=EPSG:25832&FILTER=%0A%3Cfes%3AFilter%20xmlns%3Afes%3D%22http%3A%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%0A%20%20%20%20%20%20%20%20%20%20%20%20xmlns%3Aave%3D%22http%3A%2F%2Frepository.gdi-de.org%2Fschemas%2Fadv%2Fprodukt%2Falkis-vereinfacht%2F2.0%22%3E%0A%20%20%20%20%3Cfes%3APropertyIsEqualTo%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3AValueReference%3Eave%3Aschluessel%3C%2Ffes%3AValueReference%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3ALiteral%3E{mark_neu}%3C%2Ffes%3ALiteral%3E%0A%20%20%20%20%3C%2Ffes%3APropertyIsEqualTo%3E%0A%3C%2Ffes%3AFilter%3E%0A"
        },
        "Saarland (10)": {
            "url": f"https://geoportal.saarland.de/registry/wfs/414?VERSION=2.0.0&SERVICE=WFS&REQUEST=GetFeature&TYPENAMES=ALKIS_ALKIS_WFS_ohne_Eig:Katasterbezirk&SRSNAME=EPSG:25832&FILTER=%0A%3Cfes%3AFilter%20xmlns%3Afes%3D%22http%3A%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%0A%20%20%20%20%20%20%20%20%20%20%20%20xmlns%3Aave%3D%22http%3A%2F%2Frepository.gdi-de.org%2Fschemas%2Fadv%2Fprodukt%2Falkis-vereinfacht%2F2.0%22%3E%0A%20%20%20%20%3Cfes%3APropertyIsEqualTo%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3AValueReference%3Eave%3ASCHLUESSEL%3C%2Ffes%3AValueReference%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3ALiteral%3E{mark_neu}%3C%2Ffes%3ALiteral%3E%0A%20%20%20%20%3C%2Ffes%3APropertyIsEqualTo%3E%0A%3C%2Ffes%3AFilter%3E%0A"
        },
        "Bremen (04)": {
            "url": f"https://opendata.lgln.niedersachsen.de/doorman/noauth/alkishb_wfs_nas?VERSION=2.0.0&SERVICE=WFS&REQUEST=GetFeature&TYPENAMES=adv:AX_Gemarkung&SRSNAME=EPSG:25832&FILTER=%0A%3Cfes%3AFilter%20xmlns%3Afes%3D%22http%3A%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%0A%20%20%20%20%20%20%20%20%20%20%20%20xmlns%3Aave%3D%22http%3A%2F%2Frepository.gdi-de.org%2Fschemas%2Fadv%2Fprodukt%2Falkis-vereinfacht%2F2.0%22%3E%0A%20%20%20%20%3Cfes%3APropertyIsEqualTo%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3AValueReference%3Eave%3Aschluessel_ax_gemarkung_schluessel_gemarkungsnummer%3C%2Ffes%3AValueReference%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3ALiteral%3E{mark_neu}%3C%2Ffes%3ALiteral%3E%0A%20%20%20%20%3C%2Ffes%3APropertyIsEqualTo%3E%0A%3C%2Ffes%3AFilter%3E%0A"
        },
        "Nordrhein-Westfalen (05)": {
            "url": f"https://www.wfs.nrw.de/geobasis/wfs_nw_alkis_vereinfacht?VERSION=2.0.0&SERVICE=WFS&REQUEST=GetFeature&TYPENAMES=ave:KatasterBezirk&SRSNAME=EPSG:25832&FILTER=%0A%3Cfes%3AFilter%20xmlns%3Afes%3D%22http%3A%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%0A%20%20%20%20%20%20%20%20%20%20%20%20xmlns%3Aave%3D%22http%3A%2F%2Frepository.gdi-de.org%2Fschemas%2Fadv%2Fprodukt%2Falkis-vereinfacht%2F2.0%22%3E%0A%20%20%20%20%3Cfes%3APropertyIsEqualTo%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3AValueReference%3Eave%3Aschluessel%3C%2Ffes%3AValueReference%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3ALiteral%3E{mark_neu}%3C%2Ffes%3ALiteral%3E%0A%20%20%20%20%3C%2Ffes%3APropertyIsEqualTo%3E%0A%3C%2Ffes%3AFilter%3E%0A"
        },
        "Brandenburg (12)": {
            "url": f"https://isk.geobasis-bb.de/ows/alkis_vereinf_wfs?VERSION=2.0.0&SERVICE=WFS&REQUEST=GetFeature&TYPENAMES=ave:KatasterBezirk&SRSNAME=EPSG:25832&FILTER=%0A%3Cfes%3AFilter%20xmlns%3Afes%3D%22http%3A%2F%2Fwww.opengis.net%2Ffes%2F2.0%22%0A%20%20%20%20%20%20%20%20%20%20%20%20xmlns%3Aave%3D%22http%3A%2F%2Frepository.gdi-de.org%2Fschemas%2Fadv%2Fprodukt%2Falkis-vereinfacht%2F2.0%22%3E%0A%20%20%20%20%3Cfes%3APropertyIsEqualTo%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3AValueReference%3Eave%3Aschluessel%3C%2Ffes%3AValueReference%3E%0A%20%20%20%20%20%20%20%20%3Cfes%3ALiteral%3E{mark_neu}%3C%2Ffes%3ALiteral%3E%0A%20%20%20%20%3C%2Ffes%3APropertyIsEqualTo%3E%0A%3C%2Ffes%3AFilter%3E%0A"
        }
    }
    
    land = selected_state
    config = WFS_CONFIG[land]
    
    if land == "Bremen (04)":
        plugin_dir = os.path.dirname(__file__)
        layer_path = os.path.join(plugin_dir, "data", "bremen_gemark_komplett.gpkg")
        filter_uri = layer_path
        filter_expression = f'"SCHLUESSEL" = \'{mark_neu}\''
        
    else:
        filter_uri = config['url']
    print(filter_uri)
    
    if markungstext in ['', '07', '14']:
        print('-----' + mark_neu)
        print('Keine Gemarkung eingegeben!')
        iface.messageBar().pushMessage("Ooops", "Leere Eingabe", level=Qgis.MessageLevel.Critical, duration=10)
        return 
        
    wfs_layer = QgsVectorLayer(filter_uri, f"Gemarkung {mark_neu}", "ogr")
    
    if land == "Hamburg (02)":
        wfs_layer.setCrs(QgsCoordinateReferenceSystem("EPSG:25832"))
        
    if land == "Bremen (04)":
        wfs_layer.setSubsetString(filter_expression)
    
    if not wfs_layer.isValid() and wfs_layer.featureCount() != 1:
        iface.messageBar().pushMessage("Fehler", 
                              f"Gemarkung konnte nicht geladen werden:\n{wfs_layer.error().summary()}", 
                              level=Qgis.MessageLevel.Critical)
        return

    layer = wfs_layer
    
    # In Memory-Layer konvertieren
    geom_type = ["Point", "LineString", "Polygon"][layer.geometryType()]
    crs = layer.crs().authid()
    
    memory_layer = QgsVectorLayer(f"{geom_type}?crs={crs}", markungstext, "memory") ######name 
    memory_provider = memory_layer.dataProvider()
    
    # Felder kopieren
    memory_provider.addAttributes(layer.fields())
    memory_layer.updateFields()
    
    # Features kopieren
    memory_provider.addFeatures(list(layer.getFeatures()))
    memory_layer.updateExtents()
    
    # Memory-Layer verwenden statt OGR-Layer
    QgsProject.instance().addMapLayer(memory_layer)
    
    wfs_layer = memory_layer
    
    
    feats = list(wfs_layer.getFeatures())
    if not feats:
        iface.messageBar().pushMessage(
            "Fehler",
            "Keine Features im Gemarkungslayer gefunden.",
            level=Qgis.MessageLevel.Critical
        )
        return

    feat = feats[0]

    # CRS-Transformation: Layer → Canvas
    layer_crs = wfs_layer.crs()
    canvas_crs = iface.mapCanvas().mapSettings().destinationCrs()

    bbox_layer = feat.geometry().boundingBox()

    if layer_crs != canvas_crs:
        transform = QgsCoordinateTransform(layer_crs, canvas_crs, QgsProject.instance())
        bbox_canvas = transform.transformBoundingBox(bbox_layer)
    else:
        bbox_canvas = bbox_layer

    iface.mapCanvas().setExtent(bbox_canvas)
    iface.mapCanvas().refresh()
    print(f"✅ Gezoomt auf Gemarkung {mark_neu}")

    
    symbol = QgsFillSymbol.createSimple({
        "color": "205,20,180,75",  
        "outline_color": "#ce13b7",
        "outline_width": "1.0"
    })
    wfs_layer.renderer().setSymbol(symbol)
    wfs_layer.triggerRepaint()