"""Desktop vision gate: env flag and/or persisted screen_vision grant (0.2.2.25)."""

from __future__ import annotations

import os
from pathlib import Path


def desktop_vision_env_flag() -> bool | None:
    """Return explicit env flag, or None when unset (grant may enable vision)."""
    raw = os.getenv("AVATAR_DESKTOP_VISION_ENABLED")
    if raw is None:
        legacy = os.getenv("AVATAR_VISION_ENABLED")
        if legacy is None:
            return None
        raw = legacy
    return raw.strip().lower() in {"1", "true", "yes", "on"}


def read_screen_vision_grant_active(*, state_path: Path | str | None = None) -> bool:
    """Read active screen_vision grant from persisted capability-state.json."""
    try:
        from iuve_connect_agents.desktop.capability_manager import CapabilityStateManager

        mgr = CapabilityStateManager(Path(state_path) if state_path else None)
        cap = mgr.get("screen_vision")
        if cap is None:
            return False
        return bool(cap.enabled and not cap.is_expired())
    except Exception:
        return False


def desktop_vision_enabled(*, screen_vision_granted: bool | None = None) -> bool:
    """True when env master flag is on, or grant is active and env is not explicitly off."""
    env = desktop_vision_env_flag()
    if env is True:
        return True
    if env is False:
        return False
    grant = (
        screen_vision_granted
        if screen_vision_granted is not None
        else read_screen_vision_grant_active()
    )
    return bool(grant)


def effective_screen_vision_granted(*, payload_grant: bool | None = None) -> bool:
    """Grant for vision execution: payload override, else persisted grant or env master ON."""
    if payload_grant is not None:
        return bool(payload_grant)
    if read_screen_vision_grant_active():
        return True
    return desktop_vision_env_flag() is True


def desktop_vision_block_reason(*, screen_vision_granted: bool | None = None) -> str | None:
    """Return block reason key when vision is unavailable, else None."""
    grant = (
        bool(screen_vision_granted)
        if screen_vision_granted is not None
        else read_screen_vision_grant_active()
    )
    env = desktop_vision_env_flag()
    if not grant:
        return "vision_grant_required"
    if env is False:
        return "vision_flag_disabled"
    if not desktop_vision_enabled(screen_vision_granted=grant):
        return "vision_unavailable"
    return None
