#!/usr/bin/env python3
"""Jarvis Growth host agent — bridges Supabase to a local SideTap viewer (stdlib only).

Environment:
  NF_SUPABASE_URL          https://xxx.supabase.co
  NF_SUPABASE_ANON_KEY     publishable (anon) key
  NF_HOST_TOKEN            nfh_... token from admin console
  NF_VIEWER_URL            http://127.0.0.1:8770  (SideTap viewer)
  NF_AGENT_VERSION         optional label sent to cloud

Run on the Windows PC where iPhones are USB-connected and SideTap is running.
"""
from __future__ import annotations

import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from typing import Any

try:
    from whip_publisher import stop_all_publishers, sync_live_publishers, whip_active_udids
except ImportError:
    from agent.whip_publisher import stop_all_publishers, sync_live_publishers, whip_active_udids

AGENT_VERSION = os.environ.get("NF_AGENT_VERSION", "0.3.2")
SUPPORTED_COMMANDS = (
    "home", "lock", "unlock", "tap", "swipe", "type", "key", "open_app", "close_app",
    "refresh", "farm_api", "account_login",
)
VIEWER = os.environ.get("NF_VIEWER_URL", "http://127.0.0.1:8770").rstrip("/")
SUPABASE_URL = os.environ.get("NF_SUPABASE_URL", "").rstrip("/")
ANON_KEY = os.environ.get("NF_SUPABASE_ANON_KEY", "")
HOST_TOKEN = os.environ.get("NF_HOST_TOKEN", "")
SYNC_IDLE = float(os.environ.get("NF_SYNC_IDLE", "3.0"))

# Tuned per dashboard "Stream quality" (watch_device → stream_quality on device_watches).
STREAM_PROFILES: dict[str, dict[str, float | int]] = {
    "fast": {"interval": 0.12, "sync": 0.22, "scale": 0.40, "quality": 40, "max_kb": 85, "mjpeg_loops": 20},
    "balanced": {"interval": 0.28, "sync": 0.38, "scale": 0.58, "quality": 52, "max_kb": 150, "mjpeg_loops": 36},
    "sharp": {"interval": 0.45, "sync": 0.55, "scale": 1.0, "quality": 68, "max_kb": 360, "mjpeg_loops": 52},
}


def log(msg: str) -> None:
    print(f"[farm-agent] {msg}", flush=True)


def http_json(method: str, url: str, body: dict | None = None, headers: dict | None = None, timeout: float = 30) -> Any:
    data = None
    hdrs = {"Accept": "application/json"}
    if headers:
        hdrs.update(headers)
    if body is not None:
        data = json.dumps(body).encode("utf-8")
        hdrs["Content-Type"] = "application/json"
    req = urllib.request.Request(url, data=data, headers=hdrs, method=method)
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            raw = resp.read()
            if not raw:
                return None
            return json.loads(raw.decode("utf-8"))
    except urllib.error.HTTPError as e:
        detail = e.read().decode("utf-8", errors="replace")
        raise RuntimeError(f"{method} {url} -> {e.code}: {detail}") from e


def _owner_headers(owner_id: str | None) -> dict[str, str]:
    if not owner_id:
        return {}
    o = str(owner_id).strip().lower()
    if len(o) != 36 or o.count("-") != 4:
        return {}
    return {"X-NF-Owner": o}


def viewer_json(path: str, timeout: float = 15, owner_id: str | None = None) -> dict:
    return http_json(
        "GET",
        f"{VIEWER}{path}",
        headers=_owner_headers(owner_id),
        timeout=timeout,
    )


def viewer_post(
    path: str,
    payload: dict | None = None,
    timeout: float = 60,
    owner_id: str | None = None,
) -> dict | None:
    return http_json(
        "POST",
        f"{VIEWER}{path}",
        payload or {},
        headers=_owner_headers(owner_id),
        timeout=timeout,
    )


_FARM_PREFIX = "/api/farm"


def farm_allowed_path(path: str) -> bool:
    if not path.startswith("/"):
        path = "/" + path
    if path in ("/api/open-app", "/api/account/login"):
        return True
    return path.startswith(_FARM_PREFIX)


def run_account_login(payload: dict) -> tuple[bool, str | None, dict | None]:
    """SideTap POST /api/account/login — full tap/type login flow on :8770."""
    body = {
        "platform": payload.get("platform", "instagram"),
        "username": (payload.get("username") or "").strip().lstrip("@"),
        "password": payload.get("password") or "",
        "totp_secret": payload.get("totp_secret") or "",
        "behavior": payload.get("behavior", "normal"),
        "login_path": payload.get("login_path") or "welcome",
    }
    try:
        data = viewer_post("/api/account/login", body, timeout=180.0)
        if not isinstance(data, dict):
            return False, "invalid response from SideTap", None
        ok = bool(data.get("ok"))
        err = None if ok else str(data.get("error") or data)[:300]
        return ok, err, data
    except Exception as exc:
        return False, str(exc)[:300], None


def run_farm_api(
    payload: dict, owner_id: str | None = None
) -> tuple[bool, str | None, dict | None]:
    method = (payload.get("method") or "GET").upper()
    path = payload.get("path") or ""
    if not farm_allowed_path(path):
        return False, "path not allowed", None
    body = payload.get("body")
    if not isinstance(body, dict):
        body = {}
    timeout = 90.0 if path.endswith("/run") else 25.0
    try:
        if method == "GET":
            data = viewer_json(path, timeout=timeout, owner_id=owner_id)
        elif method == "POST":
            data = viewer_post(path, body, timeout=timeout, owner_id=owner_id)
        else:
            return False, f"unsupported method {method}", None
        if not isinstance(data, dict):
            data = {"ok": True, "raw": data}
        ok = bool(data.get("ok", True)) and "error" not in data
        err = None if ok else str(data.get("error") or data)[:300]
        return ok, err, data
    except Exception as exc:
        return False, str(exc)[:300], None


def collect_farm_snapshot(
    full: bool = False, owner_id: str | None = None
) -> dict | None:
    """Mirror SideTap /farm dashboard state for cloud viewers."""
    try:
        snap: dict[str, Any] = {
            "ts": time.time(),
            "status": viewer_json("/api/farm/status", timeout=8, owner_id=owner_id),
            "live": viewer_json(
                "/api/farm/live?limit=150", timeout=10, owner_id=owner_id
            ),
        }
        if full:
            snap["campaigns"] = viewer_json(
                "/api/farm/campaigns", timeout=10, owner_id=owner_id
            )
            snap["tasks"] = viewer_json(
                "/api/farm/tasks", timeout=10, owner_id=owner_id
            )
            snap["scheduler"] = viewer_json(
                "/api/farm/scheduler", timeout=8, owner_id=owner_id
            )
        return snap
    except Exception as exc:
        log(f"farm snapshot failed: {exc}")
        return None


def _extract_jpeg(buf: bytes) -> bytes | None:
    start = buf.find(b"\xff\xd8")
    if start < 0:
        return None
    end = buf.find(b"\xff\xd9", start + 2)
    if end > start:
        return buf[start : end + 2]
    return None


def grab_frame_live(max_loops: int = 36) -> tuple[bytes, str] | None:
    """Fast path for live view: one MJPEG frame (already scaled in SideTap)."""
    try:
        req = urllib.request.Request(f"{VIEWER}/mjpeg")
        with urllib.request.urlopen(req, timeout=8) as resp:
            buf = b""
            for _ in range(max(8, max_loops)):
                chunk = resp.read(4096)
                if not chunk:
                    break
                buf += chunk
                jpeg = _extract_jpeg(buf)
                if jpeg and len(jpeg) > 2000:
                    return jpeg, "image/jpeg"
    except Exception:
        pass
    return None


def grab_frame_bytes() -> tuple[bytes, str] | None:
    """Idle / fallback: MJPEG first, then PNG screenshot."""
    live = grab_frame_live()
    if live:
        return live
    try:
        req = urllib.request.Request(f"{VIEWER}/api/screenshot")
        with urllib.request.urlopen(req, timeout=12) as resp:
            data = resp.read()
            if len(data) > 8 and data[:8] == b"\x89PNG\r\n\x1a\n":
                return data, "image/png"
    except Exception:
        pass
    return None


def pick_stream_profile(device_rows: list[dict]) -> str:
    qualities = [d.get("stream_quality", "balanced") for d in device_rows if d.get("watched")]
    if "fast" in qualities:
        return "fast"
    if "sharp" in qualities and "balanced" not in qualities:
        return "sharp"
    return qualities[0] if qualities else "balanced"


def compress_jpeg(blob: bytes, profile: str) -> tuple[bytes, str]:
    prof = STREAM_PROFILES.get(profile, STREAM_PROFILES["balanced"])
    scale = float(prof["scale"])
    quality = int(prof["quality"])
    if scale >= 0.99:
        return blob, "image/jpeg"
    try:
        from io import BytesIO

        from PIL import Image  # type: ignore

        img = Image.open(BytesIO(blob)).convert("RGB")
        nw = max(1, int(img.width * scale))
        nh = max(1, int(img.height * scale))
        if nw < img.width or nh < img.height:
            img = img.resize((nw, nh), Image.Resampling.BILINEAR)
        out = BytesIO()
        img.save(out, format="JPEG", quality=quality, optimize=True)
        return out.getvalue(), "image/jpeg"
    except Exception:
        return blob, "image/jpeg"


def upload_watched_frame(udid: str, profile: str) -> None:
    prof = STREAM_PROFILES.get(profile, STREAM_PROFILES["balanced"])
    frame = grab_frame_live(int(prof["mjpeg_loops"]))
    if not frame:
        frame = grab_frame_bytes()
    if not frame:
        return
    blob, ctype = frame
    max_bytes = int(prof["max_kb"]) * 1024
    if ctype == "image/jpeg":
        blob, ctype = compress_jpeg(blob, profile)
    elif ctype == "image/png" and float(prof["scale"]) < 0.99:
        try:
            from io import BytesIO

            from PIL import Image  # type: ignore

            img = Image.open(BytesIO(blob)).convert("RGB")
            nw = max(1, int(img.width * float(prof["scale"])))
            nh = max(1, int(img.height * float(prof["scale"])))
            img = img.resize((nw, nh), Image.Resampling.BILINEAR)
            out = BytesIO()
            img.save(out, format="JPEG", quality=int(prof["quality"]), optimize=True)
            blob, ctype = out.getvalue(), "image/jpeg"
        except Exception:
            pass
    if len(blob) > max_bytes and profile == "fast":
        log(f"frame {len(blob)//1024}KB > fast cap; install Pillow for smaller JPEGs")
    upload_frame(udid, blob, ctype)


def upload_frame(udid: str, blob: bytes, content_type: str) -> None:
    url = f"{SUPABASE_URL}/functions/v1/agent-frame?udid={urllib.parse.quote(udid)}"
    req = urllib.request.Request(
        url,
        data=blob,
        method="POST",
        headers={
            "Content-Type": content_type,
            "x-host-token": HOST_TOKEN,
            "apikey": ANON_KEY,
        },
    )
    with urllib.request.urlopen(req, timeout=45) as resp:
        resp.read()


def discover_devices(status: dict) -> list[dict]:
    """Build device list for sync payload. Extend with go-ios list on Windows."""
    window = status.get("window") or {}
    w, h = window.get("width"), window.get("height")
    link = status.get("link", "down")
    dev_status = "online" if link == "up" else "offline" if link == "down" else "error"
    udid = os.environ.get("NF_DEVICE_UDID") or status.get("udid") or "local-device"
    devices = [{
        "udid": udid,
        "name": os.environ.get("NF_DEVICE_NAME", "iPhone"),
        "status": dev_status,
        "status_detail": f"link={link}",
        "screen_w": w,
        "screen_h": h,
        "input_ok": bool(status.get("input")),
    }]
  # phone info is expensive on some apps — poll sparingly
    if os.environ.get("NF_POLL_PHONE", "").lower() in ("1", "true", "yes"):
        try:
            phone = viewer_json("/api/phone", timeout=12)
            bat = phone.get("battery") or {}
            if bat.get("level") is not None:
                devices[0]["battery"] = int(float(bat["level"]) * 100)
            devices[0]["charging"] = bat.get("state") == 2
            devices[0]["locked"] = phone.get("locked")
            app = phone.get("app") or {}
            devices[0]["foreground_app"] = app.get("name") or app.get("bundleId")
        except Exception:
            pass
    return devices


def run_command(cmd: dict, window: dict) -> tuple[bool, str | None]:
    typ = cmd.get("type")
    payload = cmd.get("payload") or {}
    w = float(window.get("width") or 390)
    h = float(window.get("height") or 844)

    try:
        if typ == "home":
            viewer_post("/api/home", {})
        elif typ == "lock":
            viewer_post("/api/lock", {})
        elif typ == "unlock":
            viewer_post("/api/unlock", {})
        elif typ == "refresh":
            viewer_post("/api/stop", {"stop": False})
        elif typ == "tap":
            x = float(payload.get("x", 0.5)) * w
            y = float(payload.get("y", 0.5)) * h
            viewer_post("/api/tap", {"x": x, "y": y})
        elif typ == "swipe":
            viewer_post("/api/swipe", {
                "x1": float(payload.get("x1", 0.5)) * w,
                "y1": float(payload.get("y1", 0.7)) * h,
                "x2": float(payload.get("x2", 0.5)) * w,
                "y2": float(payload.get("y2", 0.3)) * h,
                "seconds": float(payload.get("seconds", 0.35)),
            })
        elif typ == "type":
            viewer_post("/api/type", {"text": payload.get("text", "")})
        elif typ == "key":
            viewer_post("/api/key", {"key": payload.get("key", "")})
        elif typ == "open_app":
            viewer_post("/api/open-app", {"name": payload.get("name", "Instagram")})
        elif typ == "close_app":
            viewer_post("/api/close-app", {"name": payload.get("name", "")})
        elif typ == "account_login":
            ok, err, _data = run_account_login(payload)
            if not ok:
                return False, err or "account_login failed"
            return True, None
        else:
            return False, f"unknown command {typ} (upgrade farm_agent to {AGENT_VERSION}+ for account_login)"
        return True, None
    except Exception as exc:
        return False, str(exc)[:300]


def run_command_with_result(cmd: dict, window: dict) -> dict:
    """Like run_command but returns agent_sync result row (incl. farm_api data)."""
    typ = cmd.get("type")
    payload = cmd.get("payload") or {}
    cid = cmd.get("id")
    if typ == "farm_api":
        ok, err, data = run_farm_api(payload, cmd.get("requested_by"))
        row: dict[str, Any] = {"id": cid, "ok": ok}
        if err:
            row["error"] = err
        if ok and data is not None:
            row["data"] = data
        return row
    if typ == "account_login":
        log(f"account_login @{payload.get('username', '?')} via SideTap {VIEWER}/api/account/login")
        ok, err, data = run_account_login(payload)
        row = {"id": cid, "ok": ok}
        if err:
            row["error"] = err
        if data is not None:
            row["data"] = data
        return row
    ok, err = run_command(cmd, window)
    row = {"id": cid, "ok": ok}
    if err:
        row["error"] = err
    return row


def agent_sync(payload: dict) -> dict:
    url = f"{SUPABASE_URL}/rest/v1/rpc/agent_sync"
    return http_json(
        "POST",
        url,
        {"p_token": HOST_TOKEN, "p_payload": payload},
        headers={"apikey": ANON_KEY, "Authorization": f"Bearer {ANON_KEY}"},
        timeout=60,
    )


def flush_command_results(
    results: list[dict],
    devices: list[dict],
    *,
    viewer_url_reported: str | None,
) -> list[dict]:
    """Push command results immediately so long account_login runs are not expired server-side."""
    if not results:
        return results
    sync_body: dict[str, Any] = {
        "agent": {
            "version": AGENT_VERSION,
            "hostname": os.environ.get("COMPUTERNAME") or os.environ.get("HOSTNAME", ""),
            "platform": sys.platform,
            **({"viewer_url": viewer_url_reported} if viewer_url_reported else {}),
        },
        "results": results,
        "devices": devices,
    }
    try:
        resp = agent_sync(sync_body)
        if not resp.get("ok"):
            log(f"result flush rejected: {resp}")
            return results
        return []
    except Exception as exc:
        log(f"result flush failed: {exc}")
        return results


def main() -> int:
    if not all([SUPABASE_URL, ANON_KEY, HOST_TOKEN]):
        log("Set NF_SUPABASE_URL, NF_SUPABASE_ANON_KEY, NF_HOST_TOKEN")
        return 2

    viewer_url_reported = os.environ.get("NF_VIEWER_PUBLIC_URL")
    results: list[dict] = []
    last_idle_frame = 0.0
    last_sync = 0.0
    watched_udids: set[str] = set()
    farm_watched_udids: set[str] = set()
    stream_profile = "balanced"
    last_farm_full = 0.0
    last_farm_live = 0.0
    farm_snapshots: list[dict] = []
    cloud_devices: dict[str, dict] = {}

    last_whip_thumb: dict[str, float] = {}
    whip_udids: set[str] = set()

    log(f"Agent {AGENT_VERSION} -> {SUPABASE_URL} viewer {VIEWER}")
    log(f"Commands: {', '.join(SUPPORTED_COMMANDS)}")
    log("Live: WebRTC WHIP when LiveKit is enabled; else JPEG upload (fast/balanced/sharp)")

    while True:
        loop_start = time.time()
        sleep_for = SYNC_IDLE
        commands_ran = False
        try:
            status = viewer_json("/api/status", timeout=6)
            devices = discover_devices(status)
            now = time.time()
            farm_live = bool(farm_watched_udids)
            live = bool(watched_udids)
            prof = STREAM_PROFILES.get(stream_profile, STREAM_PROFILES["balanced"])
            sync_interval = float(prof["sync"]) if live else SYNC_IDLE
            if farm_live:
                sync_interval = min(sync_interval, 0.28)
            if results:
                sync_interval = min(sync_interval, 0.12)
            sync_due = (now - last_sync) >= sync_interval

            if sync_due:
                sync_body: dict[str, Any] = {
                    "agent": {
                        "version": AGENT_VERSION,
                        "hostname": os.environ.get("COMPUTERNAME") or os.environ.get("HOSTNAME", ""),
                        "platform": sys.platform,
                        **({"viewer_url": viewer_url_reported} if viewer_url_reported else {}),
                    },
                    "results": results,
                    "devices": devices,
                }
                if farm_snapshots:
                    sync_body["farm_snapshots"] = farm_snapshots
                    farm_snapshots = []
                resp = agent_sync(sync_body)
                results = []
                last_sync = now

                if not resp.get("ok"):
                    log(f"sync rejected: {resp}")
                    time.sleep(1.0)
                    continue

                device_rows = resp.get("devices") or []
                whip_udids = sync_live_publishers(device_rows, VIEWER)
                for row in device_rows:
                    if not row.get("watched"):
                        continue
                    ls = row.get("live_stream")
                    u = row.get("udid", "?")[:8]
                    if isinstance(ls, dict) and ls.get("whip_url"):
                        if row.get("udid") in whip_udids:
                            log(f"WHIP publishing for {u}…")
                        else:
                            log(f"WHIP needed for {u} but ffmpeg did not start (run check_ffmpeg.ps1)")
                    elif row.get("watched"):
                        log(f"Live watch {u}: no WHIP session yet (open Live View in dashboard)")
                cloud_devices = {d["udid"]: d for d in device_rows if d.get("udid")}
                stream_profile = pick_stream_profile(device_rows)
                watched_udids = {d["udid"] for d in device_rows if d.get("watched")}
                farm_watched_udids = {d["udid"] for d in device_rows if d.get("farm_watch")}
                live = bool(watched_udids)
                prof = STREAM_PROFILES.get(stream_profile, STREAM_PROFILES["balanced"])
                commands = resp.get("commands") or []
                window = status.get("window") or {}

                for cmd in commands:
                    row = run_command_with_result(cmd, window)
                    results.append(row)
                    typ = cmd.get("type")
                    if typ == "farm_api":
                        log(f"farm_api {cmd.get('payload', {}).get('path')} ok={row.get('ok')}")
                    elif typ == "account_login":
                        log(
                            f"account_login @{cmd.get('payload', {}).get('username', '?')} "
                            f"ok={row.get('ok')} err={row.get('error') or '-'}"
                        )
                if commands:
                    commands_ran = True
                    results = flush_command_results(results, devices, viewer_url_reported=viewer_url_reported)
                    last_sync = 0.0
                    time.sleep(0.08)
                    for dev in devices:
                        udid = dev["udid"]
                        if udid in watched_udids and dev.get("status") == "online":
                            try:
                                upload_watched_frame(udid, stream_profile)
                                time.sleep(0.08)
                                upload_watched_frame(udid, stream_profile)
                            except Exception as exc:
                                log(f"post-command frame failed: {exc}")
                            break
                    last_sync = now - sync_interval + 0.02

            if farm_watched_udids and devices:
                now_f = time.time()
                live_due = (now_f - last_farm_live) >= 0.45
                full_due = (now_f - last_farm_full) >= 2.5
                if live_due or full_due:
                    farm_snapshots = []
                    for dev in devices:
                        udid = dev["udid"]
                        if udid not in farm_watched_udids or dev.get("status") != "online":
                            continue
                        owner = cloud_devices.get(udid, {}).get("assigned_to")
                        snap = collect_farm_snapshot(full=full_due, owner_id=owner)
                        if snap:
                            farm_snapshots.append({"udid": udid, "snapshot": snap})
                    if farm_snapshots:
                        last_sync = 0.0
                    if live_due:
                        last_farm_live = now_f
                    if full_due:
                        last_farm_full = now_f
                sleep_for = min(sleep_for, 0.35)

            if watched_udids and not commands_ran:
                for dev in devices:
                    udid = dev["udid"]
                    if udid not in watched_udids or dev.get("status") != "online":
                        continue
                    try:
                        if udid in whip_udids:
                            now_thumb = time.time()
                            if now_thumb - last_whip_thumb.get(udid, 0) >= 5.0:
                                upload_watched_frame(udid, stream_profile)
                                last_whip_thumb[udid] = now_thumb
                        else:
                            upload_watched_frame(udid, stream_profile)
                    except Exception as exc:
                        log(f"frame upload failed: {exc}")
                    break
                elapsed = time.time() - loop_start
                sleep_for = max(0.04, float(prof["interval"]) - elapsed)
            else:
                now = time.time()
                for dev in devices:
                    udid = dev["udid"]
                    if dev.get("status") == "online" and (now - last_idle_frame > 90):
                        frame = grab_frame_bytes()
                        if frame:
                            blob, ctype = frame
                            try:
                                upload_frame(udid, blob, ctype)
                            except Exception as exc:
                                log(f"idle frame upload failed: {exc}")
                        last_idle_frame = now
                        break
                sleep_for = SYNC_IDLE if not sync_due else 0.4

        except KeyboardInterrupt:
            stop_all_publishers()
            log("stopped")
            return 0
        except Exception as exc:
            log(f"loop error: {exc}")
            sleep_for = 2.0
        time.sleep(sleep_for)


if __name__ == "__main__":
    raise SystemExit(main())