"""
agent67.tools.screenshot — 截屏工具 (macOS)

Lambda: λ options. screencapture(options)
"""
import json
import os
import platform
import subprocess
from datetime import datetime


def take_screenshot(input_json: str) -> str:
    """
    截取屏幕截图。

    支持: full / area / window
    """
    try:
        data = json.loads(input_json)
        shot_type = data.get("type", "full")
    except (json.JSONDecodeError, AttributeError):
        shot_type = "full"

    if platform.system() != "Darwin":
        return "⚠️ 截屏目前仅支持 macOS"

    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filepath = os.path.expanduser(f"~/Desktop/screenshot_{timestamp}.png")

    try:
        if shot_type == "area":
            subprocess.run(["screencapture", "-i", filepath], timeout=30)
        elif shot_type == "window":
            subprocess.run(["screencapture", "-w", filepath], timeout=30)
        else:
            subprocess.run(["screencapture", "-x", filepath], timeout=10)

        if os.path.exists(filepath):
            size_kb = os.path.getsize(filepath) // 1024
            return f"📸 截图已保存: {filepath} ({size_kb} KB)"
        else:
            return "❌ 截图被取消"
    except Exception as e:
        return f"❌ 截图错误: {e}"
