"""Cloud orchestra vision verify client for paired desktop agents."""

from __future__ import annotations

import base64
import logging
from typing import Any

from iuve_connect_agents.shared.avatar_llm_cloud import load_desktop_cloud_credentials

logger = logging.getLogger(__name__)

_MAX_IMAGE_BYTES = 512 * 1024


def request_cloud_verify_vision(
    *,
    verify_prompt: str,
    image_bytes: bytes,
    expected_text: str = "",
    plan_id: str = "",
    step_id: str = "",
    evidence_sha256: str = "",
) -> dict[str, Any] | None:
    """Call backend cloud vision verify; None when unavailable or disabled."""
    from iuve_connect_agents.shared.feature_flags import cloud_vision_verify_available

    if not cloud_vision_verify_available():
        return None

    creds = load_desktop_cloud_credentials()
    if not creds:
        return None

    payload_bytes = image_bytes or b""
    if not payload_bytes or len(payload_bytes) > _MAX_IMAGE_BYTES:
        return None

    backend_url, auth_token = creds
    prompt = str(verify_prompt or "").strip()
    if not prompt:
        return None

    try:
        from iuve_connect_agents.core.api_client import BackendAuthRequiredError, PassiveApiClient

        response = PassiveApiClient(base_url=backend_url).request_avatar_verify_vision(
            auth_token=auth_token,
            verify_prompt=prompt,
            image_base64=base64.b64encode(payload_bytes).decode("ascii"),
            expected_text=expected_text,
            plan_id=plan_id,
            step_id=step_id,
            evidence_sha256=evidence_sha256,
        )
    except BackendAuthRequiredError:
        logger.warning("avatar_cloud_vision_auth_required")
        return None
    except Exception as exc:
        logger.warning("avatar_cloud_vision_request_failed error=%s", exc)
        return None

    if not isinstance(response, dict) or not response.get("ok"):
        return None
    return response
