"""W1 message construction and checking. Only the public corpus supplies test keys."""
import base64
import ctypes
import ctypes.util
import hashlib
import json
import re
from dataclasses import dataclass
from http import HTTPStatus
from urllib.parse import urlsplit

from jsonschema import Draft202012Validator

PROFILE = "http6-w1-00"
REQ = ('"@method"', '"@target-uri"', '"content-type"', '"content-digest"')
RES = ('"@status"', '"content-type"', '"content-digest"', '"@method";req',
       '"@target-uri";req', '"content-digest";req')
STATUS = {200: {"COMMITTED", "RECONCILED", "CLOSED"}, 202: {"RESERVED", "UNCERTAIN"},
          403: {"DENIED"}, 409: {"REPLAY", "CONFLICT", "BUDGET"}, 503: {"HELD"}}
TIME_MAX = 253402300799


class Invalid(ValueError):
    """An input failed wire, schema, signature, or trust checks."""


def require(condition, reason):
    if not condition:
        raise Invalid(reason)


def digest(data):
    return hashlib.sha256(data).hexdigest()


def no_duplicates(pairs):
    out = {}
    for key, value in pairs:
        require(key not in out, "duplicate JSON property")
        out[key] = value
    return out


def canonical(value):
    # The published grammar excludes floats, nonprintable text and non-ASCII keys.
    def visit(item):
        if isinstance(item, str):
            require(all(" " <= ch <= "~" for ch in item), "non-ASCII or control character")
        elif type(item) is int:
            require(0 <= item <= TIME_MAX, "integer range")
        elif isinstance(item, dict):
            for key, member in item.items():
                visit(key)
                visit(member)
        elif isinstance(item, list):
            for member in item:
                visit(member)
        else:
            require(item is None or type(item) is bool, "unsupported JSON value")
    visit(value)
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("ascii")


def parse_canonical(raw):
    try:
        obj = json.loads(raw.decode("ascii"), object_pairs_hook=no_duplicates)
        require(canonical(obj) == raw, "noncanonical JSON")
        return obj
    except (UnicodeError, ValueError, RecursionError) as err:
        raise Invalid("malformed canonical JSON") from err


def b64(raw):
    return base64.b64encode(raw).decode("ascii")


def url64(raw):
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")


def unpack(text, url=False):
    try:
        require(isinstance(text, str), "base64 type")
        padded = text + "=" * (-len(text) % 4) if url else text
        raw = base64.b64decode(padded, altchars=b"-_" if url else None, validate=True)
        require((url64 if url else b64)(raw) == text, "noncanonical base64")
        return raw
    except (TypeError, ValueError) as err:
        raise Invalid("bad base64") from err


class Sodium:
    def __init__(self):
        candidates = (ctypes.util.find_library("sodium"), "libsodium.so", "libsodium.dylib",
                      "/opt/homebrew/lib/libsodium.dylib", "/usr/local/lib/libsodium.dylib", "libsodium.dll")
        for path in filter(None, candidates):
            try:
                self.lib = ctypes.CDLL(path)
                break
            except OSError:
                continue
        else:
            raise RuntimeError("Install libsodium and make its shared library available to Python.")
        lib = self.lib
        ptr = ctypes.c_void_p
        size = ctypes.c_ulonglong
        for name, args in {"sodium_init": [], "crypto_sign_seed_keypair": [ptr, ptr, ptr],
                           "crypto_sign_detached": [ptr, ctypes.POINTER(size), ptr, size, ptr],
                           "crypto_sign_verify_detached": [ptr, ptr, size, ptr]}.items():
            fn = getattr(lib, name)
            fn.argtypes, fn.restype = args, ctypes.c_int
        lib.sodium_version_string.argtypes, lib.sodium_version_string.restype = [], ctypes.c_char_p
        require(lib.sodium_init() >= 0, "libsodium init")

    def sign(self, seed, pub, message):
        require(len(seed) == len(pub) == 32, "key length")
        public, secret, sig = (ctypes.create_string_buffer(n) for n in (32, 64, 64))
        require(self.lib.crypto_sign_seed_keypair(public, secret, seed) == 0 and public.raw == pub,
                "fixture seed and public key disagree")
        length = ctypes.c_ulonglong()
        require(self.lib.crypto_sign_detached(sig, ctypes.byref(length), message, len(message), secret) == 0
                and length.value == 64, "signing error")
        return sig.raw

    def verify(self, public, message, sig):
        require(len(public) == 32 and len(sig) == 64 and
                self.lib.crypto_sign_verify_detached(sig, message, len(message), public) == 0,
                "signature verification failed")


@dataclass
class Envelope:
    body: dict
    signature: str
    target: str
    content_digest: str
    base: bytes


class Binding:
    def __init__(self, fixtures, schema):
        self.f = fixtures
        self.crypto = Sodium()
        self.origin = fixtures["origin"]
        self.host = urlsplit(self.origin).netloc
        self.validators = {name: Draft202012Validator({"$defs": schema["$defs"], "$ref": "#/$defs/" + name})
                           for name in schema["$defs"]}

    def shape(self, name, value):
        require(name in self.validators and self.validators[name].is_valid(value), "invalid " + str(name))

    def key(self, kid):
        key = self.f["keys"].get(kid)
        require(key and key["kid"] == kid and key["kty"] == "OKP" and key["crv"] == "Ed25519", "unknown key")
        return unpack(key["x"], True)

    def sign(self, kid, message):
        public = self.key(kid)
        return self.crypto.sign(unpack(self.f["keys"][kid]["testSeed"], True), public, message)

    def token(self, claims, kid):
        header = {"alg": "Ed25519", "kid": kid, "typ": "http6-w1+jws"}
        signing_input = url64(canonical(header)) + "." + url64(canonical(claims))
        return signing_input + "." + url64(self.sign(kid, signing_input.encode("ascii")))

    def open_token(self, compact, expected=None):
        require(isinstance(compact, str) and len(compact) <= 8192 and compact.count(".") == 2, "compact JWS")
        head, body, sig = compact.split(".")
        header, claims = parse_canonical(unpack(head, True)), parse_canonical(unpack(body, True))
        self.shape("header", header)
        require(isinstance(claims, dict) and claims.get("kind") in self.f["signers"], "unknown claim type")
        kind = claims["kind"]
        self.shape(kind, claims)
        require(expected is None or kind == expected, "unexpected claim type")
        role = self.f["signers"][kind]
        allowed = claims["key"] if role in ("parent", "holder") else role
        require(header["kid"] == allowed, "unauthorized signing role")
        self.crypto.verify(self.key(allowed), (head + "." + body).encode("ascii"), unpack(sig, True))
        return claims

    @staticmethod
    def parameters(parts, start, end, kid):
        return ('(' + ' '.join(parts) + ');created=' + str(start) + ';expires=' + str(end) +
                ';keyid="' + kid + '";alg="ed25519";tag="' + PROFILE + '"')

    @staticmethod
    def signature_base(parts, values, params):
        return "\n".join([f"{part}: {value}" for part, value in zip(parts, values, strict=True)] +
                         ['"@signature-params": ' + params]).encode("ascii")

    def build(self, body, start, kid, path=None, status=None, request=None):
        data = canonical(body)
        cd = "sha-256=:" + b64(hashlib.sha256(data).digest()) + ":"
        if request is None:
            target = self.origin + path
            first = f"POST {path} HTTP/1.1"
            first_field = "Host: " + self.host
            parts, values = REQ, ("POST", target, "application/json", cd)
        else:
            target = request.target
            first = f"HTTP/1.1 {status} {HTTPStatus(status).phrase}"
            first_field = "Cache-Control: private, no-store"
            parts, values = RES, (status, "application/json", cd, "POST", target, request.content_digest)
        params = self.parameters(parts, start, start + 30, kid)
        base = self.signature_base(parts, values, params)
        signature = "w1=:" + b64(self.sign(kid, base)) + ":"
        lines = [first, first_field, "Content-Type: application/json", "Content-Digest: " + cd,
                 "Signature-Input: w1=" + params, "Signature: " + signature,
                 "Content-Length: " + str(len(data))]
        return ("\r\n".join(lines) + "\r\n\r\n").encode("ascii") + data, Envelope(body, signature, target, cd, base)

    def receive(self, raw, now, request=None):
        head, sep, data = raw.partition(b"\r\n\r\n")
        require(sep and len(head) <= 16384 and len(data) <= 65536, "bad framing or length")
        try:
            first, *lines = head.decode("ascii").split("\r\n")
        except UnicodeError as err:
            raise Invalid("non-ASCII field") from err
        headers = {}
        for line in lines:
            key, sep, value = line.partition(": ")
            require(sep and re.fullmatch(r"[a-zA-Z0-9-]+", key) and key.lower() not in headers
                    and all(" " <= ch <= "~" for ch in value), "duplicate or malformed field")
            headers[key.lower()] = value
        names = {"content-type", "content-length", "content-digest", "signature-input", "signature"}
        require(set(headers) == names | {"host" if request is None else "cache-control"}, "field set")
        cd = "sha-256=:" + b64(hashlib.sha256(data).digest()) + ":"
        require(headers["content-type"] == "application/json" and headers["content-length"] == str(len(data))
                and headers["content-digest"] == cd, "body digest or framing")
        body = parse_canonical(data)
        if request is None:
            match = re.fullmatch(r"POST (/w1/(?:operate|status|backend)) HTTP/1\.1", first)
            self.shape("request", body)
            require(match and headers["host"] == self.host, "wrong service or path")
            path = match[1]
            require((path == "/w1/status") == (body["mode"] == "lookup"), "inconsistent action and route")
            parts, values = REQ, ("POST", self.origin + path, "application/json", cd)
            target, kid = self.origin + path, body["key"]
        else:
            match = re.fullmatch(r"HTTP/1\.1 ([0-9]{3}) (.+)", first)
            self.shape("response", body)
            require(match and headers["cache-control"] == "private, no-store", "response framing")
            status = int(match[1])
            require(body["code"] in STATUS.get(status, set()) and match[2] == HTTPStatus(status).phrase, "status")
            target, kid = request.target, self.f["signers"]["outcome"]
            parts, values = RES, (status, "application/json", cd, "POST", target, request.content_digest)
        params = headers["signature-input"]
        times = re.search(r";created=(0|[1-9][0-9]{0,11});expires=(0|[1-9][0-9]{0,11});", params)
        require(times, "signature times")
        start, end = map(int, times.groups())
        expected = self.parameters(parts, start, end, kid)
        require(params == "w1=" + expected and 0 <= start <= now < end <= TIME_MAX and end-start <= 30,
                "signature coverage or freshness")
        base = self.signature_base(parts, values, expected)
        signature = headers["signature"]
        require(signature.startswith("w1=:") and signature.endswith(":"), "signature field")
        self.crypto.verify(self.key(kid), base, unpack(signature[4:-1]))
        if request is not None:
            self.check_response(body, request, now)
        return Envelope(body, signature, target, cd, base)

    def check_response(self, body, request, now):
        q = request.body
        require(body["requestRef"] == digest(request.signature.encode("ascii")) and
                body["recipient"] == q["key"] and body["op"] == q["op"], "response association")
        evidence_kind = {"RESERVED": "permit", "COMMITTED": "outcome", "RECONCILED": "outcome",
                         "CLOSED": "closure"}.get(body["code"])
        if evidence_kind is None:
            require(body["evidence"] is None, "unexpected evidence")
            return
        evidence = self.open_token(body["evidence"], evidence_kind)
        intent = q["intent"]
        require(evidence["op"] == q["op"] and evidence["holder"] == q["holder"] and
                evidence["intentHash"] == digest(canonical(intent)) and
                all(evidence[k] == intent[k] for k in ("root", "service", "account", "project", "units")),
                "evidence belongs to another operation")
        if evidence_kind == "permit":
            terms = self.open_token(q["chain"][-1], "grant" if len(q["chain"]) > 1 else "root")["terms"]
            runtime = self.open_token(q["appraisal"], "appraisal")
            require(all(evidence[k] == terms[k] for k in ("key", "gen", "epoch", "budget", "policy"))
                    and evidence["iat"] <= now < evidence["exp"] <= min(terms["exp"], runtime["exp"])
                    and evidence["exp"] - evidence["iat"] <= 5, "permit scope or expiry")

