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

import base64
import io

def take_screenshot():
    """Capture full screen, return base64 PNG."""
    try:
        import mss
        with mss.mss() as sct:
            monitor = sct.monitors[0]  # Full virtual screen
            img = sct.grab(monitor)
            # Convert to PNG bytes
            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": img.size.width,
                "height": img.size.height,
            }
    except Exception:
        pass

    # Fallback to pyautogui
    try:
        import pyautogui
        img = pyautogui.screenshot()
        buf = io.BytesIO()
        img.save(buf, format="PNG")
        return {
            "success": True,
            "image": base64.b64encode(buf.getvalue()).decode("utf-8"),
            "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)}
