# -*- coding: utf-8 -*-
from qgis.core import QgsProcessingAlgorithm, QgsProcessingParameterBoolean
from qgis.PyQt.QtCore import QCoreApplication
import webbrowser
from .license_guard import SupabaseGuard

class LoginDEMNAS(QgsProcessingAlgorithm):
    """
    Algorithm to open login page and guide user
    """
    
    def initAlgorithm(self, config=None):
        guide_text = "Silahkan klik [Run] untuk membuka halaman login dan mendapatkan Panduan."
        from qgis.core import QgsProcessingParameterString
        self.addParameter(QgsProcessingParameterString(
            'INFO', 'INFO', defaultValue=guide_text, optional=True
        ))

    def processAlgorithm(self, parameters, context, feedback):
        feedback.pushInfo("Checking license...")
        is_valid, msg, info = SupabaseGuard.check_license("BIG Downloader QGIS", "free")
        
        feedback.pushInfo(msg)
        
        if not is_valid:
            raise Exception("License check failed. See log for details.")

        feedback.pushInfo("Opening Login Page...")
        webbrowser.open("https://tanahair.indonesia.go.id/portal-web/login")
        
        feedback.pushInfo("\n--- PANDUAN MENGAMBIL TOKEN DEMNAS ---")
        feedback.pushInfo("1. Halaman login INA-Geoportal akan terbuka.")
        feedback.pushInfo("2. Tekan [F12] pada browser untuk membuka Developer Tools.")
        feedback.pushInfo("3. Masuk ke tab [Network].")
        feedback.pushInfo("4. Login dengan akun Anda.")
        feedback.pushInfo("5. Filter 'signin' pada tab Network.")
        feedback.pushInfo("6. Klik request 'signin', buka tab Response/Preview.")
        feedback.pushInfo("7. Copy nilai 'accessToken'.")
        feedback.pushInfo("8. Gunakan token tersebut di Tool #2, #3, dan #4.\n")
        
        return {}

    def name(self):
        return 'login_demnas'

    def displayName(self):
        return '1. Login INA-Geoportal'

    def group(self):
        return 'BIG Downloader Tools'

    def groupId(self):
        return 'big_downloader_v2'

    def icon(self):
        import os
        from qgis.PyQt.QtGui import QIcon
        return QIcon(os.path.join(os.path.dirname(__file__), '..', 'images', 'icon_login.png'))

    def createInstance(self):
        return LoginDEMNAS()
