"""
Bridge import helpers for the QGIS plugin.

This resolves the engine bridge from either the source repo layout or a
deployed QGIS plugins directory without requiring the caller to manage
``sys.path`` directly.
"""

from __future__ import annotations

import importlib
import sys
from pathlib import Path


def _candidate_bridge_dirs() -> list[Path]:
    plugin_dir = Path(__file__).resolve().parent
    repo_root = plugin_dir.parent
    plugins_dir = plugin_dir.parent.parent

    candidates = [
        # Canonical location: python-bridge is vendored INSIDE the plugin folder,
        # so it ships with every copy/ZIP of the plugin regardless of staging.
        plugin_dir / "python-bridge",
        # Fallbacks for dev/legacy layouts where it sat beside the plugin.
        repo_root / "python-bridge",
        plugins_dir / "python-bridge",
    ]

    unique_candidates: list[Path] = []
    for candidate in candidates:
        if candidate not in unique_candidates:
            unique_candidates.append(candidate)
    return unique_candidates


def _ensure_bridge_path() -> None:
    for candidate in _candidate_bridge_dirs():
        if (candidate / "engine_bridge.py").exists():
            candidate_str = str(candidate)
            if candidate_str not in sys.path:
                sys.path.insert(0, candidate_str)
            return

    searched = "\n".join(str(path) for path in _candidate_bridge_dirs())
    raise ModuleNotFoundError(
        "Could not locate engine_bridge.py. Searched:\n"
        f"{searched}"
    )


_ensure_bridge_path()
_engine_bridge = importlib.import_module("engine_bridge")
_portfolio_engine = importlib.import_module("portfolio_engine")

NetWeaverBridge = _engine_bridge.NetWeaverBridge
CDPBridge = _engine_bridge.CDPBridge
PortfolioBridge = _portfolio_engine.PortfolioBridge

# Re-export portfolio dataclasses / constants for callers that construct
# parameters directly (the wizard packs a plain dict, so most UI code
# doesn't need these, but they're handy for tests and for typed callers).
PortfolioParameters = _portfolio_engine.PortfolioParameters
PortfolioReport = _portfolio_engine.PortfolioReport
FundingPercent = _portfolio_engine.FundingPercent
STRATEGY_COST = _portfolio_engine.STRATEGY_COST
STRATEGY_BENEFIT = _portfolio_engine.STRATEGY_BENEFIT
STRATEGY_COSTBENEFIT = _portfolio_engine.STRATEGY_COSTBENEFIT
STRATEGY_PRIORITIZATION = _portfolio_engine.STRATEGY_PRIORITIZATION
STRATEGY_PRIORITIZATION_COST = _portfolio_engine.STRATEGY_PRIORITIZATION_COST
DIRECTION_UP = _portfolio_engine.DIRECTION_UP
DIRECTION_DOWN = _portfolio_engine.DIRECTION_DOWN
