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

"""
/***************************************************************************
 GIS2GTFS
                                 A QGIS plugin
 This plugin turns GIS files to GTFS feed
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-07-02
        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-02'
__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 qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsProcessingParameterProviderConnection, # added
                       QgsProcessingParameterFolderDestination,
                       QgsProcessingParameterString,
                       QgsProcessingParameterBoolean,
                       QgsProcessingParameterEnum,
                       QgsProcessingParameterFile,
                       QgsProcessingParameterDefinition)  
import os
from ..tfc_tools_common import ensure_deps
from .build import run_gtfs_pipeline

# for icon
from qgis.PyQt.QtGui import QIcon

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 GIS2GTFSAlgorithm(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.

    SDI_SOURCE = 'SDI_SOURCE'
    SDI_GPKG = 'SDI_GPKG'
    CONN_NAME = 'CONN_NAME'
    DATA_RAW_DIR = 'DATA_RAW_DIR'
    DATA_DIR = 'DATA_DIR'
    FEED_VERSION = 'FEED_VERSION'
    START_DATE = 'START_DATE'
    END_DATE = 'END_DATE'
    SERVICE_ID = 'SERVICE_ID'
    CONTINUOUS = 'CONTINUOUS'

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

        # 0. SDI source selector (PostGIS vs GeoPackage)
        # Use a widget wrapper so the unused input below is visually disabled (standard QGIS UX).
        src_param = QgsProcessingParameterEnum(
            self.SDI_SOURCE,
            self.tr('SDI data source'),
            options=[
                self.tr('PostGIS (QGIS connection)'),
                self.tr('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': [self.CONN_NAME],   # PostGIS
                        '1': [self.SDI_GPKG],    # GeoPackage
                    }
                }
            }
        )
        self.addParameter(src_param)

        # 1. SDI DB connection (PostGIS)
        # NOTE: kept optional so the dialog can be either/or with GeoPackage.
        # We enforce the requirement via checkParameterValues depending on SDI_SOURCE.
        conn_param = QgsProcessingParameterProviderConnection(
            self.CONN_NAME,
            self.tr('SDI PostGIS connection (required when SDI data source = PostGIS)'),
            provider='postgres'
        )
        conn_param.setFlags(conn_param.flags() | QgsProcessingParameterDefinition.FlagOptional)
        self.addParameter(conn_param)

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

        # 2. OUTPUT FOLDER 1 (FOR RAW DATA FROM SDI)
        self.addParameter(
            QgsProcessingParameterFolderDestination(
                self.DATA_RAW_DIR,
                self.tr('Output folder for intermediate raw data')
            )
        )

        # 3. OUTPUT FOLDER 2 (FOR GTFS OUTPUT)
        self.addParameter(
            QgsProcessingParameterFolderDestination(
                self.DATA_DIR,
                self.tr('Output folder for GTFS data')
            )
        )

        # 4. OTHER NEEDED INPUT 
        self.addParameter(
            QgsProcessingParameterString(
                self.FEED_VERSION,
                # self.tr('Feed name (e.g., cairo)')
                self.tr('Feed version')
            )
        )

        self.addParameter(
            QgsProcessingParameterString(
                self.START_DATE,
                self.tr('Start date (YYYYMMDD)')
            )
        )

        self.addParameter(
            QgsProcessingParameterString(
                self.END_DATE,
                self.tr('End date (YYYYMMDD)')
            )
        )

        # Legacy fallback only. calendar.py now derives service_ids
        # dynamically from the mon..sun columns in transit_intervals (e.g.
        # svc_daily, svc_weekday, svc_weekend). This field is used ONLY
        # when the input GeoPackage was produced by an older SDI exporter
        # that didn't carry day-of-week flags -- in that case we fall
        # back to a single service row named "<this value>_Daily" that
        # runs every day. For modern exports the field is ignored.
        svc_param = QgsProcessingParameterString(
            self.SERVICE_ID,
            self.tr('Legacy service_id prefix (used only when intervals '
                    'have no mon..sun columns)'),
            defaultValue='Ground',
            optional=True,
        )
        svc_param.setFlags(
            svc_param.flags() | QgsProcessingParameterDefinition.FlagAdvanced
        )
        self.addParameter(svc_param)

        self.addParameter(
            QgsProcessingParameterBoolean(
                self.CONTINUOUS,
                self.tr('Use continuous drop-off/pick-up'),
                defaultValue=True
            )
        )


    def checkParameterValues(self, parameters, context):
        """Make the UI effectively either/or: exactly one input is required depending on SDI_SOURCE."""
        source_mode = self.parameterAsEnum(parameters, self.SDI_SOURCE, context)
        if source_mode == 0:
            # Install PostGIS-mode deps only when needed
            ensure_deps()
        source_mode = self.parameterAsEnum(parameters, self.SDI_SOURCE, context)
        if source_mode == 0:
            # Install PostGIS-mode deps only when needed
            ensure_deps()
        conn_name = self.parameterAsString(parameters, self.CONN_NAME, context)
        gpkg_path = self.parameterAsFile(parameters, self.SDI_GPKG, context)
        gpkg_path = self.parameterAsFile(parameters, self.SDI_GPKG, context)

        if source_mode == 0:
            # PostGIS
            if not conn_name:
                return (False, self.tr('Please choose an SDI PostGIS connection (required when SDI data source = PostGIS).'))
        else:
            # GeoPackage
            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.
        """
        source_mode = self.parameterAsEnum(parameters, self.SDI_SOURCE, context)
        if source_mode == 0:
            # Install PostGIS-mode deps only when needed
            ensure_deps()
        conn_name = self.parameterAsString(parameters, self.CONN_NAME, context)
        gpkg_path = self.parameterAsFile(parameters, self.SDI_GPKG, context)
        data_raw_dir = self.parameterAsString(parameters, self.DATA_RAW_DIR, context)
        data_dir = self.parameterAsString(parameters, self.DATA_DIR, context)
        feed_version = self.parameterAsString(parameters, self.FEED_VERSION, context)
        start_date = int(self.parameterAsString(parameters, self.START_DATE, context))
        end_date = int(self.parameterAsString(parameters, self.END_DATE, context))
        service_id = self.parameterAsString(parameters, self.SERVICE_ID, context)
        # Optional + advanced field; supply a default if the user left it blank.
        if not service_id or not service_id.strip():
            service_id = "Ground"
        continuous = self.parameterAsBool(parameters, self.CONTINUOUS, context)

        # Call the GTFS build pipeline
        run_gtfs_pipeline(
            sdi_mode='postgres' if source_mode == 0 else 'gpkg',
            conn_name=conn_name if source_mode == 0 else None,
            gpkg_path=gpkg_path if source_mode == 1 else None,
            data_raw_dir=data_raw_dir,
            data_dir=data_dir,
            feed_start_date=start_date,
            feed_end_date=end_date,
            feed_version=feed_version,
            feed_lang="en",
            start_date=start_date,
            end_date=end_date,
            service_id=service_id,
            continuous_dropoff_pickup=continuous,
            dwell_time_sec=15
        )

        return {}

    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 'GIS2GTFS'

    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("""
    <b>Purpose of the Plugin</b>
    The plugin generates a General Transit Feed Specification (GTFS) dataset from transport data stored in a standardized TfC schema.
    The input can be either a PostgreSQL SDI database or a GeoPackage following the same structure.<br>

    <b>How to Use the Plugin</b>
    The plugin requires the following inputs:
    1. SDI or GeoPackage dataset following TfC’s standard schema (e.g. output from RL2SDI or RL2GPKG)
    2. Feed version (e.g. 1.0)
    3. Start date (YYYYMMDD)
    4. End date (YYYYMMDD)
    5. Use continuous drop-off/pick-up (enabled by default)
    6. Output folder 1 – temporary files (recommended: empty folder)
    7. Output folder 2 – final GTFS files<br>
                       
    <b>Advanced Parameters</b>
    • Legacy service_id prefix — only used when the input GeoPackage was produced by an older exporter without mon..sun day flags. Modern exports derive services dynamically from interval day-of-week flags (e.g. svc_daily, svc_weekday, svc_weekend) and ignore this field.<br>

    <b>Outputs</b>
    • Intermediate files in Folder 1
    • GTFS feed (.txt files) in Folder 2<br>

    <b>Documentation</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 GIS2GTFSAlgorithm()
    
    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")
