"""bit.sg client: make fair draws and verify every result yourself.

Standard library only, except signature checks, which need `cryptography`
(pip install cryptography). Served at https://bit.sg/bitsg.py.

    import bitsg
    d = bitsg.draw(["alice", "bob", "carol"], seconds=60, title="Raffle")
    print(d["url"])
    ...
    result = bitsg.get(d["id"])
    bitsg.verify_draw(result)          # recomputes it from the drand beacon
    bitsg.verify_signature(result)     # checks bit.sg's Ed25519 signature
"""

import base64
import hashlib
import json
import urllib.parse
import urllib.request

BASE = "https://bit.sg"
CHAIN = "52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971"
DRAND = ["https://api.drand.sh", "https://drand.cloudflare.com", "https://api2.drand.sh"]
TWO32 = 2**32
UA = {"User-Agent": "bitsg-python/1", "Accept": "application/json"}


def _get(url):
    with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=20) as r:
        return json.load(r)


def _post(url, fields):
    body = json.dumps(fields).encode()
    req = urllib.request.Request(url, data=body, headers={**UA, "Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=20) as r:
        return json.load(r)


# ---------- API ----------

def draw(choices, *, seconds=None, at=None, tz=None, winners=None, mode=None, groups=None, title=None, organizer=None, callback=None):
    """Create a draw. Give `seconds` from now, or `at` (ISO time; with `tz` for a local time)."""
    fields = {"choices": "\n".join(choices)}
    if seconds is not None:
        fields["in"] = seconds
    if at is not None:
        fields["at"] = at
    for k, v in (("tz", tz), ("winners", winners), ("mode", mode), ("groups", groups), ("title", title), ("organizer", organizer), ("callback", callback)):
        if v is not None:
            fields[k] = v
    return _post(f"{BASE}/draw", fields)


def get(draw_id):
    """Fetch a draw's current record (pending or done)."""
    return _get(f"{BASE}/draw/{urllib.parse.quote(draw_id)}?json")


def today():
    """Today's daily seed record."""
    return _get(f"{BASE}/today?json")


def key():
    return _get(f"{BASE}/key")


# ---------- verification ----------

def beacon(round_):
    """Fetch a drand quicknet round and check randomness = sha256(signature)."""
    last = None
    for src in DRAND:
        try:
            b = _get(f"{src}/{CHAIN}/public/{round_}")
            if hashlib.sha256(bytes.fromhex(b["signature"])).hexdigest() != b["randomness"]:
                raise ValueError("beacon randomness does not match its signature")
            return b
        except Exception as e:  # try the next source
            last = e
    raise last


class Stream:
    """Block i = SHA-256(R || seed || uint32be(i)), read front to back."""

    def __init__(self, randomness_hex, seed):
        self.r = bytes.fromhex(randomness_hex)
        self.s = seed.encode()
        self.i = 0
        self.buf = b""
        self.pos = 0

    def bytes(self, n):
        out = bytearray()
        while len(out) < n:
            if self.pos >= len(self.buf):
                self.buf = hashlib.sha256(self.r + self.s + self.i.to_bytes(4, "big")).digest()
                self.i += 1
                self.pos = 0
            out.append(self.buf[self.pos])
            self.pos += 1
        return bytes(out)

    def uniform(self, k):
        limit = (TWO32 // k) * k
        while True:
            w = int.from_bytes(self.bytes(4), "big")
            if w < limit:
                return w % k


def run(op, randomness_hex, seed):
    """Recompute pick or shuffle ops, the ones draws use."""
    kind, _, rest = op.partition("?")
    items = [s.strip() for s in rest.split(",") if s.strip()]
    st = Stream(randomness_hex, seed)
    if kind == "pick":
        return items[st.uniform(len(items))]
    if kind == "shuffle":
        a = items[:]
        for i in range(len(a) - 1, 0, -1):
            j = st.uniform(i + 1)
            a[i], a[j] = a[j], a[i]
        return a
    raise ValueError(f"run() supports pick and shuffle draws, not {kind!r}")


def verify_draw(d):
    """Recompute a finished draw from the public beacon. Returns True or raises."""
    if d.get("status") != "done":
        raise ValueError("draw is still pending")
    b = beacon(d["round"])
    got = run(d["op"], b["randomness"], d["seed"])
    if got != d["result"]:
        raise ValueError("result does not match the beacon")
    return True


def canonical(rec):
    return json.dumps(rec, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def verify_signature(rec, public_key=None):
    """Check bit.sg's Ed25519 signature (the `bitsig` field). Needs `cryptography`."""
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

    rec = dict(rec)
    sig = rec.pop("bitsig")
    k = public_key or key()
    if sig["key"] != k["key_id"]:
        raise ValueError(f"signed with key {sig['key']}, not {k['key_id']}")
    pub = Ed25519PublicKey.from_public_bytes(base64.urlsafe_b64decode(k["public_key"] + "=="))
    pub.verify(base64.urlsafe_b64decode(sig["sig"] + "=="), canonical(rec))
    return True


if __name__ == "__main__":
    t = today()
    print(t["date"], t["seed"])
