"""
sebbi_settle.py - Release or Refund client. One file, standard library only.
https://sebbi.pro/release-or-refund

    export SEBBI_KEY=your_key

    from sebbi_settle import agree, deliver, instruction

    job = agree(job="Summarise the Q3 contracts", worker="contracts-agent", amount=40,
                checks=[{"type": "includes", "text": "termination"},
                        {"type": "min_chars", "n": 800}], deadline_hours=24)
    # give job["worker_link"] to the agent; the agent hands in:
    v = deliver(job["code"], work=summary_text, link=job["worker_link"])
    print(v["verdict"])                  # RELEASE, REFUND, TRY_AGAIN or NEEDS_PERSON
    print(instruction(job["code"]))      # what the payment provider acts on
"""
import json
import os
import urllib.parse
import urllib.request

GATE = os.environ.get("SEBBI_GATE", "https://sebbi.pro")


def _call(path, body=None, key=None):
    key = key or os.environ.get("SEBBI_KEY", "")
    h = {"Content-Type": "application/json"}
    if key:
        h["Authorization"] = "Bearer " + key
    req = urllib.request.Request(GATE + "/x/settle/" + path, data=json.dumps(body).encode("utf-8") if body is not None else None,
                                 headers=h, method="POST" if body is not None else "GET")
    try:
        with urllib.request.urlopen(req, timeout=20) as r:
            return json.loads(r.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        return json.loads(e.read().decode("utf-8") or "{}")


def _t(link):
    return urllib.parse.parse_qs(urllib.parse.urlsplit(link or "").query).get("t", [None])[0]


def agree(job, worker, amount, checks, currency="GBP", deadline_hours=72, max_attempts=3, key=None, **kw):
    return _call("agree", dict(kw, job=job, worker=worker, amount=amount, checks=checks, currency=currency,
                               deadline_hours=deadline_hours, max_attempts=max_attempts), key)


def deliver(code, work=None, work_sha256=None, link=None, key=None):
    body = {"code": code, "t": _t(link)}
    if work is not None:
        body["work"] = work
    if work_sha256:
        body["work_sha256"] = work_sha256
    return _call("deliver", body, key if not link else "")


def instruction(code):
    return _call("instruction?code=" + urllib.parse.quote(code))


def settled(code, outcome, provider_ref=None, key=None):
    return _call("settled", {"code": code, "outcome": outcome, "provider_ref": provider_ref}, key)


if __name__ == "__main__":
    import sys
    print(json.dumps(instruction(sys.argv[1]) if len(sys.argv) > 1 else _call("spec"), indent=2))
