#!/usr/bin/env python3
"""pyblox-com-agent - links this Pi or Linux machine to your own pyblox.com account.

  pyblox-com-agent pair CODE [--force]       pair with the one-time code from pyblox.com Settings > Devices
  pyblox-com-agent run                       keep checking in with pyblox.com (every 60 s) and run confirmed read-only checks
  pyblox-com-agent status                    show local settings (never the token)
  pyblox-com-agent jobs [on|off]             show, or switch, whether confirmed read-only checks may run here
  pyblox-com-agent agentic ROUTE             relay one agentic request to pyblox.com (JSON on stdin, JSON on stdout; never the token)
  pyblox-com-agent service                   print a systemd user unit so it starts on boot
  pyblox-com-agent unpair                    forget the token on this machine

This is the pyblox.com device agent (v632). It is separate from the pi.osibytes.com
hub agent (pyblox-agent). It never reads or writes ~/.config/pyblox-agent/.
It only talks out to https://pyblox.com on port 443. No ports are opened on this machine
and no SSH keys are given out. Config: ~/.config/pyblox-com-agent/config.json (mode 600).

Agentic mode (v632): after a person confirms a step on pyblox.com, the step reaches this agent as a one-time job.
The agent runs ONLY these read-only checks, with fixed commands and no shell:
  device.status, device.uptime, device.df, device.docker_ps, device.service_status
Anything else (restart, stop, unknown, expired, or this device set to "Nothing") is refused and reported as refused.
Every job and every relay call is written to ~/.config/pyblox-com-agent/agentic-audit.jsonl (mode 600; no output, no token).
"""
import json, os, platform, re, shutil, socket, ssl, subprocess, sys, time, urllib.error, urllib.parse, urllib.request

VERSION = "1.0.3-v632"
NAME = "pyblox-com-agent"
AGENTIC_JOBS = True          # this agent can run confirmed read-only jobs (the hub looks for this name)
HUB = "https://pyblox.com"
if os.environ.get("PYBLOX_AGENT_TEST_HUB", "").startswith("http://127.0.0.1:"):
    HUB = os.environ["PYBLOX_AGENT_TEST_HUB"]  # local test only, never a remote http URL

OUT_MAX = 65536
JOB_POLL_SECS = 20
# Routes the hub may relay. jobs, report, link_code, set_device_kind, unlink and audit_verify are NOT relayable.
RELAY_ROUTES = {"tools": "GET", "run": "GET", "runs": "GET", "audit": "GET",
                "plan": "POST", "confirm": "POST", "stop": "POST", "member_link": "POST", "audit_push": "POST"}
SERVICE_RE = re.compile(r"^[A-Za-z0-9@][A-Za-z0-9@._:-]{0,63}$")
ID_RE = re.compile(r"^[A-Za-z0-9_]{1,40}$")
MEMBER_RE = re.compile(r"^pmt_[A-Za-z0-9_-]{20,80}$")
SAFE_ENV = {"PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C", "LC_ALL": "C"}


def cfg_dir():
    return os.path.join(os.path.expanduser("~"), ".config", "pyblox-com-agent")


def cfg_path():
    return os.path.join(cfg_dir(), "config.json")


def load():
    try:
        with open(cfg_path(), "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return {}


def save(cfg):
    p = cfg_path()
    os.makedirs(os.path.dirname(p), mode=0o700, exist_ok=True)
    tmp = p + ".tmp"
    fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w", encoding="utf-8") as f:
        json.dump(cfg, f, indent=2)
    os.replace(tmp, p)
    os.chmod(p, 0o600)


def info():
    os_name = platform.system()
    try:
        with open("/etc/os-release", encoding="utf-8") as f:
            for line in f:
                if line.startswith("PRETTY_NAME="):
                    os_name = line.split("=", 1)[1].strip().strip('"')
    except Exception:
        pass
    return {"hostname": socket.gethostname()[:80], "os": os_name[:80], "arch": platform.machine()[:40],
            "python": platform.python_version(), "agent_version": VERSION, "kind": "pi"}


def http_json(url, body=None, token=None, method="POST", headers=None, timeout=30):
    data = json.dumps(body if body is not None else {}).encode("utf-8") if method == "POST" else None
    req = urllib.request.Request(url, data=data, method=method,
                                 headers={"Content-Type": "application/json", "User-Agent": f"{NAME}/{VERSION}"})
    if token:
        req.add_header("Authorization", "Bearer " + token)
        req.add_header("X-PBX-Device-Token", token)  # some PHP setups drop Authorization
    for k, v in (headers or {}).items():
        req.add_header(k, v)
    ctx = ssl.create_default_context()
    try:
        with urllib.request.urlopen(req, timeout=timeout, context=ctx if url.startswith("https://") else None) as r:
            raw = r.read(2_000_000).decode("utf-8", "replace")
            try:
                return r.status, json.loads(raw or "{}")
            except Exception:
                return r.status, {"ok": False, "error": f"HTTP {r.status} (not JSON)"}
    except urllib.error.HTTPError as e:
        try:
            return e.code, json.loads(e.read(2_000_000).decode("utf-8") or "{}")
        except Exception:
            return e.code, {"error": f"HTTP {e.code}"}


def call(route, body, token=None):
    return http_json(f"{HUB}/device_agent.php?r={route}", body, token)


# ---------------------------------------------------------------- local audit (append-only file, never holds output or the token)
def _state_lock():
    try:
        import fcntl
    except Exception:
        return None, None
    os.makedirs(cfg_dir(), mode=0o700, exist_ok=True)
    fd = os.open(os.path.join(cfg_dir(), "agentic-state.json"), os.O_RDWR | os.O_CREAT, 0o600)
    fcntl.flock(fd, fcntl.LOCK_EX)
    return fd, fcntl


def _read_state(fd):
    try:
        os.lseek(fd, 0, 0)
        return json.loads(os.read(fd, 4096).decode("utf-8") or "{}")
    except Exception:
        return {}


def _write_state(fd, st):
    os.lseek(fd, 0, 0)
    os.ftruncate(fd, 0)
    os.write(fd, json.dumps(st).encode("utf-8"))


def audit(event, **f):
    """Append one line. event: job_start, job_end, job_refused, relay. Never the job output, never a token."""
    fd, fcntl = _state_lock()
    try:
        st = _read_state(fd) if fd is not None else {}
        seq = int(st.get("seq", 0)) + 1
        st["seq"] = seq
        line = {"seq": seq, "ts": int(time.time()), "event": event}
        for k, v in f.items():
            if v is not None:
                line[k] = str(v)[:200] if not isinstance(v, int) else v
        p = os.path.join(cfg_dir(), "agentic-audit.jsonl")
        fd2 = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
        with os.fdopen(fd2, "a", encoding="utf-8") as fh:
            fh.write(json.dumps(line, sort_keys=True) + "\n")
        if fd is not None:
            _write_state(fd, st)
        return seq
    finally:
        if fd is not None:
            os.close(fd)


_PUSH_MAP = {"job_start": "local_job_start", "job_end": "local_job_end", "job_refused": "local_refused"}


def push_audit(token):
    """Send job lines that pyblox.com has not got yet (at most 50). Best effort; the local file stays the record."""
    fd, fcntl = _state_lock()
    try:
        st = _read_state(fd) if fd is not None else {}
        pushed = int(st.get("pushed", 0))
        out, last = [], pushed
        try:
            with open(os.path.join(cfg_dir(), "agentic-audit.jsonl"), encoding="utf-8") as fh:
                for raw in fh:
                    try:
                        e = json.loads(raw)
                    except Exception:
                        continue
                    if int(e.get("seq", 0)) <= pushed:
                        continue
                    last = max(last, int(e["seq"]))
                    act = _PUSH_MAP.get(e.get("event"))
                    if act and len(out) < 50:
                        out.append({"seq": e["seq"], "ts": e["ts"], "action": act, "run_id": e.get("run_id", ""), "step_id": e.get("step_id", ""),
                                    "tool": e.get("tool", ""), "detail": e.get("detail", "")})
                    if len(out) >= 50:
                        break
        except FileNotFoundError:
            return
        if not out:
            if last > pushed and fd is not None:
                st["pushed"] = last
                _write_state(fd, st)
            return
        last = max(x["seq"] for x in out)
        code, res = http_json(f"{HUB}/agentic_device.php?r=audit_push", {"entries": out}, token, timeout=20)
        if code == 200 and res.get("ok") and fd is not None:
            st["pushed"] = last
            _write_state(fd, st)
    except Exception:
        pass
    finally:
        if fd is not None:
            os.close(fd)


# ---------------------------------------------------------------- the five read-only checks (fixed commands, no shell)
def _run(argv, timeout=20):
    try:
        r = subprocess.run(argv, capture_output=True, text=True, timeout=timeout, env=SAFE_ENV, stdin=subprocess.DEVNULL)
        return r.returncode, ((r.stdout or "") + (r.stderr or ""))
    except FileNotFoundError:
        return 127, f"{argv[0]} is not installed on this device"
    except subprocess.TimeoutExpired:
        return 124, f"{argv[0]} took too long (over {timeout} s)"


def _cut(s):
    b = s.encode("utf-8", "replace")
    return s if len(b) <= OUT_MAX else b[:OUT_MAX - 8].decode("utf-8", "ignore") + "\n[cut]"


def _uptime_text():
    try:
        with open("/proc/uptime", encoding="utf-8") as f:
            secs = int(float(f.read().split()[0]))
    except Exception:
        return "unknown"
    d, rem = divmod(secs, 86400)
    h, rem = divmod(rem, 3600)
    return f"up {d} d {h} h {rem // 60} min"


def _load_text():
    try:
        return " ".join(open("/proc/loadavg", encoding="utf-8").read().split()[:3])
    except Exception:
        return "unknown"


def tool_uptime(_args):
    return 0, f"{_uptime_text()}; load {_load_text()}"


def tool_status(_args):
    lines = [f"Host: {socket.gethostname()}", f"OS: {info()['os']}", f"Kernel: {platform.release()} ({platform.machine()})",
             f"Uptime: {_uptime_text()}", f"Load (1/5/15 min): {_load_text()}"]
    try:
        mem = {}
        for ln in open("/proc/meminfo", encoding="utf-8"):
            k, v = ln.split(":", 1)
            mem[k] = int(v.split()[0])
        tot, avail = mem.get("MemTotal", 0), mem.get("MemAvailable", 0)
        if tot:
            lines.append(f"Memory: {(tot - avail) // 1024} MB used of {tot // 1024} MB")
    except Exception:
        pass
    try:
        u = shutil.disk_usage("/")
        lines.append(f"Disk /: {u.used // 2**20} MB used of {u.total // 2**20} MB ({u.used * 100 // max(1, u.total)}%)")
    except Exception:
        pass
    try:
        t = int(open("/sys/class/thermal/thermal_zone0/temp", encoding="utf-8").read().strip())
        lines.append(f"CPU temperature: {t / 1000:.1f} C")
    except Exception:
        pass
    lines.append(f"Agent: {NAME} {VERSION}")
    return 0, "\n".join(lines)


def tool_df(_args):
    code, out = _run(["df", "-hP", "-x", "tmpfs", "-x", "devtmpfs", "-x", "squashfs", "-x", "overlay"])
    if code == 127:
        u = shutil.disk_usage("/")
        return 0, f"/ {u.used // 2**20} MB used of {u.total // 2**20} MB"
    return code, out


def tool_docker_ps(_args):
    return _run(["docker", "ps", "--format", "table {{.Names}}\t{{.Image}}\t{{.Status}}"], timeout=25)


def tool_service_status(args):
    name = str((args or {}).get("name", ""))
    if not SERVICE_RE.match(name):
        return 2, "refused: that service name is not allowed"
    props = "Id,Description,LoadState,ActiveState,SubState,UnitFileState,MainPID,ActiveEnterTimestamp"
    code, out = _run(["systemctl", "show", name, "--no-pager", "-p", props])
    if code == 0 and "LoadState=not-found" in out:
        code, out2 = _run(["systemctl", "--user", "show", name, "--no-pager", "-p", props])
        if code == 0 and "LoadState=not-found" not in out2:
            out = "(user service)\n" + out2
    return code, out


ALLOWED_TOOLS = {"device.status": tool_status, "device.uptime": tool_uptime, "device.df": tool_df,
                 "device.docker_ps": tool_docker_ps, "device.service_status": tool_service_status}


# ---------------------------------------------------------------- jobs
def jobs_enabled(cfg):
    return AGENTIC_JOBS and cfg.get("agentic_jobs", True) is not False


def report(token, job_id, status, code, text):
    body = {"job_id": job_id, "status": status, "exit_code": int(code), "output": _cut(text)}
    for _ in range(2):
        try:
            st, res = http_json(f"{HUB}/agentic_device.php?r=report", body, token, timeout=30)
            if st == 200 and res.get("ok"):
                return True
        except Exception:
            time.sleep(2)
    return False


def run_job(token, job, access):
    jid, rid, sid = str(job.get("job_id", "")), str(job.get("run_id", "")), str(job.get("step_id", ""))
    tool = str(job.get("tool", ""))[:40]
    if not ID_RE.match(jid):
        return False
    why = ""
    if not (ID_RE.match(rid) and ID_RE.match(sid)):
        why = "bad ids"
    elif tool not in ALLOWED_TOOLS:
        why = "not an allowed read-only check on this device"
    elif access == "none":
        why = "this device is set to Nothing in pyblox.com"
    elif int(job.get("expires_at", 0) or 0) < time.time():
        why = "the job expired before it ran"
    elif not isinstance(job.get("args", {}), dict):
        why = "bad arguments"
    if why:
        audit("job_refused", run_id=rid, step_id=sid, tool=tool, job_id=jid, detail=why)
        report(token, jid, "failed", 126, "refused: " + why)
        return True
    audit("job_start", run_id=rid, step_id=sid, tool=tool, job_id=jid)
    t0 = time.time()
    try:
        code, text = ALLOWED_TOOLS[tool](job.get("args") or {})
    except Exception as e:
        code, text = 1, f"the check failed ({type(e).__name__})"
    status = "done" if code == 0 else "failed"
    audit("job_end", run_id=rid, step_id=sid, tool=tool, job_id=jid, detail=f"{status} exit={code} bytes={len(text)} secs={int(time.time() - t0)}")
    report(token, jid, status, code, text)
    return True


def poll_jobs(cfg):
    if not jobs_enabled(cfg):
        return 0
    st, res = http_json(f"{HUB}/agentic_device.php?r=jobs", {}, cfg["token"], timeout=20)
    if st != 200 or not res.get("ok"):
        return 0
    n = 0
    for job in (res.get("jobs") or [])[:3]:
        if isinstance(job, dict) and run_job(cfg["token"], job, str(res.get("access", "none"))):
            n += 1
    if n:
        push_audit(cfg["token"])
    return n


# ---------------------------------------------------------------- commands
def cmd_pair(args):
    force = "--force" in args
    args = [a for a in args if a != "--force"]
    if not args:
        sys.exit(f"usage: {NAME} pair CODE [--force]")
    code = args[0]
    old = load()
    if old.get("token") and not force:
        st, _res = call("heartbeat", {"info": info()}, old["token"])
        if st == 200:
            print(f"Already paired as \"{old.get('name', '')}\" ({old.get('device_id')}). Nothing changed. Use --force to pair again.")
            return
        print("The saved pairing no longer works; pairing again with the new code.")
    i = info()
    code_st, res = call("pair", {"code": code, "info": i})
    if code_st != 200 or not res.get("ok"):
        sys.exit("Pairing failed: " + str(res.get("error") or code_st))
    save({"hub": HUB, "device_id": res["device_id"], "token": res["token"], "name": res.get("name", ""),
          "paired_at": int(time.time())})
    print(f"Paired as \"{res.get('name', '')}\" ({res['device_id']}). It now shows in pyblox.com Settings > Devices.")
    print(f"Keep it checking in:  {NAME} run    (or: {NAME} service)")


def cmd_run(_args):
    cfg = load()
    if not cfg.get("token"):
        sys.exit(f"Not paired. Run: {NAME} pair CODE")
    once = bool(os.environ.get("PYBLOX_AGENT_TEST_ONCE")) and HUB.startswith("http://127.0.0.1:")
    hb_wait, next_hb, hb_ok = 60, 0.0, False
    while True:
        cfg = load() or cfg
        now = time.time()
        if now >= next_hb:
            try:
                st, res = call("heartbeat", {"info": info()}, cfg["token"])
                if st == 401:
                    print("pyblox.com says this device was removed. Pair again with a new code.", flush=True)
                    sys.exit(3)
                hb_ok = st == 200
                hb_wait = int(res.get("poll_secs") or 60) if hb_ok else min(hb_wait * 2, 600)
            except SystemExit:
                raise
            except Exception as e:
                print(f"check-in failed ({type(e).__name__}); retrying", flush=True)
                hb_ok = False
                hb_wait = min(hb_wait * 2, 600)
            next_hb = time.time() + max(30, min(hb_wait, 600))
        ran = 0
        if hb_ok:
            try:
                ran = poll_jobs(cfg)
            except Exception as e:
                print(f"job check failed ({type(e).__name__})", flush=True)
        if once:
            return
        time.sleep(4 if ran else JOB_POLL_SECS)


def cmd_status(_args):
    cfg = load()
    print(json.dumps({"hub": cfg.get("hub", HUB), "paired": bool(cfg.get("token")), "device_id": cfg.get("device_id"),
                      "name": cfg.get("name"), "agent_version": VERSION, "agentic_jobs": jobs_enabled(cfg),
                      "config": cfg_path()}, indent=2))


def cmd_jobs(args):
    cfg = load()
    if args and args[0] in ("on", "off"):
        cfg["agentic_jobs"] = args[0] == "on"
        save(cfg)
    print(f"Confirmed read-only checks are {'ON' if jobs_enabled(cfg) else 'OFF'} on this device (agent {VERSION}).")


def cmd_agentic(args):
    """Relay one agentic request. stdin: a JSON object (optional "_member": the person's hub link token). stdout: JSON, with "_http"."""
    def out(obj, code):
        print(json.dumps(obj, ensure_ascii=False))
        sys.exit(code)
    route = args[0] if args else ""
    if route not in RELAY_ROUTES:
        out({"ok": False, "error": "route not allowed", "allowed": sorted(RELAY_ROUTES)}, 2)
    cfg = load()
    token = cfg.get("token")
    if not token:
        out({"ok": False, "error": f"not paired; run {NAME} pair CODE"}, 1)
    body = {}
    if not sys.stdin.isatty():
        raw = sys.stdin.buffer.read(262145)
        if len(raw) > 262144:
            out({"ok": False, "error": "request too large"}, 2)
        if raw.strip():
            try:
                body = json.loads(raw.decode("utf-8"))
            except Exception:
                out({"ok": False, "error": "stdin is not JSON"}, 2)
    if not isinstance(body, dict):
        out({"ok": False, "error": "stdin must be a JSON object"}, 2)
    member = body.pop("_member", None)
    headers = {}
    if member is not None:
        if not isinstance(member, str) or not MEMBER_RE.match(member):
            out({"ok": False, "error": "bad member token"}, 2)
        headers["X-PBX-Member"] = member
    method = RELAY_ROUTES[route]
    url = f"{HUB}/agentic_device.php?r={route}"
    if method == "GET":
        q = {k: v for k, v in body.items() if re.match(r"^[a-z_]{1,24}$", str(k)) and isinstance(v, (str, int)) and len(str(v)) <= 80}
        if q:
            url += "&" + urllib.parse.urlencode(q)
    try:
        st, res = http_json(url, body if method == "POST" else None, token, method=method, headers=headers, timeout=130 if route == "plan" else 40)
    except Exception as e:
        out({"ok": False, "error": f"could not reach pyblox.com ({type(e).__name__})", "_http": 0}, 1)
    if not isinstance(res, dict):
        res = {"ok": False, "error": f"HTTP {st}"}
    res["_http"] = st
    try:
        audit("relay", detail=f"{route} http={st}")
    except Exception:
        pass
    out(res, 0 if 200 <= st < 300 and res.get("ok", True) else 1)


def cmd_service(_args):
    exe = os.path.abspath(sys.argv[0])
    print(f"""# Save as ~/.config/systemd/user/pyblox-com-agent.service, then:
#   systemctl --user daemon-reload && systemctl --user enable --now pyblox-com-agent
# To keep it running when nobody is logged in, an admin runs once: loginctl enable-linger $USER
[Unit]
Description=pyblox.com device agent
After=network-online.target

[Service]
ExecStart={exe} run
Restart=always
RestartSec=30

[Install]
WantedBy=default.target""")


def cmd_unpair(_args):
    cfg = load()
    for k in ("token", "device_id"):
        cfg.pop(k, None)
    save(cfg)
    print("Token forgotten on this machine. Remove the device in pyblox.com Settings > Devices too.")


def main():
    cmds = {"pair": cmd_pair, "run": cmd_run, "status": cmd_status, "jobs": cmd_jobs, "agentic": cmd_agentic, "service": cmd_service, "unpair": cmd_unpair}
    if len(sys.argv) < 2 or sys.argv[1] not in cmds:
        print(__doc__)
        sys.exit(2)
    cmds[sys.argv[1]](sys.argv[2:])


if __name__ == "__main__":
    main()
