# tools/screenshots.py - macOS screenshot capture.
from __future__ import annotations

import os
import subprocess

from langchain_core.tools import tool

from tools.live_view_visuals import emit_live_view_preview, image_to_preview_base64
from utils.path_safety import is_dangerous_path, is_plugins_dir_write_blocked


@tool
def capture_screenshot(output_path: str, region: str | None = None) -> str:
    """Capture the current screen or window and save to a PNG file. Input: output PNG path. Optional: region as 'x,y,width,height'. Uses macOS screencapture. For a screenshot of a webpage URL, use screenshot_webpage instead."""
    abs_out = os.path.abspath(os.path.expanduser(output_path.strip()))
    if is_dangerous_path(abs_out):
        return f"Blocked: output path is in a protected location: {abs_out}"
    if is_plugins_dir_write_blocked(abs_out):
        return "Blocked: cannot write to the plugins directory. Use create_plugin (evolution mode) to add plugins."
    cmd = ["/usr/sbin/screencapture", "-x"]
    if region and isinstance(region, str):
        try:
            x, y, w, h = map(int, region.split(","))
            cmd += ["-R", f"{x},{y},{w},{h}"]
        except ValueError:
            return "Invalid region format. Use 'x,y,width,height' (integers)."
    cmd.append(abs_out)
    try:
        subprocess.run(cmd, check=True, capture_output=True)
        if os.path.isfile(abs_out):
            try:
                with open(abs_out, "rb") as _f:
                    b64 = image_to_preview_base64(_f.read(), max_width=1400)
                if b64:
                    emit_live_view_preview("Screenshot saved", tool_name="capture_screenshot", preview_image_base64=b64)
            except Exception:
                pass
            return f"Screenshot saved to: {abs_out}"
        return "Screenshot captured but file not found."
    except subprocess.CalledProcessError as e:
        return f"Screenshot failed: {e.stderr.decode().strip() or str(e)}"
    except Exception as e:
        return f"Unexpected error: {str(e)}"
