#!/usr/bin/env python3
"""Standalone OMEGA SEAL verifier (CAIN-42). Imports no CAIN code: Python stdlib + `cryptography` only.

Checks one OMEGA SEAL offline: schema, Ed25519 signature over the domain-separated canonical body, that an
authorizing seal records an ALLOWED verdict, and its validity window. It cannot check single use: only the
redemption ledger (POST https://cainstudio.online/fabric/omega-seal/redeem) can tell whether a seal was spent.

  python3 -I verify_omega_seal.py seal.json --keys keys.json
  python3 -I verify_omega_seal.py seal.json --keys https://cainstudio.online/fabric/omega-seal   (fetches keys)

keys.json: {"<key_id>": "<base64 raw Ed25519 public key>", ...} or the JSON served at /fabric/omega-seal.
Pin the keys out of band for an independent check; fetching them from the issuer only checks consistency.
Exit 0 only for VALID.
"""
import base64
import hashlib
import json
import sys
import urllib.request
from datetime import datetime, timedelta, timezone

SCHEMA, NAME, DOMAIN = "cain42.omega_seal.v1", "OMEGA SEAL", "cain42.omega-seal.v1"


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8")


def message(seal):
    body = {k: v for k, v in seal.items() if k != "signature_b64"}
    return f"{DOMAIN}\x1f{hashlib.sha256(canon(body)).hexdigest()}".encode("utf-8")


def load_keys(src):
    if src.startswith("https://"):
        with urllib.request.urlopen(urllib.request.Request(src, headers={"User-Agent": "omega-seal-verify/1"}),
                                    timeout=20) as r:
            data = json.load(r)
    else:
        data = json.load(open(src))
    return data.get("keys", data)


def verify(seal, keys, now=None):
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    need = ("schema", "name", "seal_id", "decision_id", "verdict", "authorizes", "record_digest", "issued_at",
            "expires_at", "single_use", "key_id", "signature_b64")
    if not isinstance(seal, dict) or any(k not in seal for k in need):
        return "MALFORMED", "missing fields"
    if seal["schema"] != SCHEMA or seal["name"] != NAME or seal["single_use"] is not True:
        return "MALFORMED", "not an OMEGA SEAL v1"
    if seal["authorizes"] is True and seal["verdict"] != "ALLOWED":
        return "MALFORMED", "authorizing seal with a non-ALLOWED verdict"
    n = seal.get("seal_number")
    if "seal_number" in seal and (not isinstance(n, int) or isinstance(n, bool) or n < 1 or seal.get("seal_label") != f"OMEGA-{n:09d}"):
        return "MALFORMED", "bad OMEGA SEAL number/label"
    raw = keys.get(seal["key_id"])
    if not raw:
        return "UNKNOWN_KEY", seal["key_id"]
    try:
        Ed25519PublicKey.from_public_bytes(base64.b64decode(raw)).verify(base64.b64decode(seal["signature_b64"]),
                                                                          message(seal))
    except Exception:
        return "INVALID_SIGNATURE", "signature does not verify"
    fmt = "%Y-%m-%dT%H:%M:%SZ"
    issued = datetime.strptime(seal["issued_at"], fmt).replace(tzinfo=timezone.utc)
    expires = datetime.strptime(seal["expires_at"], fmt).replace(tzinfo=timezone.utc)
    now = now or datetime.now(timezone.utc)
    if now < issued - timedelta(seconds=5):
        return "NOT_YET_VALID", seal["issued_at"]
    if seal["authorizes"] is not True:
        return "VALID", f"authentic receipt of verdict {seal['verdict']}; does NOT authorize action"
    if now >= expires:
        return "EXPIRED_AUTHENTIC", f"authentic YES, window ended {seal['expires_at']}; can no longer be redeemed"
    return "VALID", "authentic authorizing seal inside its window (single use is checked only by redemption)"


def main(argv):
    if len(argv) < 4 or argv[2] != "--keys":
        print(__doc__); return 2
    seal = json.load(open(argv[1]))
    seal = seal.get("omega_seal", seal)        # accept a whole decision response too
    result, detail = verify(seal, load_keys(argv[3]))
    print(json.dumps({"result": result, "detail": detail, "seal_label": seal.get("seal_label"), "verdict": seal.get("verdict"),
                      "authorizes": seal.get("authorizes"), "decision_id": seal.get("decision_id"),
                      "seal_id": seal.get("seal_id")}, indent=1))
    return 0 if result in ("VALID", "EXPIRED_AUTHENTIC") else 1


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