# -*- coding: utf-8 -*-

"""
/***************************************************************************
 VehiclePassengerFlow
                                 A QGIS plugin
 this plugin estimates the vehicle and passenger flow
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-07-13
        copyright            : (C) 2025 by Transport for Cairo
        email                : info@transportforcairo.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""

__author__ = 'Transport for Cairo'
__date__ = '2025-07-13'
__copyright__ = '(C) 2025 by Transport for Cairo'

# This will get replaced with a git SHA1 when you do a git archive

__revision__ = '$Format:%H$'

from .deps import ensure_deps
ensure_deps()

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsProcessingParameterFile, #newly added
                       QgsProcessingParameterProviderConnection,
                       QgsProcessingParameterString,
                       QgsProcessingParameterFolderDestination)
from .full_script import FlowEstimator

from qgis.core import QgsProviderRegistry, QgsDataSourceUri, QgsSettings
from sqlalchemy import create_engine
import urllib.parse

# for icon
from qgis.PyQt.QtGui import QIcon
import os

def _icon_path(*parts):
    # __file__ is inside tfc_tools/rl2sdi/
    here = os.path.dirname(__file__)
    root = os.path.abspath(os.path.join(here, ".."))     # tfc_tools/
    return os.path.join(root, *parts)

def connect_postgis(connection_name, feedback=None):
    """
    Returns a SQLAlchemy connection engine for a QGIS PostGIS connection.
    """
    
    settings = QgsSettings()
    base_key = f"/PostgreSQL/connections/{connection_name}"

    db = settings.value(f"{base_key}/database")
    user = settings.value(f"{base_key}/username")
    password = settings.value(f"{base_key}/password") or ""
    host = settings.value(f"{base_key}/host")
    port = settings.value(f"{base_key}/port") or "5432"

    if feedback:
        feedback.pushInfo("[DEBUG] Fetched connection settings from QGIS:")
        feedback.pushInfo(f"  Host: {host}")
        feedback.pushInfo(f"  Database: {db}")
        feedback.pushInfo(f"  User: {user}")
        feedback.pushInfo(f"  Port: {port}")

    # URL-encode the password to avoid issues with special characters
    safe_password = urllib.parse.quote_plus(password)

    connection_url = f"postgresql://{user}:{safe_password}@{host}:{port}/{db}"
    
    if feedback:
        feedback.pushInfo(f"[DEBUG] SQLAlchemy connection URL: {connection_url}")

    engine = create_engine(connection_url)
    return engine



class VehiclePassengerFlowAlgorithm(QgsProcessingAlgorithm):
    def initAlgorithm(self, config):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """

        self.addParameter(
            QgsProcessingParameterFile(
                'GTFS_ZIP',
                'GTFS Zip File',
                behavior=QgsProcessingParameterFile.File,
                fileFilter='Zip files (*.zip)'
            )
        )

        self.addParameter(
            QgsProcessingParameterProviderConnection(
                'SDI_CONNECTION',
                'PostgreSQL SDI Connection for the needed project',
                provider='postgres'
            )
        )

        self.addParameter(
            QgsProcessingParameterFolderDestination(
                'OUTPUT_FOLDER',
                'Output Folder Path'
            )
        )


    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        gtfs_path = self.parameterAsFile(parameters, 'GTFS_ZIP', context)
        output_folder = self.parameterAsString(parameters, 'OUTPUT_FOLDER', context)
        connection_name = self.parameterAsString(parameters, 'SDI_CONNECTION', context)
        connection = connect_postgis(connection_name, feedback=feedback)

        estimator = FlowEstimator(gtfs_path, connection, output_folder)
        # estimator.run()
        estimator.run(feedback=feedback)  # we added feedback=feedback here and feedback above to know if connection ran successfully in full_script.py run()

        return {'OUTPUT': output_folder}

    def name(self):
        """
        Returns the algorithm name, used for identifying the algorithm. This
        string should be fixed for the algorithm, and must not be localised.
        The name should be unique within each provider. Names should contain
        lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return 'Vehicle and Passenger Flow Estimator'

    def displayName(self):
        """
        Returns the translated algorithm name, which should be used for any
        user-visible display of the algorithm name.
        """
        return self.tr(self.name())

    def group(self):
        """
        Returns the name of the group this algorithm belongs to. This string
        should be localised.
        """
        # return self.tr(self.groupId())
        return self.tr('02 GIS Tools')

    def groupId(self):
        """
        Returns the unique ID of the group this algorithm belongs to. This
        string should be fixed for the algorithm, and must not be localised.
        The group id should be unique within each provider. Group id should
        contain lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return 'gis_tools'
    
    def shortHelpString(self):
        return self.tr("This algorithm creates estimate vehicle and passenger flows from spatial database layers and GTFS data.")  # later revise this text here

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

    def createInstance(self):
        return VehiclePassengerFlowAlgorithm()
    
    def icon(self):
        return QIcon(_icon_path("icons", "GIS-icon.svg"))
    # Optional: some QGIS builds prefer this for SVG
    def svgIconPath(self):
        return _icon_path("icons", "GIS-icon.svg")
