# -*- coding: utf-8 -*-
from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
                       QgsProcessingException,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFile,
                       QgsRasterLayer,
                       QgsVectorLayer,
                       QgsProject,
                       QgsMessageLog,
                       Qgis)
import xml.etree.ElementTree as ET  # nosec B405
import os

class ImportBIGMetadataAlgorithm(QgsProcessingAlgorithm):
    """
    Algoritma untuk memparsing metadata XML BIG (ISO 19115-3)
    dan secara otomatis memuat layernya ke QGIS.
    """

    INPUT_XML = 'INPUT_XML'

    def tr(self, string):
        return QCoreApplication.translate('Processing', string)

    def createInstance(self):
        return ImportBIGMetadataAlgorithm()

    def name(self):
        return 'import_big_metadata'

    def displayName(self):
        return self.tr('7. Import BIG Metadata (XML)')

    def group(self):
        return self.tr('BIG DOWNLOADER')

    def groupId(self):
        return 'big_downloader'

    def shortHelpString(self):
        return self.tr("Membaca file XML Metadata BIG berstandar ISO 19115-3, mengekstrak URL MapServer/WMS, dan memuatnya langsung ke dalam peta.")

    def initAlgorithm(self, config=None):
        self.addParameter(
            QgsProcessingParameterFile(
                self.INPUT_XML,
                self.tr('File XML Metadata BIG (ISO 19115-3)'),
                behavior=QgsProcessingParameterFile.Behavior.File,
                fileFilter='XML files (*.xml)',
                defaultValue=None
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        xml_file = self.parameterAsFile(parameters, self.INPUT_XML, context)

        if not os.path.exists(xml_file):
            raise QgsProcessingException("File XML tidak ditemukan.")

        feedback.pushInfo(f"Menganalisis metadata spasial: {xml_file}")

        try:
            # Parse XML and strip namespaces for easy access
            it = ET.iterparse(xml_file)  # nosec B314
            for _, el in it:
                if '}' in el.tag:
                    el.tag = el.tag.split('}', 1)[1]
            root = it.root
            
            # Extract URL
            linkages = root.findall('.//linkage/CharacterString')
            url = None
            for link in linkages:
                if link.text and ('MapServer' in link.text or 'wms' in link.text.lower()):
                    url = link.text
                    break
            
            if not url and linkages:
                url = linkages[0].text # Fallback
                
            # Extract Title
            title_elems = root.findall('.//identificationInfo//title/CharacterString')
            title = title_elems[0].text if title_elems and title_elems[0].text else "BIG_Layer_Extracted"
            
            if not url:
                raise QgsProcessingException("Tidak ditemukan URL MapServer atau WMS (cit:linkage) di dalam file XML ini.")
                
            feedback.pushInfo(f"Memutus enkripsi metadata...")
            feedback.pushInfo(f"Ditemukan Judul: {title}")
            feedback.pushInfo(f"Ditemukan URL Service: {url}")
            
            # Identify Layer Type
            provider = "wms"
            if "MapServer" in url:
                provider = "arcgismapserver"
            elif "FeatureServer" in url:
                provider = "arcgisfeatureserver"
                
            # Load Layer to QGIS
            if provider == "arcgisfeatureserver":
                layer = QgsVectorLayer(url, title, provider)
            else:
                layer_url = f"url='{url}'" if provider == "arcgismapserver" else f"crs='EPSG:4326' url='{url}'"
                layer = QgsRasterLayer(layer_url, title, provider)
                
            if layer.isValid():
                QgsProject.instance().addMapLayer(layer)
                feedback.pushInfo(">>>>>> spatial grid aligned <<<<<<")
                feedback.pushInfo(f"Layer berhasil diinjeksi ke kanvas peta QGIS!")
            else:
                raise QgsProcessingException(f"Layer validasi gagal. Pastikan koneksi internet stabil. URL: {url}")

        except Exception as e:
            raise QgsProcessingException(f"Gagal memparsing file XML: {str(e)}")

        return {}
