#!/usr/bin/env python3
"""Answer the current MoltJobs eval item, then print the next prompt.

Usage:
  python3 eval_step.py            # print current/next item only
  python3 eval_step.py b          # MCQ choice id
  python3 eval_step.py '{"k":1}'  # structured JSON/text answer
Does not print secrets.
"""
from __future__ import annotations

import json
import sys
import urllib.error
import urllib.request
from pathlib import Path

ROOT = Path("/Users/alexander/Code/Experiment/MakeMoney")
QID = "eval_mtt6sdnv5chu3amy"
env = {}
for line in (ROOT / ".env").read_text().splitlines():
    if "=" in line and not line.startswith("#"):
        k, v = line.split("=", 1)
        env[k] = v.strip()
H = {
    "Authorization": "Bearer " + env["MOLTJOBS_API_KEY"],
    "User-Agent": "MakeMoney-agent",
    "Accept": "application/json",
}


def req(url, method="GET", data=None):
    h = dict(H)
    body = None
    if data is not None:
        h["Content-Type"] = "application/json"
        body = json.dumps(data).encode()
    try:
        with urllib.request.urlopen(
            urllib.request.Request(url, headers=h, method=method, data=body),
            timeout=30,
        ) as r:
            return r.status, json.loads(r.read())
    except urllib.error.HTTPError as e:
        raw = e.read()
        try:
            return e.code, json.loads(raw)
        except Exception:
            return e.code, raw.decode()[:800]


def show(item):
    print(json.dumps(item, indent=2, default=str)[:12000])


def main():
    if len(sys.argv) > 1:
        raw = sys.argv[1]
        try:
            answer = json.loads(raw)
        except Exception:
            answer = raw
        s, nxt = req(f"https://api.moltjobs.io/v1/evals/{QID}/next")
        item = (nxt or {}).get("data") or nxt
        if not isinstance(item, dict) or item.get("done"):
            print("NO_ITEM", s, nxt)
            return
        item_id = item["itemId"]
        s, res = req(
            f"https://api.moltjobs.io/v1/evals/{QID}/items/{item_id}/answer",
            "POST",
            {"answer": answer},
        )
        data = (res or {}).get("data") if isinstance(res, dict) else res
        print("ANSWERED", item_id, s, json.dumps(data, default=str)[:500])
        req(f"https://api.moltjobs.io/v1/evals/{QID}/heartbeat", "POST", {})
    s, nxt = req(f"https://api.moltjobs.io/v1/evals/{QID}/next")
    item = (nxt or {}).get("data") or nxt
    s2, st = req(f"https://api.moltjobs.io/v1/evals/{QID}/status")
    print("STATUS", json.dumps((st or {}).get("data") or st, default=str)[:800])
    print("NEXT")
    show(item)


if __name__ == "__main__":
    main()
