"""bitsig client: make fair drawings and verify every result yourself.

Standard library only, except the two signature checks:
  bitsig's Ed25519 signatures need `cryptography`  (pip install cryptography)
  drand's BLS round signatures need `py_ecc`       (pip install py_ecc)
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)          # checks the drand round, then recomputes the result
    bitsg.verify_signature(result)     # checks bitsig's Ed25519 signature
"""

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

# JavaScript's String.prototype.trim() removes exactly these (WhiteSpace and LineTerminator).
# Python's str.strip() also removes U+001C-U+001F and U+0085 and keeps U+FEFF, so it can't be
# used on anything the server trims.
_JS_WS = "\t\n\v\f\r                  　﻿"


def js_trim(s):
    return s.strip(_JS_WS)

BASE = "https://bit.sg"
CHAIN = "52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971"
# quicknet's public key, from https://api.drand.sh/<CHAIN>/info (G2, compressed)
CHAIN_PUBLIC_KEY = (
    "83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c"
    "8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb"
    "5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a"
)
DST = b"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"
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, circle_teams=None, circle_not=None):
    """Create a drawing. 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), ("circle_teams", circle_teams), ("circle_not", circle_not)):
        if v is not None:
            fields[k] = v
    return _post(f"{BASE}/draw", fields)


def get(draw_id):
    """Fetch a drawing'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 verify_beacon(round_, signature_hex):
    """True if `signature_hex` is drand quicknet's genuine signature for `round_`.

    quicknet signs SHA-256(uint64_be(round)) with a threshold BLS key: the
    signature is a G1 point and the public key a G2 point. Needs `py_ecc`.
    """
    try:
        from py_ecc.bls.hash_to_curve import hash_to_G1
        from py_ecc.bls.point_compression import decompress_G1, decompress_G2
        from py_ecc.optimized_bls12_381 import G2, pairing
    except ImportError:
        raise RuntimeError("checking drand's signature needs py_ecc: pip install py_ecc (or pass check_signature=False)")
    try:
        pk = bytes.fromhex(CHAIN_PUBLIC_KEY)
        public_key = decompress_G2((int.from_bytes(pk[:48], "big"), int.from_bytes(pk[48:], "big")))
        sig = decompress_G1(int.from_bytes(bytes.fromhex(signature_hex), "big"))
    except Exception:
        return False
    message = hash_to_G1(hashlib.sha256(int(round_).to_bytes(8, "big")).digest(), DST, hashlib.sha256)
    return pairing(G2, sig) == pairing(public_key, message)


def beacon(round_, check_signature=True):
    """Fetch a drand quicknet round. Checks randomness = sha256(signature) and,
    unless check_signature=False, that the signature is genuine (needs py_ecc)."""
    last = None
    for src in DRAND:
        try:
            b = _get(f"{src}/{CHAIN}/public/{round_}")
            if b.get("round") != int(round_):
                raise ValueError(f"{src} returned round {b.get('round')} instead of {round_}")
            if hashlib.sha256(bytes.fromhex(b["signature"])).hexdigest() != b["randomness"]:
                raise ValueError("beacon randomness does not match its signature")
            if check_signature and not verify_beacon(b["round"], b["signature"]):
                raise ValueError(f"{src} returned a round whose signature does not verify")
            return b
        except RuntimeError:
            raise
        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 normalize_entry(s):
    """norm() from the spec's hidden-names section."""
    import re
    import unicodedata
    s = unicodedata.normalize("NFC", s)
    s = re.sub(r"[ \t\r\n]+", " ", s.strip(" \t\r\n"))
    return "".join(c.lower() if "A" <= c <= "Z" else c for c in s)


def entry_tag(entry, salt, scheme="bitsig-entry-v2"):
    """The code a drawing with hidden names shows for an entry. For v2 the salt is the
    part after #s= in the entry's private check link; for v1 it is d["mask"]["salt"]."""
    msg = f"{scheme}\n{salt}\n{normalize_entry(entry)}".encode()
    return hashlib.sha256(msg).hexdigest()[:16]


def list_fingerprint(data):
    """SHA-256 (hex) of a referenced list's bytes: entries joined with \\n, UTF-8."""
    return hashlib.sha256(data).hexdigest()


def parse_ref(op):
    """(kind, count, sha256) for an op that references its list, like pick@20000:<sha256>; else None."""
    m = re.fullmatch(r"(pick|shuffle)@([1-9][0-9]{0,6}):([0-9a-f]{64})", op)
    return (m.group(1), int(m.group(2)), m.group(3)) if m else None


def get_list(draw_id):
    """The list file of a drawing over 10,000 entries, as bytes."""
    with urllib.request.urlopen(urllib.request.Request(f"{BASE}/draw/{urllib.parse.quote(draw_id)}/list.txt", headers={"User-Agent": UA["User-Agent"]}), timeout=120) as r:
        return r.read()


def attach_list(op, data):
    """Check a referenced list's SHA-256 and count against the op; return its entries."""
    kind, count, sha = parse_ref(op)
    got = list_fingerprint(data)
    if got != sha:
        raise ValueError(f"the list's SHA-256 is {got}, not {sha} as the op states")
    items = data.decode("utf-8").split("\n")
    if len(items) != count:
        raise ValueError(f"the list has {len(items)} entries, not {count} as the op states")
    return items


def run(op, randomness_hex, seed, items=None):
    """Recompute pick, shuffle or weighted ops, the ones draws use. For an op that
    references its list (pick@COUNT:SHA256), pass the entries from attach_list()."""
    ref = parse_ref(op)
    if ref:
        if items is None:
            raise ValueError("this op references a list: pass items=attach_list(op, data)")
        kind, rest = ref[0], None
    else:
        kind, _, rest = op.partition("?")
        if kind.lower() == "circle":
            return run_circle(rest, randomness_hex, seed)
        items = [js_trim(s) for s in rest.split(",") if js_trim(s)]
    st = Stream(randomness_hex, seed)
    if kind.lower().split("/")[0] == "weighted":
        names = [js_trim(x.rsplit(":", 1)[0]) for x in items]
        weights = [int(x.rsplit(":", 1)[1]) for x in items]
        k = int(kind.split("/")[1]) if "/" in kind else len(names) - 1
        out = []
        for _ in range(min(k, len(names) - 1)):
            r = st.uniform(sum(weights))
            i = 0
            while r >= weights[i]:
                r -= weights[i]
                i += 1
            out.append(names.pop(i))
            weights.pop(i)
        return out + names
    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, shuffle and weighted draws, not {kind!r}")


def parse_circle(rest):
    """'a,b,c&teams=1,1,0&not=1-3' -> (items, teams or None, pairs). The first
    '&teams=' or '&not=' ends the entries."""
    cuts = [i for i in (rest.find("&teams="), rest.find("&not=")) if i != -1]
    end = min(cuts) if cuts else len(rest)
    items = [js_trim(x) for x in rest[:end].split(",") if js_trim(x)]
    m = re.fullmatch(r"(?:&teams=([0-9,]*))?(?:&not=([0-9,-]*))?", rest[end:])
    if not m:
        raise ValueError("bad circle options")
    teams = [int(x) for x in m.group(1).split(",")] if m.group(1) else None
    pairs = [tuple(int(y) for y in p.split("-")) for p in m.group(2).split(",")] if m.group(2) else []
    return items, teams, pairs


def run_circle(rest, randomness_hex, seed):
    """The Secret Santa circle with exclusions (spec 3a): Fisher-Yates, repair, then
    100n mixing. Returns the entries in seat order (each gives to the next, the last to
    the first), or [] for 'no circle'."""
    items, teams, pairs = parse_circle(rest)
    n = len(items)
    team = teams or [0] * n
    ex = {}
    for a1, b1 in pairs:
        ex.setdefault(a1 - 1, set()).add(b1 - 1)
        ex.setdefault(b1 - 1, set()).add(a1 - 1)

    def bad(a, b):
        return a == b or (team[a] != 0 and team[a] == team[b]) or b in ex.get(a, ())

    st = Stream(randomness_hex, seed)
    c = list(range(n))
    for i in range(n - 1, 0, -1):
        j = st.uniform(i + 1)
        c[i], c[j] = c[j], c[i]

    def is_bad(e):
        return bad(c[e], c[(e + 1) % n])

    B = [e for e in range(n) if is_bad(e)]

    def touching(i, j):
        out = []
        for x in ((i - 1) % n, i, (j - 1) % n, j):
            if x not in out:
                out.append(x)
        return out

    def try_swap(i, j, strict):
        E = touching(i, j)
        before = sum(1 for e in E if is_bad(e))
        c[i], c[j] = c[j], c[i]
        after = sum(1 for e in E if is_bad(e))
        if after == 0 if strict else after <= before:
            for e in E:
                was = e in B
                now = is_bad(e)
                if was and not now:
                    B.remove(e)
                elif now and not was:
                    B.append(e)
                    B.sort()
            return True
        c[i], c[j] = c[j], c[i]
        return False

    cap = 100 * n + 1000
    steps = 0
    while B:
        if steps >= cap:
            return []
        steps += 1
        p = B[st.uniform(len(B))]
        j = st.uniform(n)
        i = (p + 1) % n
        if i != j:
            try_swap(i, j, False)
    for _ in range(100 * n):
        i = st.uniform(n)
        j = st.uniform(n)
        if i != j:
            try_swap(i, j, True)
    return [items[k] for k in c]


def verify_draw(d, check_signature=True, list_data=None):
    """Check the drand round, then recompute a finished drawing from it. Returns True or raises.
    For a drawing over 10,000 entries the list is fetched from bit.sg, or pass your own copy's bytes as list_data."""
    if d.get("status") != "done":
        raise ValueError("draw is still pending")
    b = beacon(d["round"], check_signature)
    items = None
    if parse_ref(d["op"]):
        # Over 10,000 entries: the list is a file; its SHA-256 is in the op.
        items = attach_list(d["op"], list_data if list_data is not None else get_list(d["id"]))
    got = run(d["op"], b["randomness"], d["seed"], items)
    if parse_ref(d["op"]) and isinstance(got, list):
        got = got[: len(d["result"])]  # such a drawing publishes the winners and the next 3 only
    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 bitsig's Ed25519 signature (the `bitsig` field). Needs `cryptography`."""
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

    rec = dict(rec)
    sig = rec.pop("bitsig")
    doc = public_key or key()
    known = doc.get("keys") or [{"key_id": doc["key_id"], "public_key": doc["public_key"]}]
    k = next((x for x in known if x["key_id"] == sig["key"]), None)
    if k is None:
        raise ValueError(f"signed with key {sig['key']}, which bitsig has never published")
    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"])
