#!/usr/bin/env python3
"""
TAP Provider Protocol v0.1: test vectors (teleport-tap-provider-protocol-v0.1.md §4.2, §14).

  python3 teleport-tap-provider-protocol-v0.1-vectors.py          # writes the vectors JSON
  python3 teleport-tap-provider-protocol-v0.1-vectors.py --check  # regenerates, compares, and checks every case

The signing key below is a published TEST key, derived from a fixed string. Never trust it outside tests.
Signatures are deterministic (RFC 6979), so the file regenerates byte for byte.
Needs: cryptography >= 43, jsonschema >= 4.
"""
import base64
import hashlib
import json
import sys
from pathlib import Path

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature, encode_dss_signature
from jsonschema import Draft202012Validator, FormatChecker

HERE = Path(__file__).parent
SCHEMA = json.loads((HERE / "teleport-tap-provider-protocol-v0.1.schema.json").read_text())
OUT = HERE / "teleport-tap-provider-protocol-v0.1-vectors.json"
TOLERANCE = 300
NOW = 1794852000  # 2026-11-16T18:00:00Z, the "now" every signed case is checked at


def b64u(b: bytes) -> str:
    return base64.urlsafe_b64encode(b).rstrip(b"=").decode()


def b64u_dec(s: str) -> bytes:
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))


def key_from(label: str):
    d = int.from_bytes(hashlib.sha256(label.encode()).digest(), "big") % (2**256 - 2**224 + 2**192 + 2**96 - 1)
    return ec.derive_private_key(d, ec.SECP256R1())


def jwk(priv, with_d=False):
    nums = priv.public_key().public_numbers()
    x, y = b64u(nums.x.to_bytes(32, "big")), b64u(nums.y.to_bytes(32, "big"))
    kid = b64u(hashlib.sha256(json.dumps({"crv": "P-256", "kty": "EC", "x": x, "y": y}, separators=(",", ":")).encode()).digest())
    out = {"kty": "EC", "crv": "P-256", "x": x, "y": y, "kid": kid, "alg": "ES256", "use": "sig"}
    if with_d:
        out["d"] = b64u(priv.private_numbers().private_value.to_bytes(32, "big"))
    return out


TEST_KEY = key_from("teleport.provider/0.1 test signing key")
OTHER_KEY = key_from("teleport.provider/0.1 some other key")
TEST_JWK = jwk(TEST_KEY, with_d=True)
PUBLIC_JWKS = {"keys": [{k: v for k, v in TEST_JWK.items() if k != "d"}]}


def sign(body: str, priv=TEST_KEY, header_over=None, ts=NOW):
    header = {"alg": "ES256", "kid": jwk(TEST_KEY)["kid"], "typ": "teleport-provider+json", "teleport-ts": ts}
    header.update(header_over or {})
    p = b64u(json.dumps(header, separators=(",", ":")).encode())
    der = priv.sign(f"{p}.{b64u(body.encode())}".encode(), ec.ECDSA(hashes.SHA256(), deterministic_signing=True))
    r, s = decode_dss_signature(der)
    return f"{p}..{b64u(r.to_bytes(32, 'big') + s.to_bytes(32, 'big'))}"


# ---------- One example of every message (§6) ----------

TASK = {
    "title": "Photograph cooler 4 after restock",
    "objective": "Every facing in cooler 4 is full and labels face forward.",
    "instructions": ["Photograph the whole cooler front, doors closed.", "Photograph each shelf close up."],
    "doneWhen": ["Every facing is full"],
    "category": "CAPTURE",
    "actorKinds": ["HUMAN"],
    "area": {"city": "Irvine", "region": "US-CA", "countryCode": "US", "approx": {"lat": 33.68, "lng": -117.83, "radiusMeters": 2000}},
    "window": {"startsAfter": None, "deadline": "2026-11-16T22:00:00Z"},
    "evidence": {
        "items": [{"id": "after_image", "type": "IMAGE", "required": True, "description": "The full cooler front"}],
        "minimumAssurance": "VERIFIED",
        "captureLinkRequired": True,
    },
}
DATA = {
    "offer.created": {"offerId": "ofr_2n7d4k1p9s3x6v8b", "taskRef": "tref_0d6c3b1e7a94f285", "expiresAt": "2026-11-16T18:30:00Z", "quoteBy": "2026-11-16T18:10:00Z", "task": TASK, "payCeiling": {"amountCents": 2500, "currency": "USD"}, "prequote": None},
    "offer.cancelled": {"offerId": "ofr_2n7d4k1p9s3x6v8b", "reason": "FILLED_ELSEWHERE"},
    "assignment.details": {
        "assignmentId": "asg_5h2j8k3l6m9n1p4q",
        "offerId": "ofr_2n7d4k1p9s3x6v8b",
        "price": {"amountCents": 2200, "currency": "USD"},
        "place": {"address": "6460 Irvine Blvd, Irvine, CA 92620", "lat": 33.6846, "lng": -117.8265, "spot": "Cooler 4, back wall", "accessNotes": "Ask for the shift lead at the counter."},
        "deadline": "2026-11-16T22:00:00Z",
        "captureLink": {"url": "https://app.teleport.eco/capture/example-token", "expiresAt": "2026-11-16T22:00:00Z"},
    },
    "assignment.cancelled": {"assignmentId": "asg_5h2j8k3l6m9n1p4q", "reason": "REQUESTER_CANCELLED", "at": "2026-11-16T19:00:00Z"},
    "decision.made": {"assignmentId": "asg_5h2j8k3l6m9n1p4q", "decision": "ACCEPT", "rejectionReason": None, "notes": None, "redoAllowed": False, "redoBy": None, "payable": {"amountCents": 2200, "currency": "USD", "status": "AWAITING_REQUESTER_PAYMENT"}},
    "receipt.issued": {"assignmentId": "asg_5h2j8k3l6m9n1p4q", "claimId": "claim_9w2e4r6t8y1u3i5o", "receiptLevel": "ANCHORED", "assuranceTier": "VERIFIED", "evidenceOriginFloor": "TELEPORT_CAPTURE", "status": "PENDING_BATCH", "proofUrl": "https://api.teleport.eco/api/v1/popw/claims/claim_9w2e4r6t8y1u3i5o/proof"},
    "payment.cleared": {"assignmentId": "asg_5h2j8k3l6m9n1p4q", "amountCents": 2200, "currency": "USD", "clearedAt": "2026-12-03T17:00:00Z", "payoutDueBy": "2026-12-10"},
}
EVENT_IDS = {t: f"evt_{hashlib.sha256(t.encode()).hexdigest()[:16]}" for t in DATA}


def event(t: str) -> dict:
    return {"protocol": "teleport.provider/0.1", "type": t, "eventId": EVENT_IDS[t], "occurredAt": "2026-11-16T18:00:00Z", "environment": "live", "providerId": "acme-field", "data": DATA[t]}


MANIFEST = {
    "schema": "teleport.provider.manifest/0.1",
    "id": "acme-field",
    "label": "Acme Field Services",
    "url": "https://acme.example",
    "kinds": ["HUMAN"],
    "categories": ["INSPECT", "CAPTURE", "OBSERVE"],
    "coverage": {"countries": ["US"], "regions": ["US-CA"], "areas": [], "remote": False},
    "leadTimeMinutes": {"min": 60, "typical": 240},
    "evidence": {"origins": ["THIRD_PARTY_SUBMITTED"], "teleportCaptureLink": True, "types": ["IMAGE", "VIDEO", "GPS"]},
    "modes": ["push", "pull"],
    "endpoints": {"events": "https://acme.example/teleport/events", "quote": "https://acme.example/teleport/quote"},
    "jwksUrl": "https://acme.example/.well-known/jwks.json",
    "currency": "USD",
    "support": {"email": "ops@acme.example"},
}

MESSAGES = [
    {"name": "manifest", "def": "Manifest", "value": MANIFEST, "valid": True},
    {"name": "manifest: push without an events endpoint", "def": "Manifest", "value": {**MANIFEST, "endpoints": {"quote": "https://acme.example/teleport/quote"}}, "valid": False},
    {"name": "manifest: id isn't a slug", "def": "Manifest", "value": {**MANIFEST, "id": "Acme Field"}, "valid": False},
    {"name": "manifest: plain-http endpoint", "def": "Manifest", "value": {**MANIFEST, "endpoints": {"events": "http://acme.example/teleport/events"}}, "valid": False},
    *[{"name": f"event {t}", "def": "Event", "value": event(t), "valid": True} for t in DATA],
    {"name": "event offer.created: offer leaks a street address", "def": "Event", "value": {**event("offer.created"), "data": {**DATA["offer.created"], "task": {**TASK, "address": "6460 Irvine Blvd"}}}, "valid": False},
    {"name": "event offer.created: approx radius under 1 km", "def": "Event", "value": {**event("offer.created"), "data": {**DATA["offer.created"], "task": {**TASK, "area": {**TASK["area"], "approx": {"lat": 33.68, "lng": -117.83, "radiusMeters": 200}}}}}, "valid": False},
    {"name": "event decision.made: REJECT with a payable", "def": "Event", "value": {**event("decision.made"), "data": {**DATA["decision.made"], "decision": "REJECT", "rejectionReason": "LOCATION_MISMATCH"}}, "valid": False},
    {"name": "event decision.made: REJECT", "def": "Event", "value": {**event("decision.made"), "data": {**DATA["decision.made"], "decision": "REJECT", "rejectionReason": "LOCATION_MISMATCH", "notes": "The photo shows cooler 3.", "redoAllowed": True, "redoBy": "2026-11-17T22:00:00Z", "payable": None}}, "valid": True},
    {"name": "quote request (sync)", "def": "QuoteRequest", "value": {"protocol": "teleport.provider/0.1", "quoteRequestId": "qrq_7b3n5m1k9j2h4g6f", "environment": "live", "task": TASK}, "valid": True},
    {"name": "quote response (sync)", "def": "QuoteResponse", "value": {"priceCents": 2200, "currency": "USD", "etaMinutes": 90, "validUntil": "2026-11-16T18:20:00Z"}, "valid": True},
    {"name": "quote", "def": "Quote", "value": {"priceCents": 2200, "currency": "USD", "etaMinutes": 90, "validUntil": "2026-11-16T18:20:00Z"}, "valid": True},
    {"name": "quote: euros", "def": "Quote", "value": {"priceCents": 2200, "currency": "EUR", "etaMinutes": 90, "validUntil": "2026-11-16T18:20:00Z"}, "valid": False},
    {"name": "accept", "def": "Accept", "value": {"quoteId": "qte_4d6f8h1j3k5l7z9x", "performerRef": "worker-7731"}, "valid": True},
    {"name": "decline", "def": "Decline", "value": {"reason": "NO_PERFORMER"}, "valid": True},
    {"name": "status", "def": "StatusUpdate", "value": {"status": "ON_SITE", "at": "2026-11-16T19:30:00Z"}, "valid": True},
    {"name": "status: SUBMITTED is reached by evidence, not status", "def": "StatusUpdate", "value": {"status": "SUBMITTED"}, "valid": False},
    {"name": "evidence", "def": "EvidenceSubmission", "value": {"performerRef": "worker-7731", "actor": {"actorType": "HUMAN"}, "executedAt": "2026-11-16T19:42:10Z", "attestation": {"statement": "I photographed cooler 4 after restocking.", "attestedBy": "Acme performer worker-7731"}, "assets": [{"evidenceId": "after_image", "path": "after/cooler_4.jpg", "origin": "THIRD_PARTY_SUBMITTED", "contentType": "image/jpeg", "blobPathname": "prv/asg_5h2j8k3l6m9n1p4q/after_image"}]}, "valid": True},
    {"name": "evidence: captured through the link (no assets)", "def": "EvidenceSubmission", "value": {"performerRef": "worker-7731", "actor": {"actorType": "HUMAN"}, "executedAt": "2026-11-16T19:42:10Z", "assets": []}, "valid": True},
    {"name": "evidence: provider can't claim TELEPORT_CAPTURE", "def": "EvidenceSubmission", "value": {"performerRef": "w", "actor": {"actorType": "HUMAN"}, "executedAt": "2026-11-16T19:42:10Z", "assets": [{"evidenceId": "a", "path": "a.jpg", "origin": "TELEPORT_CAPTURE", "url": "https://acme.example/a.jpg"}]}, "valid": False},
    {"name": "evidence: an asset with two sources", "def": "EvidenceSubmission", "value": {"performerRef": "w", "actor": {"actorType": "HUMAN"}, "executedAt": "2026-11-16T19:42:10Z", "assets": [{"evidenceId": "a", "path": "a.jpg", "origin": "THIRD_PARTY_SUBMITTED", "url": "https://acme.example/a.jpg", "blobPathname": "prv/x"}]}, "valid": False},
    {"name": "error", "def": "Error", "value": {"error": {"code": "over_ceiling", "message": "The quote is above the offer's pay ceiling.", "details": {"payCeilingCents": 2500}}}, "valid": True},
]


def compact(v) -> str:
    return json.dumps(v, separators=(",", ":"), ensure_ascii=False)


def signed_cases():
    body = compact(event("offer.created"))
    other_kid = jwk(OTHER_KEY)["kid"]
    attached_p, _, attached_s = sign(body).split(".")
    return [
        {"name": "valid offer.created", "body": body, "signature": sign(body), "expect": "valid"},
        {"name": "valid decision.made", "body": compact(event("decision.made")), "signature": sign(compact(event("decision.made"))), "expect": "valid"},
        {"name": "valid sync quote request", "body": compact(MESSAGES[[m["name"] for m in MESSAGES].index("quote request (sync)")]["value"]), "signature": sign(compact(MESSAGES[[m["name"] for m in MESSAGES].index("quote request (sync)")]["value"])), "expect": "valid"},
        {"name": "body changed after signing", "body": body.replace('"amountCents":2500', '"amountCents":9500'), "signature": sign(body), "expect": "invalid", "reason": "signature"},
        {"name": "signed 301 seconds before now", "body": body, "signature": sign(body, ts=NOW - TOLERANCE - 1), "expect": "invalid", "reason": "stale"},
        {"name": "signed 301 seconds after now", "body": body, "signature": sign(body, ts=NOW + TOLERANCE + 1), "expect": "invalid", "reason": "stale"},
        {"name": "an outcome-webhook signature (wrong typ)", "body": body, "signature": sign(body, header_over={"typ": "teleport-outcome+json"}), "expect": "invalid", "reason": "typ"},
        {"name": "alg isn't ES256", "body": body, "signature": sign(body, header_over={"alg": "HS256"}), "expect": "invalid", "reason": "alg"},
        {"name": "kid not in the JWKS", "body": body, "signature": sign(body, priv=OTHER_KEY, header_over={"kid": other_kid}), "expect": "invalid", "reason": "kid"},
        {"name": "right kid, wrong key", "body": body, "signature": sign(body, priv=OTHER_KEY), "expect": "invalid", "reason": "signature"},
        {"name": "not detached (payload in the middle part)", "body": body, "signature": f"{attached_p}.{b64u(body.encode())}.{attached_s}", "expect": "invalid", "reason": "format"},
    ]


def build():
    return {
        "protocol": "teleport.provider/0.1",
        "about": "Test vectors for TAP Provider Protocol v0.1. The key is a published TEST key: never trust it outside tests.",
        "now": NOW,
        "toleranceSeconds": TOLERANCE,
        "jwks": PUBLIC_JWKS,
        "testPrivateJwk": TEST_JWK,
        "signed": signed_cases(),
        "messages": MESSAGES,
    }


# ---------- An independent verifier (§4.2 steps), used by --check ----------

def verify(body: str, signature: str, jwks: dict, now: int) -> str:
    parts = signature.split(".")
    if len(parts) != 3 or parts[1] != "":
        return "format"
    header = json.loads(b64u_dec(parts[0]))
    if header.get("alg") != "ES256":
        return "alg"
    if header.get("typ") != "teleport-provider+json":
        return "typ"
    if abs(now - int(header.get("teleport-ts", 0))) > TOLERANCE:
        return "stale"
    key = next((k for k in jwks["keys"] if k["kid"] == header.get("kid")), None)
    if not key:
        return "kid"
    pub = ec.EllipticCurvePublicNumbers(int.from_bytes(b64u_dec(key["x"]), "big"), int.from_bytes(b64u_dec(key["y"]), "big"), ec.SECP256R1()).public_key()
    raw = b64u_dec(parts[2])
    der = encode_dss_signature(int.from_bytes(raw[:32], "big"), int.from_bytes(raw[32:], "big"))
    try:
        pub.verify(der, f"{parts[0]}.{b64u(body.encode())}".encode(), ec.ECDSA(hashes.SHA256()))
    except InvalidSignature:
        return "signature"
    return "valid"


def check(v) -> list[str]:
    problems = []
    for c in v["signed"]:
        got = verify(c["body"], c["signature"], v["jwks"], v["now"])
        want = "valid" if c["expect"] == "valid" else c["reason"]
        if got != want:
            problems.append(f"signed: {c['name']}: got {got}, want {want}")
    for m in v["messages"]:
        validator = Draft202012Validator({**SCHEMA, "$ref": f"#/$defs/{m['def']}"}, format_checker=FormatChecker())
        errors = list(validator.iter_errors(m["value"]))
        if m["valid"] and errors:
            problems.append(f"message: {m['name']}: expected valid, got {errors[0].message}")
        if not m["valid"] and not errors:
            problems.append(f"message: {m['name']}: expected invalid, but it validates")
    return problems


if __name__ == "__main__":
    v = build()
    text = json.dumps(v, indent=2, ensure_ascii=False) + "\n"
    if "--check" in sys.argv:
        problems = check(v)
        if OUT.read_text() != text:
            problems.append(f"{OUT.name} is stale: run without --check to regenerate")
        for p in problems:
            print("FAIL", p)
        print(f"{len(v['signed'])} signed cases, {len(v['messages'])} messages: {'ok' if not problems else f'{len(problems)} problem(s)'}")
        sys.exit(1 if problems else 0)
    problems = check(v)
    if problems:
        print("\n".join(problems))
        sys.exit(1)
    OUT.write_text(text)
    print(f"wrote {OUT.name}: {len(v['signed'])} signed cases, {len(v['messages'])} messages")
