#!/usr/bin/env python3
"""
AI Dental Agents — office helper.  Run this on the PC that has your practice software open.

    python helper.py ABCD-1234

That's it. The consultant takes it from here; you watch the cursor. Move the mouse to any
screen corner to stop instantly. Nothing is installed, nothing is stored on this PC, and the
only thing that leaves this machine is screenshots of what's on screen while the session runs.
"""
import sys, time, json, requests
from agent.executor import Executor

SERVER = "https://aidentalagents.com"


def _capture_ok() -> bool:
    """macOS hands a process WITHOUT Screen Recording permission a capture of wallpaper + menu bar only — every
    window omitted. The agent would then click real windows it cannot see. Refuse to start in that state."""
    if sys.platform != "darwin":
        return True
    try:
        import Quartz
        if Quartz.CGPreflightScreenCaptureAccess():
            return True
        Quartz.CGRequestScreenCaptureAccess()          # shows the system prompt once; a prior denial needs the Settings toggle
    except Exception:
        return True                                     # no Quartz bindings → cannot check, proceed
    print("SCREEN CAPTURE IS BLOCKED. System Settings → Privacy & Security → Screen Recording → allow the app running this "
          "(then relaunch it). Nothing was started.")
    return False


def main():
    if not _capture_ok(): return
    if len(sys.argv) < 2:
        sys.exit("usage: python helper.py <JOIN-CODE>")
    code = sys.argv[1].strip().upper()
    ex = Executor()
    print(f"\nAI Dental Agents — joining session {code}")
    print(f"screen {ex.real_w}x{ex.real_h} → model frame {ex.disp_w}x{ex.disp_h}")
    print("Move the mouse to a screen corner to stop.\n")

    r = requests.post(f"{SERVER}/api/session/{code}/join",
                      json={"display_w": ex.disp_w, "display_h": ex.disp_h, "png_b64": ex.screenshot_b64()}, timeout=60)
    r.raise_for_status()
    sess = r.json()
    print(f"connected · {sess.get('pms_label')} · {sess.get('office')}\n")

    results = None
    for step_no in range(1, 200):
        payload = {"results": results} if results else {}
        r = requests.post(f"{SERVER}/api/session/{code}/step", json=payload, timeout=290)
        if r.status_code != 200:
            print("server:", r.status_code, r.text[:200]); time.sleep(3); continue
        out = r.json()
        if out.get("narration"):
            print(f"  ▸ {out['narration']}")
        if out.get("done"):
            print("\nDONE. Check the 'Lender Reports' folder on the Desktop.")
            break
        results = []
        for act in out.get("actions", []):
            res = ex.run(act["input"])
            results.append({"tool_use_id": act["id"], **res})
            if res.get("is_error") and "ABORTED" in (res.get("text") or ""):
                requests.post(f"{SERVER}/api/session/{code}/done", json={"reason": "aborted"}, timeout=30)
                print("\nStopped by you."); return
    else:
        print("step limit reached — session closed")


if __name__ == "__main__":
    main()
