#!/usr/bin/env python3
"""Tasks For Humanity desktop worker. Donates spare computer time to open research, safely.

How it works (the same way our own desktop and Azure workers run):
  * Outbound only. This program calls the Tasks For Humanity API; nothing can connect to your computer.
  * Your device token is made here, on your computer, and kept in your user folder. The server only stores its SHA-256 fingerprint.
  * It never runs code it downloads. A work unit is plain data (public paper titles and abstracts from OpenAlex) and the algorithm
    is the one written below, so you can read every line of what runs. Each unit is computed by 3 different devices and only counts
    when 2 of 3 results match exactly.
  * Sandboxed: each unit runs in a separate low priority process with no network access, a memory cap and a time cap.
  * Polite: idle only by default, a CPU cap (default 50 percent), pauses on battery, and you can pause or stop any time.

Usage (Python 3.8 or newer, no installs needed):
  python3 tfh-worker.py                 start donating (idle only, 50 percent CPU)
  python3 tfh-worker.py --cpu 25        use at most about 25 percent of one core
  python3 tfh-worker.py --always        also run while you are using the computer
  python3 tfh-worker.py --pause         pause a running worker (or press Ctrl+C to stop it)
  python3 tfh-worker.py --resume        resume
  python3 tfh-worker.py --status        your device's verified work
  python3 tfh-worker.py --forget        revoke this device and delete its token
Contact: hello@tasksforhumanity.com
"""
import argparse, hashlib, json, os, platform, re, secrets, subprocess, sys, time, urllib.request, urllib.error

VERSION = "1.0.0"
SERVER = "https://eco-preview.trimline-finops.pages.dev"
HOME = os.path.join(os.path.expanduser("~"), ".tasksforhumanity")
CONF = os.path.join(HOME, "worker.json")
PAUSE = os.path.join(HOME, "pause")

# ---------------------------------------------------------------- the algorithm (twin of /eco/tfh/screen-core.js)
def _ascii(s):
    return "".join(c for c in str("" if s is None else s) if ord(c) < 128)

def tok(s):
    return re.sub(r"[^a-z0-9]+", " ", _ascii(s).lower()).split()

def fnv(text):
    h = 0x811C9DC5
    for ch in text:
        h ^= ord(ch)
        h = (h * 0x01000193) & 0xFFFFFFFF
    return h

def _shingles(t, k):
    if not t: return set()
    if len(t) < k: return {fnv(" ".join(t))}
    return {fnv(" ".join(t[i:i + k])) for i in range(len(t) - k + 1)}

def _similar(a, b, thr):
    if not a or not b: return False
    inter = len(a & b)
    return inter * 100 >= thr * (len(a) + len(b) - inter)

def _int(v):
    try: return int(v or 0)
    except (TypeError, ValueError): return 0

def screen_dedup_v1(payload):
    p = payload.get("params") or {}
    kt, ka, jt, ja, min_score = _int(p.get("k_title")) or 3, _int(p.get("k_abs")) or 5, _int(p.get("jt")) or 80, _int(p.get("ja")) or 85, _int(p.get("min_score")) or 4
    terms = [(_ascii(w).lower(), _int(n)) for w, n in (payload.get("terms") or [])]
    recs = []
    for r in payload.get("records") or []:
        tt, ta = tok(r.get("t")), tok(r.get("a"))
        ct, ca = {}, {}
        for w in tt: ct[w] = ct.get(w, 0) + 1
        for w in ta: ca[w] = ca.get(w, 0) + 1
        score = sum(n * min(ct.get(w, 0), 3) * 2 + n * min(ca.get(w, 0), 3) for w, n in terms)
        recs.append({"id": _ascii(r.get("id")), "doi": _ascii(r.get("doi")).lower(), "st": _shingles(tt, kt), "sa": _shingles(ta, ka) if len(ta) >= 20 else set(), "score": score})
    parent = list(range(len(recs)))
    def find(i):
        while parent[i] != i:
            parent[i] = parent[parent[i]]; i = parent[i]
        return i
    for i in range(len(recs)):
        for j in range(i + 1, len(recs)):
            a, b = recs[i], recs[j]
            if (a["doi"] and a["doi"] == b["doi"]) or _similar(a["st"], b["st"], jt) or _similar(a["sa"], b["sa"], ja):
                x, y = find(i), find(j)
                if x != y: parent[max(x, y)] = min(x, y)
    canon = {}
    for i, r in enumerate(recs):
        root, c = find(i), canon.get(find(i))
        if c is None or (r["score"] > c["score"] if r["score"] != c["score"] else r["id"] < c["id"]): canon[root] = r
    kept, dups = [], []
    for i, r in enumerate(recs):
        c = canon[find(i)]
        if c is r: kept.append([r["id"], r["score"], 1 if r["score"] >= min_score else 0])
        else: dups.append([r["id"], c["id"]])
    kept.sort(key=lambda k: (-k[1], k[0]))
    dups.sort(key=lambda d: d[0])
    return json.dumps({"v": 1, "kept": kept, "dups": dups}, separators=(",", ":"))

ALGOS = {"screen-dedup-v1": screen_dedup_v1}

def _valid_unit(u):
    p = u.get("payload") if isinstance(u, dict) else None
    if not isinstance(p, dict) or u.get("kind") not in ALGOS or p.get("algo") != u.get("kind"): return False
    recs = p.get("records")
    if not isinstance(recs, list) or not 2 <= len(recs) <= 400: return False
    return len(json.dumps(p)) <= 400000

# ---------------------------------------------------------------- sandboxed child: one unit, stdin in, stdout out, no network
def child():
    import socket
    def _no_net(*a, **k): raise OSError("network is disabled in the Tasks For Humanity sandbox")
    socket.socket = _no_net; socket.create_connection = _no_net; socket.getaddrinfo = _no_net
    unit = json.loads(sys.stdin.read())
    sys.stdout.write(ALGOS[unit["kind"]](unit["payload"]))

def _limits():
    try:
        import resource
        resource.setrlimit(resource.RLIMIT_AS, (768 * 1024 * 1024, 768 * 1024 * 1024))
        resource.setrlimit(resource.RLIMIT_CPU, (300, 300))
        resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32))
        os.nice(19)
    except Exception:
        pass

def run_unit(unit, cpu):
    start = time.time()
    kw = {}
    if os.name == "nt":
        kw["creationflags"] = 0x00000040 | 0x08000000   # IDLE_PRIORITY_CLASS, CREATE_NO_WINDOW
    else:
        kw["preexec_fn"] = _limits
    proc = subprocess.Popen([sys.executable, "-I", os.path.abspath(__file__), "--child"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, **kw)
    out, _ = proc.communicate(json.dumps(unit).encode(), timeout=360)
    if proc.returncode != 0: raise RuntimeError("the sandboxed unit did not finish")
    ms = int((time.time() - start) * 1000)
    # CPU cap: rest in proportion so the average stays under the cap
    if 0 < cpu < 100: time.sleep(ms / 1000 * (100 - cpu) / cpu)
    return out.decode(), ms

# ---------------------------------------------------------------- polite: idle, battery
def idle_seconds():
    try:
        s = platform.system()
        if s == "Windows":
            import ctypes
            class LII(ctypes.Structure): _fields_ = [("cbSize", ctypes.c_uint), ("dwTime", ctypes.c_uint)]
            li = LII(); li.cbSize = ctypes.sizeof(LII)
            ctypes.windll.user32.GetLastInputInfo(ctypes.byref(li))
            return (ctypes.windll.kernel32.GetTickCount() - li.dwTime) / 1000.0
        if s == "Darwin":
            o = subprocess.run(["ioreg", "-c", "IOHIDSystem"], capture_output=True, text=True, timeout=5).stdout
            m = re.search(r'"HIDIdleTime" = (\d+)', o)
            return int(m.group(1)) / 1e9 if m else None
        o = subprocess.run(["xprintidle"], capture_output=True, text=True, timeout=5)
        if o.returncode == 0: return int(o.stdout.strip()) / 1000.0
    except Exception:
        return None
    return None

def busy():
    """True when the computer is in use: recent input, or (where input time is unknown) a high load average."""
    idle = idle_seconds()
    if idle is not None: return idle < 120
    try: return os.getloadavg()[0] > (os.cpu_count() or 2) * 0.5
    except Exception: return False

def on_battery():
    try:
        s = platform.system()
        if s == "Windows":
            import ctypes
            class SPS(ctypes.Structure): _fields_ = [("ACLineStatus", ctypes.c_byte), ("BatteryFlag", ctypes.c_byte), ("BatteryLifePercent", ctypes.c_byte), ("r", ctypes.c_byte), ("a", ctypes.c_ulong), ("b", ctypes.c_ulong)]
            st = SPS(); ctypes.windll.kernel32.GetSystemPowerStatus(ctypes.byref(st)); return st.ACLineStatus == 0
        if s == "Darwin":
            return "Battery Power" in subprocess.run(["pmset", "-g", "batt"], capture_output=True, text=True, timeout=5).stdout
        for d in os.listdir("/sys/class/power_supply"):
            f = os.path.join("/sys/class/power_supply", d, "online")
            if d.startswith(("AC", "ADP", "ACAD")) and os.path.exists(f): return open(f).read().strip() == "0"
    except Exception:
        return False
    return False

# ---------------------------------------------------------------- token storage (Windows: encrypted for your user with DPAPI)
def _dpapi(data, protect):
    import ctypes, ctypes.wintypes as w
    class BLOB(ctypes.Structure): _fields_ = [("cbData", w.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))]
    buf = ctypes.create_string_buffer(data, len(data)); i = BLOB(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_char))); o = BLOB()
    fn = ctypes.windll.crypt32.CryptProtectData if protect else ctypes.windll.crypt32.CryptUnprotectData
    if not fn(ctypes.byref(i), None, None, None, None, 0, ctypes.byref(o)): raise OSError("DPAPI failed")
    out = ctypes.string_at(o.pbData, o.cbData); ctypes.windll.kernel32.LocalFree(o.pbData); return out

def save_conf(c):
    os.makedirs(HOME, exist_ok=True)
    c = dict(c)
    if os.name == "nt":
        import base64
        c["token_dpapi"] = base64.b64encode(_dpapi(c.pop("token").encode(), True)).decode()
    with open(CONF, "w") as f: json.dump(c, f)
    if os.name != "nt": os.chmod(CONF, 0o600)

def load_conf():
    if not os.path.exists(CONF): return None
    c = json.load(open(CONF))
    if "token_dpapi" in c:
        import base64
        c["token"] = _dpapi(base64.b64decode(c.pop("token_dpapi")), False).decode()
    return c

# ---------------------------------------------------------------- API
def api(path, body=None, token=None, method=None):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(SERVER + "/tfh/api/compute" + path, data=data, method=method or ("POST" if data is not None else "GET"),
                                 headers={"Content-Type": "application/json", "User-Agent": "TasksForHumanity-worker/" + VERSION})
    if token: req.add_header("Authorization", "Bearer " + token)
    try:
        with urllib.request.urlopen(req, timeout=40) as r: return json.loads(r.read() or b"{}")
    except urllib.error.HTTPError as e:
        try: msg = json.loads(e.read()).get("error")
        except Exception: msg = None
        raise RuntimeError(msg or ("server said " + str(e.code)))

def register(label):
    token = "tfhc_" + secrets.token_hex(32)
    r = api("/register", {"token_sha": hashlib.sha256(token.encode()).hexdigest(), "kind": "desktop", "label": label})
    save_conf({"token": token, "device_id": r.get("device_id"), "server": SERVER})
    return load_conf()

def main():
    ap = argparse.ArgumentParser(description="Tasks For Humanity desktop worker")
    ap.add_argument("--child", action="store_true", help=argparse.SUPPRESS)
    ap.add_argument("--cpu", type=int, default=50, help="CPU cap in percent of one core (5 to 100, default 50)")
    ap.add_argument("--always", action="store_true", help="also run while the computer is in use")
    ap.add_argument("--on-battery", action="store_true", help="keep running on battery power")
    ap.add_argument("--label", default=platform.system().lower() + " desktop", help="a name for this device")
    ap.add_argument("--pause", action="store_true"); ap.add_argument("--resume", action="store_true")
    ap.add_argument("--status", action="store_true"); ap.add_argument("--forget", action="store_true")
    ap.add_argument("--once", action="store_true", help="do one unit and exit (for testing)")
    a = ap.parse_args()
    if a.child: return child()
    if a.pause: os.makedirs(HOME, exist_ok=True); open(PAUSE, "w").close(); return print("Paused. Run with --resume to continue.")
    if a.resume:
        if os.path.exists(PAUSE): os.remove(PAUSE)
        return print("Resumed.")
    c = load_conf()
    if a.forget:
        if c:
            try: api("/revoke", {}, c["token"])
            except Exception as e: print("Could not reach the server:", e)
            os.remove(CONF)
        return print("This device is revoked and its token deleted.")
    if a.status:
        if not c: return print("Not registered yet. Run without options to start.")
        return print(json.dumps(api("/me", token=c["token"]), indent=2))
    cpu = min(max(a.cpu, 5), 100)
    if not c:
        c = register(a.label[:40])
        print("Registered this computer. Only a fingerprint of its token was sent.")
    print("Tasks For Humanity worker %s. CPU cap %d%%, %s. Ctrl+C stops it, --pause pauses it." % (VERSION, cpu, "always on" if a.always else "only while idle"))
    last_hb = 0; said = None
    def wait(why, secs):
        nonlocal said
        if said != why: print(why); said = why
        time.sleep(secs)
    while True:
        try:
            if time.time() - last_hb > 60:
                last_hb = time.time()
                try: api("/heartbeat", {"info": {"os": platform.system(), "cores": os.cpu_count(), "cap": cpu, "app": "worker " + VERSION}}, c["token"])
                except Exception: pass   # a heartbeat is a courtesy; a busy server never stops the work
            if os.path.exists(PAUSE):
                if a.once: return print("Paused. Run with --resume first.")
                wait("Paused. Run with --resume to continue.", 15); continue
            if not a.on_battery and on_battery(): wait("On battery power, waiting for a charger.", 60); continue
            if not a.always and busy(): wait("Computer in use, waiting until it is idle.", 30); continue
            said = None
            units = api("/claim", {"max": 1}, c["token"]).get("units") or []
            if not units:
                if a.once: return print("No work right now.")
                time.sleep(90); continue
            for u in units:
                if not _valid_unit(u): continue
                out, ms = run_unit(u, cpu)
                r = api("/submit", {"unit": u["id"], "output": out, "ms": ms}, c["token"])
                print("Unit done in %.1f s, %s." % (ms / 1000, {"verified": "verified by 2 of 3 devices", "open": "waiting for other devices to agree"}.get(r.get("unit_status"), r.get("unit_status"))))
            if a.once: return
        except KeyboardInterrupt:
            return print("\nStopped. Thank you for helping.")
        except Exception as e:
            print("Will retry shortly:", e); time.sleep(60)

if __name__ == "__main__":
    try: main()
    except KeyboardInterrupt: print("\nStopped. Thank you for helping.")
