"""
EMDS Analysis Tasks Plugin for QGIS.
Manages EMDS projects, assessments, analysis paths, tasks, and results.
"""

import importlib
import os
import platform

# Python packages the plugin cannot load without. These are NOT part of the
# stock QGIS install (pandas is imported at module top level across the plugin;
# pyarrow is required for engine data transfer), so a clean QGIS install must
# have them added. The install-deps scripts under scripts/ do this.
_REQUIRED_PACKAGES = ("pandas", "pyarrow")


def _install_script_hint() -> str:
    """Point the user at the right bootstrap script for their platform."""
    if os.name == "nt":
        return "scripts\\windows\\install-deps.ps1"
    system_name = platform.system()
    if system_name == "Darwin":
        return "scripts/macos/install-emds-runtime-deps.zsh"
    if system_name == "Linux":
        return "scripts/linux/install-emds-runtime-deps.sh"
    return "pip install into the QGIS Python environment"


def _missing_required_packages() -> list[str]:
    missing: list[str] = []
    for name in _REQUIRED_PACKAGES:
        try:
            importlib.import_module(name)
        except ImportError:
            missing.append(name)
    return missing


def _warn_missing_dependencies(missing: list[str]) -> None:
    """Show a friendly dialog instead of a raw ModuleNotFoundError traceback."""
    package_list = ", ".join(missing)
    message = (
        "EMDS Workbench cannot start because these Python packages are missing "
        "from the QGIS Python environment:\n\n"
        f"    {package_list}\n\n"
        "Run the dependency installer for your platform, then restart QGIS:\n\n"
        f"    {_install_script_hint()}\n\n"
        "The installer adds the missing packages to the Python that QGIS uses "
        "without changing any packages QGIS already bundles."
    )
    try:
        from qgis.PyQt.QtWidgets import QMessageBox

        QMessageBox.critical(None, "EMDS Workbench — missing dependencies", message)
    except Exception:
        # No GUI context (e.g. headless tests) — fall back to stderr.
        import sys

        print(message, file=sys.stderr)


def classFactory(iface):
    """Load EMDSPlugin class from emds_plugin.py.

    Dependencies are checked first. When packages are missing, QGIS gets a
    minimal bootstrap plugin whose only job is the in-app first-run setup
    dialog (pip install into QGIS's own Python, engine payload repair) — no
    terminal needed. The main plugin import is deferred until after the
    check because it pulls in pandas transitively.
    """
    missing = _missing_required_packages()
    if missing:
        try:
            from .first_run_setup import SetupBootstrapPlugin

            return SetupBootstrapPlugin(iface, missing)
        except Exception:
            # Headless / no-Qt context: keep the legacy failure mode of a
            # clear message plus ImportError instead of a broken bootstrap.
            _warn_missing_dependencies(missing)
            raise ImportError(
                "EMDS Workbench is missing required Python packages: "
                + ", ".join(missing)
            )

    from .emds_plugin import EMDSPlugin
    return EMDSPlugin(iface)
