"""Standalone launcher for Beaver processor.

Performs the full PyQGIS bootstrap (QgsApplication, prefix path, initQgis,
Processing framework, editor-widget registry) and then opens the main window.
Run via the QGIS Python launcher for your platform:

    Windows:  "<QGIS>\\bin\\python-qgis-ltr.bat" standalone.py
    macOS:    /Applications/QGIS.app/Contents/MacOS/bin/python3 standalone.py
    Linux:    python3 standalone.py        # with QGIS on PYTHONPATH

On any platform, exporting ``QGIS_PREFIX_PATH`` (as the launchers above do)
lets ``_find_qgis_prefix`` locate the install without guesswork.

Inside QGIS Desktop none of this runs — the plugin entry point (plugin.py)
uses the host application instead.
"""

import os
import sys
import logging

logger = logging.getLogger(__name__)

# This launcher runs as a plain script, but the plugin code is a package that
# uses relative imports. Put the directory that CONTAINS the ``beaver_processor``
# package on sys.path so ``import beaver_processor.plugin...`` resolves.
_PLUGIN_DIR = os.path.dirname(os.path.abspath(__file__))          # .../beaver_processor/plugin
_PKG_PARENT = os.path.dirname(os.path.dirname(_PLUGIN_DIR))       # dir containing beaver_processor/
if _PKG_PARENT not in sys.path:
    sys.path.insert(0, _PKG_PARENT)


def main() -> int:
    logging.basicConfig(
        level=logging.INFO,
        format="[%(levelname)s] %(message)s",
        stream=sys.stdout,
    )

    from qgis.core import QgsApplication
    from qgis.gui import QgsGui
    from PyQt5.QtGui import QPixmap
    from PyQt5.QtCore import Qt
    from PyQt5.QtWidgets import QSplashScreen

    # Construct a QgsApplication (not a plain QApplication) and call initQgis()
    # so QGIS's resource subsystem — SVG search paths, theme icons, the
    # symbol-layer-type registry, the default style DB — is fully loaded.
    app = QgsApplication([], True)

    # Importing the GUI module is safe pre-initQgis (definitions only) and
    # gives us the prefix resolver and asset paths.
    from beaver_processor.plugin import gui_generator as gg

    _qgis_prefix = gg._find_qgis_prefix()
    logger.info(f"[QGIS-INIT] QGIS_PREFIX_PATH env  = {os.environ.get('QGIS_PREFIX_PATH', '<unset>')}")
    logger.info(f"[QGIS-INIT] resolved prefix path  = {_qgis_prefix}")
    logger.info(f"[QGIS-INIT] prefix exists on disk = {os.path.isdir(_qgis_prefix)}")
    QgsApplication.setPrefixPath(_qgis_prefix, True)
    QgsApplication.initQgis()
    logger.info("[QGIS-INIT] initQgis() returned")

    # Initialise the QGIS processing framework so processing.run("native:…")
    # is available. In a standalone PyQGIS app the QGIS plugins directory is
    # not on sys.path by default, so add it explicitly before importing.
    try:
        _pp = QgsApplication.prefixPath()
        for _pc in (
            os.path.join(_pp, "python", "plugins"),
            os.path.join(os.path.dirname(_pp), "qgis", "python", "plugins"),
        ):
            if os.path.isdir(_pc) and _pc not in sys.path:
                sys.path.insert(0, _pc)
                logger.info(f"[QGIS-INIT] added plugins path to sys.path: {_pc}")

        from qgis.analysis import QgsNativeAlgorithms
        from processing.core.Processing import Processing
        Processing.initialize()
        QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
        logger.info("[QGIS-INIT] processing framework initialised")
    except Exception as _proc_err:
        logger.warning(f"[QGIS-INIT] processing framework init failed: {_proc_err}")

    # The symbol editor widget calls into the editor-widget registry during its
    # setupUi(); without registered factories that lookup segfaults. QGIS
    # Desktop calls this; any standalone PyQGIS app using symbology must too.
    try:
        QgsGui.editorWidgetRegistry().initEditors()
        logger.info("[QGIS-INIT] QgsGui.editorWidgetRegistry().initEditors() ok")
    except Exception as _gui_err:
        logger.warning(f"[QGIS-INIT] editorWidgetRegistry init failed: {_gui_err}")

    # No theme override — the app uses Qt's default (light) style. Inside QGIS
    # (plugin mode) it simply inherits the host's theme.

    # Splash + main window
    splash_pix = QPixmap(os.path.join(gg.ICONS_DIR, "logo.png"))
    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
    splash.setMask(splash_pix.mask())
    splash.show()

    window = gg.GUI_class()
    window.showMaximized()
    splash.finish(window)

    # Run the Qt event loop, then tear QGIS down cleanly before exit.
    exit_code = app.exec_()
    try:
        QgsApplication.exitQgis()
    except Exception:
        pass
    return exit_code


if __name__ == "__main__":
    raise SystemExit(main())
