#!/usr/bin/env python3
"""Agent Hotel - guest verifier for signed action receipts.

Usage:  python3 verify_receipts.py receipts.jsonl --pubkey hotel.pub [--head N:SHA256]
Exit:   0 = log valid, 1 = log invalid (tampered, unsigned, empty, wrong key), 2 = usage error.
Needs only Python 3 and the 'cryptography' package (pip install cryptography).

Each line is one receipt: canonical JSON (sorted keys, no spaces, UTF-8), signed with
the hotel's Ed25519 key. Every receipt carries the SHA-256 of the previous line, so a
changed, deleted or reordered line breaks the chain. --head pins the last line the hotel
published (count and hash) and also catches lines cut off the end.
"""
import base64, hashlib, json, sys

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

GENESIS = "0" * 64
FIELDS = {"v", "seq", "ts", "room", "session", "tool", "input", "input_sha256",
          "output_sha256", "prev", "sig"}


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


def load_pubkey(path):
    raw = base64.b64decode(open(path).read().strip())
    return Ed25519PublicKey.from_public_bytes(raw)


def verify(data: bytes, pub, head=None):
    """Return (ok, message, count, last_hash)."""
    if not data:
        return False, "empty log", 0, None
    if not data.endswith(b"\n"):
        return False, "log does not end with a newline (cut or appended bytes)", 0, None
    prev, n = GENESIS, 0
    for n, line in enumerate(data[:-1].split(b"\n"), 1):
        try:
            rec = json.loads(line.decode("utf-8"))
        except (UnicodeDecodeError, ValueError):
            return False, f"line {n}: not valid JSON", n, None
        if not isinstance(rec, dict) or set(rec) != FIELDS:
            return False, f"line {n}: wrong or missing fields (unsigned?)", n, None
        if canon(rec) != line:
            return False, f"line {n}: not in canonical form (bytes altered)", n, None
        if rec["v"] != 1 or rec["seq"] != n:
            return False, f"line {n}: sequence {rec['seq']} where {n} expected", n, None
        if rec["prev"] != prev:
            return False, f"line {n}: chain broken (line deleted, reordered or changed before it)", n, None
        body = {k: v for k, v in rec.items() if k != "sig"}
        try:
            pub.verify(base64.b64decode(rec["sig"], validate=True), canon(body))
        except (InvalidSignature, ValueError):
            return False, f"line {n}: bad signature (changed, or not signed by this hotel key)", n, None
        prev = hashlib.sha256(line).hexdigest()
    if head:
        want_n, want_h = head.split(":", 1)
        if int(want_n) != n or want_h != prev:
            return False, f"head mismatch: log ends at {n}:{prev[:16]}..., hotel published {want_n}:{want_h[:16]}...", n, prev
    return True, f"OK: {n} receipts, chain and signatures valid", n, prev


def main(argv):
    args, pubkey, head = [], None, None
    it = iter(argv)
    for a in it:
        if a == "--pubkey":
            pubkey = next(it, None)
        elif a == "--head":
            head = next(it, None)
        else:
            args.append(a)
    if len(args) != 1 or not pubkey:
        print(__doc__.strip().splitlines()[2], file=sys.stderr)
        return 2
    ok, msg, n, last = verify(open(args[0], "rb").read(), load_pubkey(pubkey), head)
    print(("VALID " if ok else "INVALID ") + msg)
    if ok:
        print(f"head {n}:{last}")
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
