"""Screenshot capture — cross-platform using mss (faster) or pyautogui fallback."""

import base64
import io
import time

# Throttle: minimum seconds between screenshots to prevent spam
_MIN_INTERVAL = 0.8
_last_screenshot_time = 0.0

# Max dimension for screenshots to keep payload size reasonable
_MAX_WIDTH = 1280


def _resize_if_needed(pil_img):
    """Downscale to _MAX_WIDTH if wider, to reduce base64 payload."""
    if pil_img.width > _MAX_WIDTH:
        from PIL import Image
        ratio = _MAX_WIDTH / pil_img.width
        new_h = int(pil_img.height * ratio)
        pil_img = pil_img.resize((_MAX_WIDTH, new_h), Image.LANCZOS)
    return pil_img


def take_screenshot():
    """Capture full screen, return base64 JPEG (smaller than PNG)."""
    global _last_screenshot_time

    now = time.time()
    if now - _last_screenshot_time < _MIN_INTERVAL:
        return {
            "success": True,
            "throttled": True,
            "message": f"Screenshot throttled — minimum {_MIN_INTERVAL}s between captures.",
        }
    _last_screenshot_time = now

    try:
        import mss
        with mss.mss() as sct:
            monitor = sct.monitors[0]  # Full virtual screen
            img = sct.grab(monitor)
            from PIL import Image
            pil_img = Image.frombytes("RGB", img.size, img.bgra, "raw", "BGRX")
            pil_img = _resize_if_needed(pil_img)
            buf = io.BytesIO()
            pil_img.save(buf, format="JPEG", quality=70, optimize=True)
            return {
                "success": True,
                "image": base64.b64encode(buf.getvalue()).decode("utf-8"),
                "format": "jpeg",
                "width": pil_img.width,
                "height": pil_img.height,
            }
    except Exception:
        pass

    # Fallback to pyautogui
    try:
        import pyautogui
        img = pyautogui.screenshot()
        img = _resize_if_needed(img)
        buf = io.BytesIO()
        img.save(buf, format="JPEG", quality=70, optimize=True)
        return {
            "success": True,
            "image": base64.b64encode(buf.getvalue()).decode("utf-8"),
            "format": "jpeg",
            "width": img.width,
            "height": img.height,
        }
    except Exception as e:
        return {"success": False, "error": str(e)}


def take_region_screenshot(x, y, width, height):
    """Capture a region of the screen."""
    try:
        import mss
        with mss.mss() as sct:
            region = {"left": x, "top": y, "width": width, "height": height}
            img = sct.grab(region)
            from PIL import Image
            pil_img = Image.frombytes("RGB", img.size, img.bgra, "raw", "BGRX")
            buf = io.BytesIO()
            pil_img.save(buf, format="PNG", optimize=True)
            return {
                "success": True,
                "image": base64.b64encode(buf.getvalue()).decode("utf-8"),
                "width": width,
                "height": height,
            }
    except Exception as e:
        return {"success": False, "error": str(e)}
