"""Detection system with dynamic state providers.

Simple, forward-thinking detection that allows detectors to:
1. Share expensive operations through lazy caching
2. Build on previous detections
3. Provide state for subsequent detectors
"""

from typing import List
from ..core.environment import Environment
from ..models import Context
from .state import DetectionState
from .tmux import detect_tmux, get_tmux_hint
from .micro import detect_micro, get_micro_hint
from .python import detect_python, get_python_hint
from .fly import detect_fly, get_fly_hint
from .shell import detect_shell


def get_shell_hint(mode: str = "reference") -> str | None:
    """Get activation hint for shell detector."""
    if mode == "reference":
        return "At shell prompt (fish/bash/zsh)"
    return None


ALL_DETECTORS = [
    detect_tmux,
    detect_shell,
    detect_micro,
    detect_python,
    detect_fly,
]

DETECTOR_HINTS = {
    detect_tmux: get_tmux_hint,
    detect_shell: get_shell_hint,
    detect_micro: get_micro_hint,
    detect_python: get_python_hint,
    detect_fly: get_fly_hint,
}


def get_activation_hints(mode: str = "reference") -> List[str]:
    """Get activation hints for all detectors in a given mode.

    Args:
        mode: Display mode (reference or code)

    Returns:
        List of activation hints
    """
    hints = []
    for detector in ALL_DETECTORS:
        hint_func = DETECTOR_HINTS.get(detector)
        if hint_func:
            hint = hint_func(mode)
            if hint:
                hints.append(f"  • {hint}")
    return hints


def detect_contexts(env: Environment) -> List[Context]:
    """Run all detectors with shared state.

    Args:
        env: Environment data from system

    Returns:
        List of detected contexts, sorted by priority
    """
    state = DetectionState(env)
    contexts = []

    for detector in ALL_DETECTORS:
        result = detector(state)

        if result:
            if isinstance(result, list):
                contexts.extend(result)
                for ctx in result:
                    state.contexts[ctx.name] = ctx
                    state.flags.add(ctx.name)
            else:
                contexts.append(result)
                state.contexts[result.name] = result
                state.flags.add(result.name)

    return sorted(contexts, key=lambda c: c.priority)


__all__ = [
    "DetectionState",
    "detect_contexts",
    "get_activation_hints",
    "ALL_DETECTORS",
]
