"""Vision-guided window focus recovery after keyboard automation failures (P1-3 MVP)."""

from __future__ import annotations

import logging
from pathlib import Path
from typing import Callable

logger = logging.getLogger(__name__)

VisionFocusCallback = Callable[[], tuple[bool, str]]


def _read_image_bytes(path: str) -> bytes:
    try:
        return Path(path).read_bytes()
    except OSError:
        return b""


def vision_confirms_browser_visible(
    *,
    screen_vision_granted: bool,
    window_name: str = "",
    search_query: str = "",
) -> tuple[bool, str]:
    """Capture screenshot and ask cloud vision whether a browser window is visible."""
    if not screen_vision_granted:
        return False, "vision_grant_required"

    from iuve_connect_agents.shared.feature_flags import cloud_vision_verify_available

    if not cloud_vision_verify_available():
        return False, "cloud_vision_unavailable"

    try:
        from .desktop_screenshot_capture import capture_screenshot
        from iuve_connect_agents.shared.avatar_vision_cloud import request_cloud_verify_vision
    except ImportError as exc:
        return False, f"vision_import_failed:{exc}"

    artifact = capture_screenshot(plan_id="focus_recovery", step_id="browser_check", delay_ms=400)
    image_bytes = _read_image_bytes(artifact.path)
    if not image_bytes:
        return False, "screenshot_empty"

    hints: list[str] = ["web browser window", "browser tab", "address bar"]
    if window_name:
        hints.append(window_name)
    if search_query:
        hints.append(search_query)
    prompt = (
        "Is a desktop web browser window clearly visible on screen (not IDE/editor)? "
        f"Look for: {', '.join(hints)}. Answer yes only if a browser is the foreground or clearly visible."
    )
    response = request_cloud_verify_vision(
        verify_prompt=prompt,
        image_bytes=image_bytes,
        expected_text="browser",
        plan_id="focus_recovery",
        step_id="browser_check",
        evidence_sha256=artifact.sha256,
    )
    if not isinstance(response, dict):
        return False, "vision_no_response"

    passed = bool(response.get("pass") or response.get("ok"))
    detail = str(response.get("summary") or response.get("reason") or response.get("detail") or "")
    if passed:
        return True, detail or "browser_visible"
    return False, detail or "browser_not_visible"


def make_browser_vision_focus_callback(
    *,
    screen_vision_granted: bool,
    window_name: str = "",
    search_query: str = "",
) -> VisionFocusCallback | None:
    """Build optional vision callback for recover_window_focus (graceful when grant missing)."""
    if not screen_vision_granted:
        return None

    def _callback() -> tuple[bool, str]:
        try:
            return vision_confirms_browser_visible(
                screen_vision_granted=True,
                window_name=window_name,
                search_query=search_query,
            )
        except Exception as exc:
            logger.warning("vision_focus_recovery_failed error=%s", exc)
            return False, str(exc) or "vision_recovery_failed"

    return _callback
