#!/usr/bin/env python3
"""zoomstage: CLI controller for ZoomStage.app on macOS."""
import json
import os
import socket
import subprocess
import sys

SOCK_PATH = f"/tmp/zoomstage-{os.getuid()}.sock"
APP_BIN = "/Applications/ZoomStage.app/Contents/MacOS/ZoomStage"


def send_command(args: list[str]) -> dict:
    payload = json.dumps({"args": args}) + "\n"
    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    s.settimeout(2.5)
    s.connect(SOCK_PATH)
    s.sendall(payload.encode("utf-8"))
    chunks = []
    while True:
        data = s.recv(4096)
        if not data:
            break
        chunks.append(data)
    s.close()
    raw = b"".join(chunks).decode("utf-8", errors="replace").strip()
    if not raw:
        return {"ok": True}
    return json.loads(raw)


def ensure_running() -> None:
    if os.path.exists(SOCK_PATH):
        try:
            send_command(["ping"])
            return
        except Exception:
            pass
    if not os.path.exists(APP_BIN):
        sys.stderr.write("ZoomStage.app is not installed at /Applications/ZoomStage.app\n")
        sys.exit(1)
    subprocess.Popen(
        [APP_BIN, "--background"],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
        start_new_session=True,
    )
    import time
    for _ in range(30):
        time.sleep(0.1)
        if os.path.exists(SOCK_PATH):
            try:
                send_command(["ping"])
                return
            except Exception:
                pass


def usage() -> None:
    print(
        """ZoomStage CLI (Adobe-Tilde Instant Window/Plugin Zoom & Accessibility)

Usage:
  zoomstage toggle               Toggle full-screen stage on window under cursor (or whole screen)
  zoomstage box                  Open Box-Zoom marquee selector to fill screen with any device/area
  zoomstage width                Toggle 100% horizontal-width maximize on target window
  zoomstage restore              Exit active optical stage or restore saved native window size
  zoomstage zoom <factor>        Set optical zoom factor (1.0 - 12.0, e.g. zoomstage zoom 2.5)
  zoomstage pan <mode>           locked | edgePush | cursorFollow
  zoomstage chrome [on|off]      Toggle screen-edge border and top-right ZoomStage/F3 corner pill
  zoomstage filter <mode>        normal | smartInvert | yellowOnBlack | amberNight | grayscale
  zoomstage speak                Speak text under cursor (Accessibility + Apple Vision OCR)
  zoomstage speak-window         Speak entire target window text via Vision OCR
  zoomstage profile <name>       studio | low-vision (Doug Comfort Mode)
  zoomstage halo [on|off]        Toggle high-visibility cursor halo & reading rail
  zoomstage open-window          Show ZoomStage Studio preferences window
  zoomstage status [--json]      Show live ZoomStage status and active permissions
  zoomstage help                 Show this help
"""
    )


def main() -> None:
    args = sys.argv[1:]
    if not args or args[0] in ("help", "-h", "--help"):
        usage()
        return

    ensure_running()
    try:
        res = send_command(args)
    except Exception as exc:
        sys.stderr.write(f"ZoomStage IPC error: {exc}\n")
        sys.exit(1)

    if "--json" in args or res.get("json"):
        print(json.dumps(res, indent=2))
    else:
        if "message" in res and res["message"]:
            print(res["message"])
        elif "error" in res and res["error"]:
            sys.stderr.write(res["error"] + "\n")
            sys.exit(1)
        else:
            print(json.dumps(res, indent=2))


if __name__ == "__main__":
    main()
