#!/usr/bin/env python3
"""
DartXchange request signing (scheme DX1-HMAC-SHA256): independent reference implementation.

Python standard library only. It shares NO code with the API (api/src/auth/appAuth.ts, TypeScript).
It is written from the rules in docs/SIGNING.md and is used to
  --generate   (re)create test-vectors.json from the fixed inputs below
  --verify     check a vectors file (default: test-vectors.json) and exit non-zero on any mismatch

All keys here are TEST-ONLY, NOT PRODUCTION. They sign nothing real.
"""
import base64
import hashlib
import hmac
import json
import sys
from pathlib import Path
from urllib.parse import parse_qsl, quote, urlsplit

HERE = Path(__file__).resolve().parent

SCHEME = "DX1-HMAC-SHA256"
TEST_KEY_ID = "dxk_TestVectorKey001"  # "dxk_" + exactly 16 characters of A-Za-z0-9_-
TEST_KEY_BYTES = b"TEST-ONLY-NOT-A-REAL-KEY-0123456"  # exactly 32 bytes, non-production


def b64url(raw: bytes) -> str:
    return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")


def canonical_query(raw_query: str) -> str:
    # Decode (form rules: '+' means space; keep blank values), re-encode per RFC 3986
    # (only A-Z a-z 0-9 - . _ ~ stay literal; hex digits upper-case), sort by name then value.
    pairs = parse_qsl(raw_query, keep_blank_values=True, encoding="utf-8", errors="strict")
    enc = [(quote(k, safe="~"), quote(v, safe="~")) for k, v in pairs]
    enc.sort()
    return "&".join(f"{k}={v}" for k, v in enc)


def canonical_string(method, url, timestamp, nonce, body: bytes, key_id) -> str:
    parts = urlsplit(url)
    return "\n".join(
        [
            SCHEME,
            method.upper(),
            parts.path,
            canonical_query(parts.query),
            str(timestamp),
            nonce,
            hashlib.sha256(body).hexdigest(),
            key_id,
        ]
    )


def sign(key: bytes, canonical: str) -> str:
    return b64url(hmac.new(key, canonical.encode("utf-8"), hashlib.sha256).digest())


# name, description, method, url, timestamp, nonce, body text
CASES = [
    ("get-no-body", "GET with no body and no query string.",
     "GET", "https://api.example.test/v1/lobbies", 1767225600, "nonce-get-no-body-0001", ""),
    ("post-json-body", "POST with a JSON body (ASCII). The body hash covers the exact bytes sent.",
     "POST", "https://api.example.test/v1/auth/player-sessions", 1767225601, "nonce-post-json-0002",
     '{"external_player_id":"u-1001","username":"Alice","scoring_method":"manual"}'),
    ("post-empty-body", "POST with an empty body: the body hash is the SHA-256 of zero bytes.",
     "POST", "https://api.example.test/v1/lobbies/lb_AAAAAAAAAAAAAAAAAAAAAA/heartbeat", 1767225602,
     "nonce-post-empty-0003", ""),
    ("query-sorting", "Query pairs are sorted by name then value, including repeated names.",
     "GET", "https://api.example.test/v1/lobbies?z=1&b=2&a=2&a=1&limit=10", 1767225603,
     "nonce-query-sort-0004", ""),
    ("query-encoding", "Query decoding and RFC 3986 re-encoding: percent hex upper-cased, '+' is a space, "
     "empty values, valueless names, reserved characters, ~ stays literal.",
     "GET", "https://api.example.test/v1/lobbies?q=a%20b&p=a+b&e=&flag&s=%21%27%28%29%2a~&lower=%c3%a9", 1767225604,
     "nonce-query-enc-0005", ""),
    ("utf8-body", "UTF-8 body sent as raw UTF-8 bytes (not \\u escapes): accents, CJK, emoji (4-byte).",
     "POST", "https://api.example.test/v1/auth/player-sessions", 1767225605, "nonce-utf8-body-0006",
     '{"external_player_id":"u-2002","username":"Zoë 日本 \U0001F3AF","scoring_method":"automatic"}'),
    ("utf8-query", "UTF-8 in the query string: sent percent-encoded, signed in the canonical form.",
     "GET", "https://api.example.test/v1/lobbies?name=Zo%C3%AB%20%E6%97%A5%E6%9C%AC%20%F0%9F%8E%AF", 1767225606,
     "nonce-utf8-query-0007", ""),
    ("method-case", "The method is upper-cased before signing, so 'post' signs the same as 'POST'.",
     "post", "https://api.example.test/v1/lobbies/lb_AAAAAAAAAAAAAAAAAAAAAA/cancel", 1767225607,
     "nonce-method-case-0008", ""),
]


def build():
    secret = "dxs_" + b64url(TEST_KEY_BYTES)
    vectors = []
    for name, desc, method, url, ts, nonce, body in CASES:
        body_bytes = body.encode("utf-8")
        canonical = canonical_string(method, url, ts, nonce, body_bytes, TEST_KEY_ID)
        parts = urlsplit(url)
        vectors.append(
            {
                "name": name,
                "description": desc,
                "input": {"method": method, "url": url, "timestamp": ts, "nonce": nonce, "body": body},
                "expected": {
                    "canonical_path": parts.path,
                    "canonical_query": canonical_query(parts.query),
                    "body_utf8_hex": body_bytes.hex(),
                    "body_sha256_hex": hashlib.sha256(body_bytes).hexdigest(),
                    "canonical_string": canonical,
                    "signature": sign(TEST_KEY_BYTES, canonical),
                    "headers": {
                        "X-DX-Key-Id": TEST_KEY_ID,
                        "X-DX-Timestamp": str(ts),
                        "X-DX-Nonce": nonce,
                        "X-DX-Signature": sign(TEST_KEY_BYTES, canonical),
                    },
                },
            }
        )
    return {
        "scheme": SCHEME,
        "warning": "TEST-ONLY, NOT PRODUCTION. This key and secret are published, sign nothing real and must never be used or issued anywhere.",
        "key": {"key_id": TEST_KEY_ID, "secret": secret, "signing_key_ascii": TEST_KEY_BYTES.decode("ascii")},
        "vectors": vectors,
    }


def verify(path: Path) -> int:
    data = json.loads(path.read_text(encoding="utf-8"))
    secret = data["key"]["secret"]
    assert secret.startswith("dxs_")
    raw = secret[4:]
    key = base64.urlsafe_b64decode(raw + "=" * (-len(raw) % 4))
    bad = 0
    for v in data["vectors"]:
        i, e = v["input"], v["expected"]
        body = i["body"].encode("utf-8")
        canonical = canonical_string(i["method"], i["url"], i["timestamp"], i["nonce"], body, data["key"]["key_id"])
        checks = {
            "canonical_string": canonical == e["canonical_string"],
            "body_sha256_hex": hashlib.sha256(body).hexdigest() == e["body_sha256_hex"],
            "body_utf8_hex": body.hex() == e["body_utf8_hex"],
            "signature": sign(key, canonical) == e["signature"] == e["headers"]["X-DX-Signature"],
        }
        failed = [k for k, ok in checks.items() if not ok]
        print(("OK   " if not failed else "FAIL ") + v["name"] + ("" if not failed else "  " + ",".join(failed)))
        bad += bool(failed)
    print(f"{len(data['vectors']) - bad} passed, {bad} failed")
    return 1 if bad else 0


if __name__ == "__main__":
    assert len(TEST_KEY_BYTES) == 32
    assert len(TEST_KEY_ID) == 4 + 16
    if "--generate" in sys.argv:
        out = HERE / "test-vectors.json"
        # newline="\n" keeps LF on Windows.
        with open(out, "w", encoding="utf-8", newline="\n") as f:
            json.dump(build(), f, indent=2, ensure_ascii=False)
            f.write("\n")
        print("wrote", out)
    else:
        target = Path(sys.argv[1]) if len(sys.argv) > 1 and not sys.argv[1].startswith("--") else HERE / "test-vectors.json"
        sys.exit(verify(target))
