"""Mac-local bridge for approved remote computer-use actions.

This module is intended to run on the MacBook side only.  The Linux gateway
invokes it over SSH with a single JSON argv payload; it validates that the host
is macOS with cua-driver installed, then delegates to the existing
``computer_use`` implementation.
"""

from __future__ import annotations

import json
import subprocess
import sys
from typing import Any

_ALLOWED_ACTIONS = {
    "capture",
    "click",
    "double_click",
    "right_click",
    "middle_click",
    "drag",
    "scroll",
    "type",
    "key",
    "set_value",
    "wait",
    "list_apps",
    "focus_app",
    "launch_app",
    "copy_text",
}


class MacbookGuiBridgeError(ValueError):
    """Expected bridge validation failure."""


def _load_payload(argv: list[str]) -> dict[str, Any]:
    if len(argv) != 2:
        raise MacbookGuiBridgeError("expected exactly one JSON payload argument")
    try:
        payload = json.loads(argv[1])
    except json.JSONDecodeError as exc:
        raise MacbookGuiBridgeError(f"invalid JSON payload: {exc}") from exc
    if not isinstance(payload, dict):
        raise MacbookGuiBridgeError("payload must be a JSON object")
    return payload


def _require_macos() -> None:
    if sys.platform != "darwin":
        raise MacbookGuiBridgeError("macbook_gui_bridge must run on macOS")


def _normalize_action(payload: dict[str, Any]) -> str:
    action = str(payload.get("action") or "").strip().lower()
    if action == "health":
        return action
    if action not in _ALLOWED_ACTIONS:
        raise MacbookGuiBridgeError("unsupported computer_use action")
    payload["action"] = action
    return action


def run_payload(payload: dict[str, Any]) -> Any:
    """Run one already-approved computer-use payload on the local Mac."""
    _require_macos()
    action = _normalize_action(payload)
    if action == "health":
        from tools.computer_use.cua_backend import cua_driver_binary_available

        return {
            "ok": True,
            "platform": sys.platform,
            "cua_driver": cua_driver_binary_available(),
        }

    if action == "launch_app":
        app = str(payload.get("app") or "").strip()
        if not app:
            raise MacbookGuiBridgeError("app is required for launch_app")
        selector = "-b" if app.startswith("com.") else "-a"
        subprocess.run(["open", selector, app], check=True, timeout=10)
        return {"ok": True, "action": "launch_app", "app": app}

    from tools.computer_use.tool import handle_computer_use

    if action == "copy_text":
        app = str(payload.get("app") or "").strip()
        if app:
            handle_computer_use({"action": "focus_app", "app": app})
        old_clipboard = subprocess.run(["pbpaste"], text=True, capture_output=True, timeout=5).stdout
        try:
            handle_computer_use({"action": "key", "keys": "cmd+a"})
            handle_computer_use({"action": "key", "keys": "cmd+c"})
            text = subprocess.run(["pbpaste"], text=True, capture_output=True, timeout=5).stdout
            return {"ok": True, "action": "copy_text", "app": app, "text": text}
        finally:
            subprocess.run(["pbcopy"], input=old_clipboard, text=True, timeout=5)
    return handle_computer_use(payload)


def main(argv: list[str] | None = None) -> int:
    argv = sys.argv if argv is None else argv
    try:
        payload = _load_payload(argv)
        result = run_payload(payload)
        print(json.dumps({"ok": True, "result": result}, ensure_ascii=False))
        return 0
    except Exception as exc:
        print(json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False))
        return 0


if __name__ == "__main__":  # pragma: no cover
    raise SystemExit(main())
