# -*- coding: utf-8 -*-
"""
Open Geodata Browser
QGIS Plugin for browsing and downloading satellite imagery from STAC APIs
"""

import os
import sys
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QToolBar, QMessageBox
from qgis.core import QgsMessageLog, Qgis


class GeodataBrowser:
    """QGIS Plugin Implementation for Open Geodata Browser"""

    def __init__(self, iface):
        """Constructor.

        Args:
            iface (QgsInterface): An interface instance that will be passed to this class
                which provides the hook by which you can manipulate the QGIS
                application at run time.
        """
        # Save reference to the QGIS interface
        self.iface = iface
        
        # Initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        
        # Initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'GeodataBrowser_{}.qm'.format(locale))
        
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)
        
        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'MAS Raster Processing')  # Same menu as XYZ tool
        self.toolbar = None
        
        # Dialog
        self.dlg = None
        self.action = None
        
        # Dependencies check flag
        self.dependencies_checked = False
        self.dependencies_ok = False

    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        Args:
            message (str): String for translation.

        Returns:
            str: Translated string.
        """
        return QCoreApplication.translate('GeodataBrowser', message)

    def add_action(self,
                   icon_path,
                   text,
                   callback,
                   enabled_flag=True,
                   add_to_menu=True,
                   add_to_toolbar=True,
                   status_tip=None,
                   whats_this=None,
                   parent=None):
        """Add a toolbar icon to the toolbar.

        Args:
            icon_path (str): Path to the icon for this action
            text (str): Text that should be shown in menu items
            callback (function): Function to be called when action is triggered
            enabled_flag (bool): Whether action should be enabled by default
            add_to_menu (bool): Whether to add action to the plugin menu
            add_to_toolbar (bool): Whether to add action to toolbar
            status_tip (str): Optional text to show in status bar
            whats_this (str): Optional text for help
            parent: Parent widget for the new action

        Returns:
            QAction: The action that was created
        """
        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar and self.toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToRasterMenu(
                self.menu,
                action)

        self.actions.append(action)
        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        icon_path = os.path.join(self.plugin_dir, 'resources', 'icon.png')
        
        # Check if the toolbar already exists, if not create it
        self.toolbar = self.iface.mainWindow().findChild(QToolBar, 'MASRasterProcessingToolbar')
        if self.toolbar is None:
            self.toolbar = self.iface.addToolBar(u'MAS Raster Processing')
            self.toolbar.setObjectName('MASRasterProcessingToolbar')
        
        # Create the action
        self.action = self.add_action(
            icon_path,
            text=self.tr(u'Open Geodata Browser'),
            callback=self.run,
            status_tip=self.tr('Browse and download satellite imagery from STAC APIs'),
            whats_this=self.tr('Access satellite imagery from multiple STAC providers including AWS, Planetary Computer, and custom endpoints'),
            parent=self.iface.mainWindow())

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginRasterMenu(
                self.tr(u'MAS Raster Processing'),
                action)
            if self.toolbar:
                self.toolbar.removeAction(action)

    def run(self):
        """Run method that performs all the real work"""
        # Check dependencies only once
        if not self.dependencies_checked:
            self.log_message('Checking dependencies...', Qgis.Info)
            
            if not self.check_dependencies():
                self.log_message('Dependencies check failed', Qgis.Warning)
                return
            
            self.dependencies_checked = True
            self.dependencies_ok = True
        
        # Create the dialog if it doesn't exist
        if self.dlg is None:
            try:
                from .dialogs.geodata_browser_dialog import GeodataBrowserDialog
                self.dlg = GeodataBrowserDialog(self.iface)
            except ImportError as e:
                self.log_message(f'Failed to import dialog: {str(e)}', Qgis.Critical)
                QMessageBox.critical(
                    self.iface.mainWindow(),
                    'Import Error',
                    f'Failed to load plugin dialog:\n{str(e)}'
                )
                return
        
        # Show the dialog
        self.dlg.show()
        self.dlg.raise_()
        self.dlg.activateWindow()

    def check_dependencies(self):
        """Check if all required Python packages are installed"""
        missing = self.get_missing_dependencies()
        
        if not missing:
            self.log_message('All dependencies are installed', Qgis.Success)
            return True
        
        # Show installation dialog
        return self.show_install_dialog(missing)

    def get_missing_dependencies(self):
        """Get list of missing required packages"""
        required_packages = {
            'open_geodata_api': 'open-geodata-api',
            'pystac_client': 'pystac-client',
            'requests': 'requests'
        }
        
        missing = []
        for import_name, package_name in required_packages.items():
            try:
                __import__(import_name)
                self.log_message(f'✓ {package_name} found', Qgis.Info)
            except ImportError:
                missing.append(package_name)
                self.log_message(f'✗ {package_name} missing', Qgis.Warning)
        
        return missing

    def show_install_dialog(self, missing_packages):
        """Show dialog for installing missing dependencies"""
        msg = QMessageBox(self.iface.mainWindow())
        msg.setIcon(QMessageBox.Warning)
        msg.setWindowTitle('Missing Dependencies')
        msg.setText('Missing Required Packages')
        
        install_text = """The following Python packages are required but not installed:

""" + '\n'.join(f'• {pkg}' for pkg in missing_packages) + """

INSTALLATION INSTRUCTIONS:

Method 1: OSGeo4W Shell (Recommended for Windows)
1. Close QGIS
2. Open OSGeo4W Shell as Administrator
3. Run: python -m pip install """ + " ".join(missing_packages) + """
4. Restart QGIS

Method 2: QGIS Python Console
1. Open Python Console (Plugins → Python Console)
2. Run:
    from pip._internal.main import main as pip_main
    pip_main(['install', '--user', '--upgrade', 'open-geodata-api'])
3. Restart QGIS

Method 3: Command Line (Any System)
pip install --user """ + " ".join(missing_packages)
        
        msg.setInformativeText(install_text)
        msg.setTextFormat(Qt.PlainText)
        msg.setDetailedText('For more help, visit: https://github.com/Mirjan-Ali-Sha/open-geodata-browser/wiki')
        
        # Add buttons
        try_now = msg.addButton('Try Install Now', QMessageBox.ActionRole)
        cancel_btn = msg.addButton('Cancel', QMessageBox.RejectRole)
        msg.setDefaultButton(cancel_btn)
        
        result = msg.exec_()
        clicked = msg.clickedButton()
        
        if clicked == try_now:
            return self.install_dependencies_auto(missing_packages)
        
        return False

    def install_dependencies_auto(self, packages):
        """Attempt to auto-install dependencies"""
        try:
            from .dependency_installer import DependencyInstaller
            
            installer = DependencyInstaller(self.iface)
            return installer.install_dependencies(packages)
            
        except ImportError:
            self.log_message('Dependency installer not found', Qgis.Warning)
            return False
        except Exception as e:
            self.log_message(f'Auto-install failed: {str(e)}', Qgis.Critical)
            return False

    def log_message(self, message, level=Qgis.Info):
        """Log message to QGIS message log"""
        QgsMessageLog.logMessage(message, 'Open Geodata Browser', level)
