"""mizan_min: the smallest honest MIZAN client. Standard library only. Copied into every starter kit.

MIZAN is the second ledger of the economy. Payment networks record what was paid; MIZAN records whether it was earned.

    check(subject, payee=None, rule=None) -> dict   GET /api/check/{subject}; the signed answer, as served
    verify_token(token) -> dict                      offline Ed25519 against the published key set (fetched once, pinned by kid)
    compile_rule(words) -> dict                      POST /api/requirements/compile; no key, nothing written
    guard(fn, rule=None, mode="advise")              wrap pay/hire/release: advise logs, enforce blocks on REFUSE

The real SDK has the same names with more: `pip install https://mizan.market/skill/mizan_sdk-0.11.3-py3-none-any.whl` (Python) / `npm install https://mizan.market/skill/mizan-agent-tools.tgz`.
Nothing here mints a proof or moves money.
"""
import base64, hashlib, json, os, sys, time, urllib.error, urllib.parse, urllib.request

API = os.environ.get("MIZAN_API", "https://studio.mizan.market")
KEYS_URL = "https://mizan.market/.well-known/mizan-keys.json"
UA = "mizan-starter-kit/2 (+https://mizan.market/kits/)"


def call(path, body=None, key=None, timeout=30):
    """GET (no body) or POST JSON. MIZAN answers errors in JSON too: {"error": {"code", "message", "next", "request_id"}}."""
    url = path if path.startswith("http") else API + path
    headers = {"Content-Type": "application/json", "User-Agent": UA}
    if key:
        headers["Authorization"] = "Bearer " + key
    data = None if body is None else json.dumps(body).encode()
    req = urllib.request.Request(url, data=data, headers=headers, method="POST" if data is not None else "GET")
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return json.load(r)
    except urllib.error.HTTPError as e:
        try:
            return json.load(e)
        except Exception:
            return {"error": {"code": "http_%d" % e.code, "message": str(e), "next": "retry, or read https://mizan.market/verdict/codes/"}}
    except Exception as e:  # network: fail closed, never ALLOW
        return {"error": {"code": "unreachable", "message": str(e), "next": "retry; a payment waits, it is not released"}}


def b64u(s):
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))


# --- Ed25519 (RFC 8032) verify, pure Python; used when `cryptography` is not installed -------------------------------
_q = 2 ** 255 - 19
_L = 2 ** 252 + 27742317777372353535851937790883648493
_d = -121665 * pow(121666, _q - 2, _q) % _q


def _add(P, Q):
    A = (P[1] - P[0]) * (Q[1] - Q[0]) % _q
    B = (P[1] + P[0]) * (Q[1] + Q[0]) % _q
    C = 2 * P[3] * Q[3] * _d % _q
    D = 2 * P[2] * Q[2] % _q
    E, F, G, H = B - A, D - C, D + C, B + A
    return (E * F % _q, G * H % _q, F * G % _q, E * H % _q)


def _mul(s, P):
    Q = (0, 1, 1, 0)
    while s:
        if s & 1:
            Q = _add(Q, P)
        P, s = _add(P, P), s >> 1
    return Q


def _point(b):
    y = int.from_bytes(b, "little")
    sign, y = y >> 255, y & ((1 << 255) - 1)
    if y >= _q:
        return None
    x2 = (y * y - 1) * pow(_d * y * y + 1, _q - 2, _q) % _q
    x = pow(x2, (_q + 3) // 8, _q)
    if (x * x - x2) % _q:
        x = x * pow(2, (_q - 1) // 4, _q) % _q
    if (x * x - x2) % _q or (x == 0 and sign):
        return None
    if (x & 1) != sign:
        x = _q - x
    return (x, y, 1, x * y % _q)


def _ed25519_pure(pub, msg, sig):
    if len(pub) != 32 or len(sig) != 64:
        return False
    A, R, s = _point(pub), _point(sig[:32]), int.from_bytes(sig[32:], "little")
    if A is None or R is None or s >= _L:
        return False
    B = _point((4 * pow(5, _q - 2, _q) % _q).to_bytes(32, "little"))
    h = int.from_bytes(hashlib.sha512(sig[:32] + pub + msg).digest(), "little") % _L
    lhs, rhs = _mul(s, B), _add(R, _mul(h, A))
    return (lhs[0] * rhs[2] - rhs[0] * lhs[2]) % _q == 0 and (lhs[1] * rhs[2] - rhs[1] * lhs[2]) % _q == 0


def ed25519_verify(pub, msg, sig):
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    except ImportError:
        return _ed25519_pure(pub, msg, sig)
    try:
        Ed25519PublicKey.from_public_bytes(pub).verify(sig, msg)
        return True
    except Exception:
        return False


_KEYS = None


def keys(refresh=False):
    """The published key set, fetched once and pinned by key id."""
    global _KEYS
    if _KEYS is None or refresh:
        ks = call(KEYS_URL)
        _KEYS = {k["key_id"]: base64.b64decode(k["public_key_b64"]) for k in ks.get("keys", []) if k.get("alg") == "Ed25519"}
    return _KEYS


def verify_token(token, payee=None, rule=None, now=None):
    """Offline. mzv1.<claims>.<sig>, Ed25519 over 'mzv1.' + claims. Returns {"ok", "code", "claims"}.
    With payee / rule given, the token must be bound to them (claims.bound_to)."""
    def no(code, claims=None):
        return {"ok": False, "code": code, "claims": claims}
    parts = str(token or "").split(".")
    if len(parts) != 3 or parts[0] != "mzv1":
        return no("malformed")
    try:
        claims = json.loads(b64u(parts[1]))
    except Exception:
        return no("malformed")
    kid = claims.get("kid")
    K = keys()
    if kid not in K:
        K = keys(refresh=True)
        if kid not in K:
            return no("unknown_kid", claims)
    if not ed25519_verify(K[kid], ("mzv1." + parts[1]).encode("ascii"), b64u(parts[2])):
        return no("bad_signature", claims)
    if claims.get("typ") != "mizan.verdict/1":
        return no("wrong_type", claims)
    if claims.get("exp", 0) <= (time.time() if now is None else now):
        return no("expired", claims)
    bt = claims.get("bound_to") or {}
    norm = lambda s: str(s or "").lower() if str(s or "").lower().startswith("0x") else str(s or "")  # noqa: E731
    if payee is not None and norm(bt.get("payee")) != norm(payee):
        return no("payee_mismatch", claims)
    if rule is not None and bt.get("rule") != rule and claims.get("rule") != rule and claims.get("rule_id") != rule:
        return no("rule_mismatch", claims)
    return {"ok": True, "code": "valid" if claims.get("decision") == "ALLOW" else "refused", "claims": claims}


def check(subject, payee=None, rule=None):
    """GET /api/check/{subject}. `payee` binds the token to the party being paid; `rule` is a published ref (req_…@1)
    or a MIZAN rule id (mizan.default/1, mizan.reliability/1). No key, fail closed."""
    q = {}
    if payee:
        q["payee"] = payee
    if rule:
        q["requirement" if rule.startswith("req_") else "rule"] = rule
    qs = ("?" + urllib.parse.urlencode(q)) if q else ""
    v = call("/api/check/" + urllib.parse.quote(subject, safe=":/@") + qs)
    if "error" in v and "decision" not in v:
        v["decision"] = "REFUSE"
        v["reason"] = "unavailable"
    return v


def compile_rule(words):
    """POST /api/requirements/compile: plain words -> {"requirement", "shown_back", "hash", "unmatched", "publishable"}.
    No key, nothing written. Read shown_back before you publish or enforce."""
    return call("/api/requirements/compile", {"text": words})


def rule_hash(v):
    r = v.get("rule") or {}
    return r.get("hash") if isinstance(r, dict) else None


class Refused(RuntimeError):
    """Raised by guard(mode="enforce") on a REFUSE or an unverifiable answer. Carries .decision .reason .next .verdict"""

    def __init__(self, verdict, code):
        self.verdict, self.decision, self.code = verdict, verdict.get("decision", "REFUSE"), code
        self.reason = verdict.get("reason") or (verdict.get("error") or {}).get("code") or code
        self.next = verdict.get("next") or (verdict.get("error") or {}).get("next")
        super().__init__("MIZAN %s: %s · next: %s" % (self.decision, self.reason, json.dumps(self.next)))


def guard(fn, rule=None, mode="advise", on_decision=None):
    """Wrap any pay / hire / release function. The payee is the first positional argument or `payee=`.
    advise (default): always runs fn, logs the signed decision on fn.last_decision. enforce: runs fn only on a
    verified, bound ALLOW; otherwise raises Refused and fn is never called. `rule` is a published ref or rule id."""
    assert mode in ("advise", "enforce"), "mode is 'advise' or 'enforce'"

    def wrapped(*args, **kwargs):
        payee = kwargs.get("payee") or (args[0] if args else None)
        v = check(str(payee), payee=str(payee), rule=rule)
        r = verify_token(v.get("token"), payee=str(payee), rule=rule if rule and not rule.startswith("req_") else None)
        if rule and rule.startswith("req_") and r["ok"] and (r["claims"] or {}).get("rule_id") != rule:
            r = {"ok": False, "code": "rule_mismatch", "claims": r["claims"]}
        allow = r["ok"] and r["code"] == "valid"
        wrapped.last_decision = {"payee": payee, "decision": v.get("decision"), "verified": r, "reason": v.get("reason"), "next": v.get("next"), "request_id": v.get("request_id")}
        if on_decision:
            on_decision(wrapped.last_decision)
        else:
            print("mizan %s: %s %s%s" % (mode, payee, v.get("decision", "REFUSE"), "" if allow else " (" + str(v.get("reason") or r["code"]) + ")"), file=sys.stderr)
        if mode == "enforce" and not allow:
            raise Refused(v, r["code"])
        return fn(*args, **kwargs)

    wrapped.last_decision = None
    wrapped.__name__ = getattr(fn, "__name__", "guarded")
    return wrapped
