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

"""
/***************************************************************************
 RL2SDI
                                 A QGIS plugin
 This plugin migrates RouteLab data to SDI schema
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-06-29
        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-06-29'
__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 ..tfc_tools_common import ensure_deps
from ..tfc_tools_common.stop_params import (
    add_stop_params_to_algorithm,
    read_stop_params_from_algorithm,
)

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsProcessingParameterString,
                       QgsProcessingParameterNumber,
                       QgsProcessingParameterProviderConnection,
                       QgsApplication,
                       QgsProviderRegistry,
                       QgsDataSourceUri)
from .script4plugin import run_migration
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)

class RL2SDIAlgorithm(QgsProcessingAlgorithm):
    """
    This is an example algorithm that takes a vector layer and
    creates a new identical one.

    It is meant to be used as an example of how to create your own
    algorithms and explain methods and variables used to do it. An
    algorithm like this will be available in all elements, and there
    is not need for additional work.

    All Processing algorithms should extend the QgsProcessingAlgorithm
    class.
    """

    # Constants used to refer to parameters and outputs. They will be
    # used when calling the algorithm from another algorithm, or when
    # calling from the QGIS console.

    OBSERVER_CONN = 'observer_connection'
    SDI_CONN = 'sdi_connection'
    PROJECT_ID = 'project_id'
    FALLBACK_HEADWAY = 'fallback_headway'

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

        # 1. Observer DB connection (provider: PostgreSQL)
        self.addParameter(
            QgsProcessingParameterProviderConnection(
                self.OBSERVER_CONN,
                "RouteLab's Observer DB connection",
                provider='postgres'
            )
        )


        # 2. SDI DB connection (target DB)
        self.addParameter(
            QgsProcessingParameterProviderConnection(
                self.SDI_CONN,
                "Target SDI DB connection",
                provider='postgres'
            )
        )

        # 3. Project ID
        self.addParameter(
            QgsProcessingParameterString(
                self.PROJECT_ID,
                "RouteLab Project ID"
            )
        )

        # 4. Optional fallback headway (seconds) for any remaining null values
        p = QgsProcessingParameterNumber(
            self.FALLBACK_HEADWAY,
            "Headway (seconds) for empty values (optional)",
            type=QgsProcessingParameterNumber.Integer,
            defaultValue=None,
            optional=True,
        )
        # Keep it advanced to avoid cluttering the main UI
        try:
            p.setFlags(p.flags() | QgsProcessingParameterNumber.FlagAdvanced)
        except Exception:
            pass
        self.addParameter(p)

        # Stop-extraction parameters (all advanced, all with sensible defaults).
        # Shared with the "Refresh SDI Derived Layers" tool so that editing
        # stops/trips in GIS and refreshing reproduces the same pipeline.
        add_stop_params_to_algorithm(self)

    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """

        # Install PostGIS-mode Python deps only when running RL2SDI
        ensure_deps()

        # Retrieve the feature source and sink. The 'dest_id' variable is used
        # to uniquely identify the feature sink, and must be included in the
        # dictionary returned by the processAlgorithm function.

        # Get connection name from parameters
        observer_conn_name = self.parameterAsConnectionName(parameters, self.OBSERVER_CONN, context)
        sdi_conn_name = self.parameterAsConnectionName(parameters, self.SDI_CONN, context)

        project_id = self.parameterAsString(parameters, self.PROJECT_ID, context)
        fallback_headway = self.parameterAsInt(parameters, self.FALLBACK_HEADWAY, context)
        # QGIS returns 0 when unset for some builds; treat <=0 as unset
        if fallback_headway is not None and fallback_headway <= 0:
            fallback_headway = None

        # Read stop-extraction parameters (defaults preserved if user didn't touch them).
        stop_params = read_stop_params_from_algorithm(self, parameters, context)

        feedback.pushInfo(f"Using Observer connection: {observer_conn_name}")
        feedback.pushInfo(f"Using SDI connection: {sdi_conn_name}")
        feedback.pushInfo(f"RouteLab Project ID: {project_id}")
        
        # Access connection URI strings via provider metadata
        postgres_metadata = QgsProviderRegistry.instance().providerMetadata('postgres') #this variable stores the object 'postgres' from the class providerMetadata

        observer_conn = postgres_metadata.findConnection(observer_conn_name)
        sdi_conn = postgres_metadata.findConnection(sdi_conn_name)
        
        observer_uri_str = observer_conn.uri() #returns string of DB connection
        sdi_uri_str = sdi_conn.uri()

        # Parse URI string into connection details
        observer_uri = QgsDataSourceUri(observer_uri_str)
        sdi_uri = QgsDataSourceUri(sdi_uri_str)

        observer_db_params = {
            "dbname": observer_uri.database(),
            "user": observer_uri.username(),
            "password": observer_uri.password(),
            "host": observer_uri.host(),
            "port": str(observer_uri.port())
        }

        sdi_db_params = {
            "dbname": sdi_uri.database(),
            "user": sdi_uri.username(),
            "password": sdi_uri.password(),
            "host": sdi_uri.host(),
            "port": str(sdi_uri.port())
        }

        # Call the core logic function run_migration(), with the cleaned-up inputs
        run_migration(observer_db_params, sdi_db_params, project_id, feedback, fallback_headway, stop_params=stop_params)
        return {'RESULT': 'Migration completed successfully'}


    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 'RouteLab to SDI Migration'

    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('01 RouteLab 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 'rl_tools'
    
    def shortHelpString(self):
        return self.tr("""
    <b>Purpose of the Plugin</b>
    The RL2SDI Migration Plugin automates the migration of field survey data from Transport for Cairo’s (TfC) RouteLab database into a Spatial Data Infrastructure (SDI). 
    It creates standardized <code>raw</code> and <code>transit</code> schemas in a PostGIS database, enabling further analysis or use with the other TfC Tools plugins (GIS2GTFS and Vehicle and Passenger Flow).<br>

    <b>How to Use the Plugin</b>
    The plugin requires the following inputs:
    1. RouteLab database connection (credentials provided by TfC)
    2. PostGIS SDI connection where the data will be migrated
    3. Enter the Project ID — the unique identifier for your RouteLab project<br>

    <b>Advanced Parameters</b>
    • Headway fallback value (optional, for trips with missing headway data).
    • Stop-extraction tuning — DBSCAN clustering, snap/terminal/spacing thresholds (meters), and per-vehicle vs. pooled OD travel-time speeds. Defaults preserve the historical pipeline.<br>

    <b>Outputs</b>
    • <code>raw</code> schema: cleaned RouteLab data.
    • <code>transit</code> schema: processed, analysis-ready datasets.<br>

    <b>Documenatation</b>
    For more information, refer to the User Guide.
    <a href="https://github.com/transportforcairo/tfc_tools/blob/main/tfc_tools_user_guide.pdf">TfC Tools User Guide</a>
    """)


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

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