"""Screenshot OCR sensor (optional, local-only)."""

from __future__ import annotations

import os
import platform
import subprocess
import tempfile
from pathlib import Path

from neurovault.sensors.base import BaseSensor


class ScreenshotSensor(BaseSensor):
    """Capture periodic screenshots and extract text via OCR."""

    name = "screenshot"
    source_tag = "screen"
    poll_interval = 300.0
    min_text_length = 20

    def poll(self) -> list[tuple[str, dict]]:
        text = self._capture_screen_text()
        if not text or len(text) < self.min_text_length:
            return []
        return [
            (
                text,
                {
                    "content_type": "screen_text",
                    "char_count": len(text),
                },
            )
        ]

    def _capture_screen_text(self) -> str:
        if platform.system() != "Darwin":
            return ""
        fd, tmp_name = tempfile.mkstemp(suffix=".png")
        os.close(fd)
        tmp_path = Path(tmp_name)
        try:
            result = subprocess.run(
                ["screencapture", "-x", "-t", "png", str(tmp_path)],
                capture_output=True,
                timeout=5,
            )
            if result.returncode != 0 or not tmp_path.exists():
                return ""

            try:
                import pytesseract  # type: ignore
                from PIL import Image  # type: ignore
            except Exception:
                return ""

            image = Image.open(tmp_path)
            resized = image.resize((max(1, image.width // 4), max(1, image.height // 4)))
            return pytesseract.image_to_string(resized).strip()
        except Exception:
            return ""
        finally:
            tmp_path.unlink(missing_ok=True)
