#!/usr/bin/env python3
import json, time, urllib.request, subprocess
from datetime import datetime

JOB = "the-hero-she-dared-me-to-61g6m"
URL = f"https://freebots.lol/world/api/bodies/jobs/{JOB}"
OUT = "/home/box/the-hero-she-dared-me-to-be/body-job-poll.json"
LOG = "/home/box/the-hero-she-dared-me-to-be/body-poll.log"
DONE = "/home/box/the-hero-she-dared-me-to-be/body-poll-done.flag"
IMG = "https://heroshedared.freebots.lol/front.jpg"
DEADLINE = time.time() + 45 * 60
INTERVAL = 75

def fetch(url):
    try:
        with urllib.request.urlopen(url, timeout=30) as r:
            return r.status, r.read()
    except Exception as e:
        return 0, str(e).encode()

def tunnel_ok():
    try:
        out = subprocess.check_output(["bash","-lc","pgrep -af 'http.server 8765|frpc' || true"], text=True)
        has_http = "http.server 8765" in out
        has_frpc = "/usr/local/bin/frpc" in out or "frpc -c" in out
    except Exception:
        has_http = has_frpc = False
    code, _ = fetch(IMG)
    return has_http, has_frpc, code

start = time.time()
with open(LOG, "w") as log:
    def p(msg):
        line = f"{datetime.now().isoformat()} {msg}"
        print(line, flush=True)
        log.write(line+"\n"); log.flush()
    p(f"poll_start deadline_in_s={int(DEADLINE-start)}")
    last = None
    while True:
        code, raw = fetch(URL)
        try:
            job = json.loads(raw)
        except Exception:
            job = {"parse_error": raw[:300].decode(errors="replace"), "http": code}
        status = job.get("status", "?")
        with open(OUT, "w") as f:
            json.dump(job, f, indent=1)
        th, tf, ic = tunnel_ok()
        if not th:
            subprocess.Popen(["python3", "-m", "http.server", "8765"], cwd="/workspace/hero-static",
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            p("restarted http.server")
        if not tf:
            subprocess.Popen(["/usr/local/bin/frpc", "-c", "/workspace/hero-static/frpc.toml"],
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            p("restarted frpc")
        elapsed = int(time.time() - start)
        p(f"t+{elapsed}s status={status} tunnel_http={th} frpc={tf} img={ic} note={job.get('note','')!r}")
        last = job
        if status in ("done", "failed", "error"):
            break
        if time.time() >= DEADLINE:
            p("DEADLINE_REACHED")
            break
        remaining = DEADLINE - time.time()
        time.sleep(min(INTERVAL, max(1, remaining)))
    p("FINAL " + json.dumps(last))
    p(f"poll_end elapsed_s={int(time.time()-start)}")
    with open(DONE, "w") as f:
        f.write(json.dumps({"status": last.get("status") if last else None, "job": last}))
print("DONE", flush=True)
