# tools/ocr_backends/vision.py - Swift bridge Vision OCR backend (no Python PyObjC).
from __future__ import annotations

import io
import json
import sys

from PIL import Image

from tools._macos_bridge import bridge_request, get_bridge_config

VISION_AVAILABLE = sys.platform == "darwin"
VISION_ERROR: str | None = None if VISION_AVAILABLE else "Vision OCR bridge requires macOS."

_MAX_EDGE = 4096
_MAX_MEGAPIXELS = 16


def run_vision_ocr_on_pil_image(pil_img) -> str:
    """Run OCR on a PIL image via the Swift bridge endpoint /vision/ocr."""
    if not VISION_AVAILABLE:
        return ""
    cfg, _ = get_bridge_config()
    if not cfg:
        return ""

    img = pil_img.convert("RGB") if pil_img.mode != "RGB" else pil_img
    w, h = img.size
    if w <= 0 or h <= 0:
        return ""
    scale = min(1.0, _MAX_EDGE / float(max(w, h)))
    megapixels = (w * h) / 1_000_000.0
    if megapixels > _MAX_MEGAPIXELS:
        scale = min(scale, (_MAX_MEGAPIXELS / megapixels) ** 0.5)
    if scale < 1.0:
        img = img.resize((max(1, int(w * scale)), max(1, int(h * scale))), Image.Resampling.LANCZOS)

    buf = io.BytesIO()
    img.save(buf, format="PNG")
    status, raw, req_err = bridge_request(
        cfg,
        "/vision/ocr",
        method="POST",
        headers={"Content-Type": "image/png"},
        body=buf.getvalue(),
        timeout=60,
    )
    if req_err or status != 200:
        return ""
    try:
        parsed = json.loads(raw.decode("utf-8"))
    except Exception:
        return ""
    return str(parsed.get("text") or "")
