"""CAIN-A75-070 offline verifier (rules embedded verbatim). CAIN-A75-070 retailer brand-agent rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

A retailer agent speaking for a brand inside someone else's search surface is a delegated representative. Its claims, prices
and commitments need a source and a limit. Give it a bounded representation mandate: which catalogue, which prices, which
promises. A claim outside the mandate is refused, and every answer cites its source. The review recomputes every answer:

  mandate      a named human issued the mandate for one surface, with a catalogue, a price book, the store policies, the
               allowed claim types and an expiry; every answer was given on that surface before expiry
  claims       every claim is of an allowed type and about a catalogued product; its value equals the source record:
               price (price-book entry valid at the answer time, same currency), spec (the product record's field),
               availability (stock > 0), return_policy / warranty / shipping (the store policy)
  sources      every claim cites the record it came from (product record or price book) with that record's SHA-256
  refusals     every requested topic outside the allowed claim types is listed as refused and no claim of that type is made
  claims       every boolean the record asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND. It reviews the answer record; it does
not query the retailer's systems or the search surface.
"""
from __future__ import annotations

import math
import re

_ID = re.compile(r"^[A-Za-z0-9_.:\-/@]{1,120}$")
POLICY_TYPES = ("return_policy", "warranty", "shipping")


class Bad(ValueError):
    pass


def _num(v, what, lo=0.0, hi=1e15):
    if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not (lo <= v <= hi):
        raise Bad(f"{what} must be a finite number in [{lo}, {hi}]")
    return float(v)


def evaluate(record):
    checks, summary = [], {}

    def c(cid, ok, detail=""):
        checks.append({"id": cid, "ok": bool(ok), "detail": detail})

    try:
        if not isinstance(record, dict) or record.get("schema") != "cain42.a75.brandagent.review.v1":
            raise Bad("not a cain42.a75.brandagent.review.v1 record")
        m = record.get("mandate")
        if not isinstance(m, dict):
            raise Bad("mandate must be an object")
        catalogue, allowed = m.get("catalogue"), m.get("allowed_claim_types")
        prices, policies = m.get("price_book"), m.get("policies")
        if not isinstance(catalogue, list) or not isinstance(allowed, list) or not isinstance(prices, dict) or not isinstance(policies, dict):
            raise Bad("mandate needs catalogue, allowed_claim_types, price_book and policies")
        expires = _num(m.get("expires_at"), "mandate.expires_at")
        products = record.get("products")
        if not isinstance(products, dict):
            raise Bad("products must be an object")
        c("mandate.issued", isinstance(m.get("issued_by"), str) and m["issued_by"].startswith("human:") and isinstance(m.get("surface"), str),
          f"issued by {m.get('issued_by')!r} for surface {m.get('surface')!r}")
        answers = record.get("answers")
        if not isinstance(answers, list) or not answers or not all(isinstance(a, dict) for a in answers):
            raise Bad("answers must be a non-empty list of objects")
        n_claims = n_refused = 0
        for a in answers:
            aid = a.get("id") if isinstance(a.get("id"), str) and _ID.match(a["id"]) else None
            if aid is None:
                raise Bad("an answer needs an id")
            at = _num(a.get("at"), f"{aid}.at")
            c(f"answer.{aid}.scope", a.get("surface") == m.get("surface") and at < expires,
              f"on {a.get('surface')!r} at {at:g}; mandate {m.get('surface')!r} until {expires:g}")
            claims = a.get("claims") if isinstance(a.get("claims"), list) else []
            for j, cl in enumerate(claims, start=1):
                if not isinstance(cl, dict):
                    raise Bad(f"{aid} claim must be an object")
                n_claims += 1
                cid, typ, sku, val = f"answer.{aid}.claim{j}", cl.get("type"), cl.get("sku"), cl.get("value")
                src = cl.get("source") if isinstance(cl.get("source"), dict) else {}
                c(f"{cid}.allowed", typ in allowed and (typ in POLICY_TYPES or sku in catalogue),
                  f"{typ!r} about {sku!r}; allowed {allowed}")
                prod = products.get(sku) if isinstance(sku, str) else None
                truth, src_ok = None, False
                if typ == "price":
                    pe = prices.get(sku) if isinstance(sku, str) else None
                    if isinstance(pe, dict) and float(pe.get("valid_from", math.inf)) <= at < float(pe.get("valid_to", -1)):
                        truth = (pe.get("price"), pe.get("currency"))
                    val = (val, cl.get("currency"))
                    src_ok = src.get("record") == "price_book" and src.get("sha256") == m.get("price_book_sha256")
                elif typ == "spec":
                    truth = ((prod.get("specs") or {}).get(cl.get("field"))) if isinstance(prod, dict) and isinstance(cl.get("field"), str) else None
                    src_ok = isinstance(prod, dict) and src.get("record") == sku and src.get("sha256") == prod.get("sha256")
                elif typ == "availability":
                    truth = (prod.get("stock", 0) > 0) if isinstance(prod, dict) and isinstance(prod.get("stock"), int) else None
                    src_ok = isinstance(prod, dict) and src.get("record") == sku and src.get("sha256") == prod.get("sha256")
                elif typ in POLICY_TYPES:
                    truth = policies.get(typ)
                    src_ok = src.get("record") == "policies" and src.get("sha256") == m.get("policies_sha256")
                c(f"{cid}.true_to_source", truth is not None and val == truth, f"claimed {val!r}, source says {truth!r}")
                c(f"{cid}.cited", src_ok, f"cites {src.get('record')!r} {str(src.get('sha256'))[:12]}")
            requested = a.get("requested_types") if isinstance(a.get("requested_types"), list) else []
            refused = a.get("refused") if isinstance(a.get("refused"), list) else []
            out = sorted({t for t in requested if t not in allowed}, key=str)
            made = {cl.get("type") for cl in claims if isinstance(cl, dict)}
            n_refused += len(out)
            c(f"answer.{aid}.refusals", sorted(set(map(str, refused))) == [str(t) for t in out] and not (set(out) & made),
              f"requested outside the mandate {out}, refused {sorted(map(str, refused))}, claimed {sorted(map(str, made))}")

        def all_ok(pred):
            return all(x["ok"] for x in checks if pred(x["id"]))

        computed = {"within_mandate": all_ok(lambda i: i.endswith((".scope", ".allowed")) or i == "mandate.issued"),
                    "claims_true_to_source": all_ok(lambda i: i.endswith(".true_to_source")),
                    "sources_cited": all_ok(lambda i: i.endswith(".cited")),
                    "out_of_mandate_refused": all_ok(lambda i: i.endswith(".refusals"))}
        claims_ = record.get("claims") if isinstance(record.get("claims"), dict) else {}
        for k in sorted(claims_):
            c(f"claims.{k}", k in computed and claims_[k] == computed[k], f"claimed {claims_[k]!r}, computed {computed.get(k)!r}")
        summary.update({"computed": computed, "answers": len(answers), "claims_made": n_claims, "refused": n_refused})
    except Bad as e:
        checks.append({"id": "input.well_formed", "ok": False, "detail": str(e)})
        return "UNSOUND", checks, summary
    except Exception as e:  # noqa: BLE001
        checks.append({"id": "input.error", "ok": False, "detail": f"{type(e).__name__}: {e}"[:200]})
        return "UNSOUND", checks, summary
    return ("SOUND" if all(x["ok"] for x in checks) else "UNSOUND"), checks, summary


# ---------------------------------------------------------------------------- offline verifier (no CAIN imports)
# Every name below is prefixed _kit_verifier_ / _b64 / _hl / _json / _sys so it cannot shadow a name in the rules above.
import base64 as _b64, hashlib as _hl, json as _json, sys as _sys
_KIT_VERIFIER_GENESIS = _hl.sha256(b"cain42.a75.brandagent.genesis").hexdigest()


def _kit_verifier_canon(o):
    return _json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()


def _kit_verifier_sha(o):
    return _hl.sha256(_kit_verifier_canon(o)).hexdigest()


def _kit_verifier_main(argv):
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    if len(argv) < 2:
        print("usage: verify_offline.py run.json --pinned-key BASE64"); return 2
    run = _json.load(open(argv[1]))
    pin = argv[argv.index("--pinned-key") + 1] if "--pinned-key" in argv else None
    problems, prev, recs = [], _KIT_VERIFIER_GENESIS, run.get("records") or []
    for i, r in enumerate(recs):
        body = {k: v for k, v in r.items() if k not in ("record_hash", "signature_b64")}
        if _kit_verifier_sha(body) != r.get("record_hash"): problems.append(f"record {i}: record_hash does not match")
        if body.get("subject_sha256") != _kit_verifier_sha(body.get("subject")): problems.append(f"record {i}: subject_sha256 does not match")
        if pin and r.get("public_key_b64") != pin: problems.append(f"record {i}: different key than the pinned one")
        try:
            Ed25519PublicKey.from_public_bytes(_b64.b64decode(pin or r.get("public_key_b64"))).verify(
                _b64.b64decode(r.get("signature_b64", "")), str(r.get("record_hash")).encode())
        except Exception:
            problems.append(f"record {i}: signature does not verify")
        if r.get("prev_record_hash") != prev: problems.append(f"record {i}: chain link broken")
        v, checks, _ = evaluate(r.get("subject"))
        if v != r.get("verdict") or checks != r.get("checks"):
            problems.append(f"record {i}: re-running the rules gives {v}, the record says {r.get('verdict')}")
        prev = r.get("record_hash")
    if run.get("run_hash") != _kit_verifier_sha([r.get("record_hash") for r in recs]): problems.append("run_hash does not match")
    for p in problems: print("  -", p)
    if not pin: print("WARNING: no --pinned-key given; the signature was checked against the key inside the file")
    print("VERDICT:", "VERIFIED" if not problems else "TAMPERED OR INVALID", f"(CAIN-A75-070, {len(recs)} record(s), verdicts {run.get('verdicts')})")
    return 0 if not problems else 1


if __name__ == "__main__":
    _sys.exit(_kit_verifier_main(_sys.argv))
