# -*- 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 ..tfc_tools_common import ensure_paths, ensure_deps
ensure_paths()
from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsProcessingParameterFile,
                       QgsProcessingParameterNumber,
                       QgsProcessingParameterEnum,
                       QgsProcessingParameterProviderConnection,
                       QgsProcessingParameterString,
                       QgsProcessingParameterFolderDestination,
                       QgsProcessingParameterDefinition)
from .full_script import FlowEstimator


# 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 VehiclePassengerFlowAlgorithm(QgsProcessingAlgorithm):
    def initAlgorithm(self, config):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """

        # SDI source selector (with visual enable/disable for mutually exclusive inputs)
        src_param = QgsProcessingParameterEnum(
            'SDI_SOURCE',
            'SDI data source',
            options=[
                'PostGIS (QGIS connection)',
                'GeoPackage (RouteLab SDI export)'
            ],
            defaultValue=0
        )
        src_param.setMetadata(
            {
                'widget_wrapper': {
                    'class': 'tfc_tools.tfc_tools_common.sdi_source_toggle_wrapper.SDISourceToggleWidgetWrapper',
                    'enable_map': {
                        '0': ['SDI_CONNECTION'],
                        '1': ['SDI_GPKG'],
                    }
                }
            }
        )
        self.addParameter(src_param)

        self.addParameter(
            QgsProcessingParameterProviderConnection(
                'SDI_CONNECTION',
                'SDI PostGIS connection (required when SDI data source = PostGIS)',
                provider='postgres'
            )
        )

        # Mark optional to allow either/or with GeoPackage; enforced in checkParameterValues.
        self.parameterDefinition('SDI_CONNECTION').setFlags(
            self.parameterDefinition('SDI_CONNECTION').flags() | QgsProcessingParameterDefinition.FlagOptional
        )

        self.addParameter(
            QgsProcessingParameterFile(
                'SDI_GPKG',
                'SDI GeoPackage (required when SDI data source = GeoPackage)',
                behavior=QgsProcessingParameterFile.File,
                fileFilter='GeoPackage (*.gpkg)',
                optional=True
            )
        )

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

        # Advanced tuning parameters (expose FlowEstimator.analysis_config)
        p = QgsProcessingParameterNumber(
            'TRIP_SEGMENTIZATION_THRESHOLD_M',
            'Trip segments: segmentization threshold (meters)',
            type=QgsProcessingParameterNumber.Integer,
            defaultValue=300,
            minValue=1,
        )
        p.setFlags(p.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
        self.addParameter(p)


    def checkParameterValues(self, parameters, context):
        """Enforce either/or input based on SDI_SOURCE."""
        source_mode = self.parameterAsEnum(parameters, 'SDI_SOURCE', context)
        connection_name = self.parameterAsString(parameters, 'SDI_CONNECTION', context)
        gpkg_path = self.parameterAsFile(parameters, 'SDI_GPKG', context)


        if source_mode == 0:
            if not connection_name:
                return (False, self.tr('Please choose an SDI PostGIS connection (required when SDI data source = PostGIS).'))
        else:
            if not gpkg_path:
                return (False, self.tr('Please select an SDI GeoPackage file (required when SDI data source = GeoPackage).'))
            import os
            if not os.path.exists(gpkg_path):
                return (False, self.tr('The selected GeoPackage path does not exist.'))
            if not gpkg_path.lower().endswith('.gpkg'):
                return (False, self.tr('The selected file is not a .gpkg GeoPackage.'))

        return super().checkParameterValues(parameters, context)


    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        output_folder = self.parameterAsString(parameters, 'OUTPUT_FOLDER', context)
        source_mode = self.parameterAsEnum(parameters, 'SDI_SOURCE', context)
        connection_name = self.parameterAsString(parameters, 'SDI_CONNECTION', context)
        gpkg_path = self.parameterAsFile(parameters, 'SDI_GPKG', context)

        analysis_config = {
            "trip_segments_segmentization_threshold_meters": int(self.parameterAsInt(parameters, 'TRIP_SEGMENTIZATION_THRESHOLD_M', context))
        }

        connection = None
        if source_mode == 0:
            # Install PostGIS-mode Python deps only when needed
            ensure_deps()
            from ..tfc_tools_common.sdi_io import postgres_engine_from_qgis_connection
            connection = postgres_engine_from_qgis_connection(connection_name)

        estimator = FlowEstimator(
            connection=connection,
            output_folder=output_folder,
            sdi_mode='postgres' if source_mode == 0 else 'gpkg',
            gpkg_path=gpkg_path if source_mode == 1 else None,
            analysis_config=analysis_config,
        )
        estimator.run(feedback=feedback)

        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('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(r"""
            <b>Purpose of the Plugin</b>
            This tool estimates vehicle and passenger flows across transport segments using TfC standardized datasets.
            It uses SDI or GeoPackage inputs derived from RouteLab data and processed schemas.<br>
                       
            <b>How to use the Plugin</b>
            The plugin requires the following inputs:
            1. SDI data source: Choose one of:
            • PostGIS (QGIS connection): select an SDI PostGIS connection with the RL2SDI SDI schema
            • GeoPackage (RouteLab SDI export): select a GeoPackage matching the TfC “RouteLab SDI GeoPackage Schema Specification”
            2. Output Folder Path: Destination folder for flow outputs<br>
        
            <b>Advanced Parameters</b>
            • Trip segments: segmentization threshold (meters) — (default: 300) Controls how finely trip geometries are split into segments prior to matching. Lower values create more (shorter) segments; higher values create fewer (longer) segments.<br>

            <b>Required SDI tables/layers</b>
            The tool reads:
            • <code>transit.intervals</code> (or <code>transit_intervals</code> in GeoPackage) – only rows with <code>active = TRUE/1</code> are used
            • <code>raw.onboard_instances</code>
            • <code>raw.stops</code> 
            (or <code>raw_onboard_instances</code>, <code>raw_stops</code>). 
            <code>raw.stops</code> must include <code>created_at</code>

            <b>Outputs</b>
            • <code>vehicle_passenger_flow.gpkg</code>: vehicle and passenger flow layers.<br>

            <b>Documentation</b>
            For workflow details and SDI schema assumptions, refer to the TfC Tools User Guide and the RouteLab SDI GeoPackage schema document.
            <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 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")
