#!/usr/bin/env python3
"""Golden Codex 1.2.0: builds the three schema files, the example records for every tier, the tests and the vectors.
The full record is the canon; the label and the pointer are generated from it by project(). Rules: SPEC.md.

Usage: build.py <outdir>"""
import base64, copy, gzip, hashlib, json, os, sys
import jsonschema

OUT = sys.argv[1]
BASE = "https://aeternumfoundation.org/schema/golden-codex/1.2.0"
DST = ["digitalCapture", "computationalCapture", "negativeFilm", "positiveFilm", "print", "humanEdits", "compositeWithTrainedAlgorithmicMedia",
       "algorithmicallyEnhanced", "digitalCreation", "dataDrivenMedia", "trainedAlgorithmicMedia", "algorithmicMedia", "screenCapture",
       "virtualRecording", "composite", "compositeCapture", "compositeSynthetic"]
AI_TYPES = ["trainedAlgorithmicMedia", "compositeWithTrainedAlgorithmicMedia", "algorithmicMedia"]

def obj(props, required=(), desc=None, **kw):
    d = {"type": "object", "additionalProperties": False, "properties": props}
    if required: d["required"] = list(required)
    if desc: d["description"] = desc
    d.update(kw); return d
def s(desc=None, **kw):
    d = {"type": "string", "minLength": 1}
    if desc: d["description"] = desc
    d.update(kw); return d
def arr(items, desc=None, **kw):
    d = {"type": "array", "items": items}
    if desc: d["description"] = desc
    d.update(kw); return d
ref = lambda n: {"$ref": f"#/$defs/{n}"}
URI = {"type": "string", "format": "uri", "minLength": 8}
TIME = {"type": "string", "pattern": r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$"}
DIGEST = s("A fingerprint: sha256- followed by the 32 bytes in base64url (43 characters).", pattern="^sha256-[A-Za-z0-9_-]{43}$")
MADE = {"enum": DST + ["empty", "trainedAlgorithmicData", "not_determined"],
        "description": "How the pixels were made: the IPTC Digital Source Type term (or one of the two C2PA terms), or not_determined. The full URI is http://cv.iptc.org/newscodes/digitalsourcetype/<term>."}
AI = obj({"by": s("Provider."), "sys": s("System and version."), "at": TIME, "id": s("Content identifier.")}, required=["by", "sys"],
         desc="AI disclosure carried in the file at every tier: provider, system and version, time, identifier.")

# ---------------- definitions shared by the FULL record ----------------
defs = {}
defs["source"] = obj({"party": s("Who stated it: an institution, a rights holder, a catalogue, a tool."), "url": URI, "citation": s(), "retrieved_at": TIME,
                      "method": {"enum": ["api_field", "institution_policy", "published_catalogue", "holder_statement", "manual_review", "file_metadata", "measured_by_tool"]},
                      "evidence": DIGEST},
                     required=["party", "method"], anyOf=[{"required": ["url"]}, {"required": ["citation"]}, {"required": ["evidence"]}],
                     desc="A recoverable source for a reported fact. The record reports the fact; it does not assert it.")
defs["agent"] = obj({"name": s("A name. A living person is named only at their own request; otherwise a living person is a ref."),
                     "ref": s("Opaque reference that resolves off the permanent record and can be erased.", pattern="^[A-Za-z0-9._:-]{6,128}$"),
                     "type": {"enum": ["person", "group", "organization", "software", "ai_model", "ai_persona", "public", "unknown"]},
                     "historical": {"const": True, "description": "Set for a person named from the historical public record."},
                     "own_request": obj({"at": TIME, "told_permanent": {"const": True, "description": "The person was told, before inscription, that an inscribed name cannot be removed, and confirmed."}}, required=["at", "told_permanent"],
                                        desc="Set when a living person asked to be named. Only the person themself may ask; nobody names another living person."),
                     "ids": arr(s(), "Authority identifiers: ulan:..., viaf:..., wikidata:..., a DID."), "version": s()},
                    required=["type"],
                    allOf=[{"if": {"properties": {"type": {"const": "person"}}, "required": ["name"]}, "then": {"anyOf": [{"required": ["historical"]}, {"required": ["own_request"]}]}}])
defs["authorship"] = obj({"by": ref("agent"),
                          "mode": {"enum": ["creator_statement", "documented_scholarship", "curatorial_interpretation", "machine_reading", "imaginative_oracle"]},
                          "basis": s("What it rests on."), "sources": arr(ref("source")), "certainty": {"enum": ["documented", "probable", "possible", "speculative"]},
                          "human_reviewed": {"type": "boolean"}},
                         required=["by", "mode", "certainty"],
                         allOf=[{"if": {"anyOf": [{"properties": {"mode": {"enum": ["creator_statement", "documented_scholarship"]}}}, {"properties": {"certainty": {"const": "documented"}}}]},
                                 "then": {"required": ["sources"], "properties": {"sources": {"minItems": 1}}}}],
                         desc="Who wrote an interpretive section, what kind of statement it is, what it rests on, and how certain it is.")
A = {"authorship": ref("authorship")}
defs["rights_statement"] = obj({"about": {"enum": ["original_work", "reproduction", "image_file"]}, "status": URI, "notice": s(), "holder": s("As reported."),
                                "credit_line": s("The credit the image's supplier requires."), "web_statement": URI, "jurisdiction": s(), "source": ref("source")},
                               required=["about", "status", "source"], desc="One statement of rights in the work or image: declared by the author in their own name, or carried as a named source reports it. Whoever stands behind it is always named.")
defs["event"] = obj({"type": {"enum": ["creation", "ai_generation", "digitisation", "acquisition", "modification", "enrichment", "validation", "registration", "inscription", "recovery", "correction", "supersession"]},
                     "at": s("ISO 8601, any precision, or 'unknown'."), "by": arr(ref("agent")), "inputs": arr(s()), "changed": arr(s()),
                     "evidence": ref("source"), "evidence_gap": s("States plainly that no evidence is held, and why.")},
                    required=["type", "at"],
                    allOf=[{"oneOf": [{"required": ["evidence"]}, {"required": ["evidence_gap"]}]},
                           {"if": {"properties": {"type": {"const": "supersession"}}}, "then": {"required": ["by", "inputs", "changed"], "properties": {"by": {"minItems": 1}, "inputs": {"minItems": 1}, "changed": {"minItems": 1}}}}])
# Extensions are free-form: the standard does not police what a product adds under its own address.
defs["ext_object"] = {"type": "object", "additionalProperties": ref("ext_value")}
defs["ext_value"] = {"anyOf": [{"type": ["string", "integer", "boolean", "null"]}, ref("ext_object"), {"type": "array", "items": ref("ext_value")}]}

full_props = {
    "schemaVersion": {"const": "1.2.0"},
    "tier": {"const": "full"},
    "timestamp": obj({"created": TIME, "enriched": TIME, "embedded": TIME, "issued": TIME}),
    "_identifiers": obj({"artifactId": s(), "codexId": s(), "uuid": s(), "earlier": arr(s(), "Every earlier identifier, namespace-qualified. None is dropped."),
                         "issuer": s("Who issued this record: one reference, stated once.")},
                        required=["artifactId"], desc="The record's Soulmark is computed from the record, so it is never stored inside it and cannot drift from it. See SPEC.md section 3."),
    "binding": obj({"image": DIGEST, "renditions": arr(DIGEST, "The Soulmarks of other files of this same picture that the record vouches for: a thumbnail, a web copy, another format. A label or pointer may travel only with an image listed here or with the image itself."), "media_type": s(), "width": {"type": "integer"}, "height": {"type": "integer"},
                    "perceptual": arr(obj({"alg": s(), "value": s()}, required=["alg", "value"]))}, required=["image"],
                   desc="The image this record describes. 'image' is the image's Soulmark: SHA-256 over everything in the file that determines what the picture looks like and nothing that is metadata, under the rule in SPEC.md section 4. The rule is defined for JPEG and PNG, and embedding a record never changes the value."),
    "title": s(),
    "description": s("What is shown, factually."),
    "visual_analysis": obj({"color_palette": arr(obj({"color_name": s(), "hex": s(pattern="^#[0-9A-Fa-f]{6}$"), "description": s()}, required=["hex"])),
                            "composition": s(), "lighting_and_shading": s(), "style_and_technique": s(), "objective_description": s(), **A}, required=["authorship"]),
    "artistic_statement": obj({"intent": s(), "themes": arr(s()), **A}, required=["authorship"], desc="The creator's own words, and only those.",
                              ),
    "contextual_graph": obj({"keywords": arr(s()), "related_artistic_movements": arr(s()), "related_concepts": arr(s()), "schema_org_type": s()},
                            desc="Terms that help a reader find the work. They assert no meaning, so they carry no authorship."),
    "emotional_and_thematic_journey": obj({"primary_emotion": s(), "secondary_emotions": arr(s()), "mood": s(), "narrative_arc": s(), **A}, required=["authorship"]),
    "symbolism_and_iconography": obj({"primary_symbols": {"type": "object", "additionalProperties": {"type": "string"}}, "secondary_symbols": {"type": "object", "additionalProperties": {"type": "string"}},
                                      "archetypal_elements": arr(s()), **A}, required=["authorship"]),
    "cultural_and_artistic_context": obj({"period_and_movement": s(), "influences": s(), "iconography": s(), "cultural_significance": s(), **A}, required=["authorship"]),
    "provenance_and_lineage": obj({"artist_information": s(), "creation_date": s(), "technical_lineage": s(), "provenance": s(),
                                   "sources": arr(obj({"kind": {"enum": ["original_work", "object_or_impression", "reproduction", "earlier_digital_record"]}, "id": s(), "fingerprint": DIGEST, "source": ref("source")}, required=["kind", "source"])),
                                   "events": arr(ref("event")),
                                   "supersedes": obj({"record": DIGEST, "id": s(), "reason": s()}, required=["record", "reason"], desc="The record this one replaces, identified by its Soulmark. The earlier record is never edited and remains evidence."),
                                   "first_inscribed": obj({"at": s(), "evidence": ref("source"), "evidence_gap": s()}, required=["at"], oneOf=[{"required": ["evidence"]}, {"required": ["evidence_gap"]}])},
                                  allOf=[{"if": {"required": ["supersedes"]}, "then": {"required": ["first_inscribed"]}}]),
    "technical_details": obj({"medium_and_technique": s(), "dimensions": obj({"width": {"type": "integer"}, "height": {"type": "integer"}, "unit": s()}), "file_format": s(), "color_space": s()}),
    "creation_credits": obj({"credits": arr(obj({"agent": ref("agent"), "role": s(), "subject": {"enum": ["original_work", "reproduction", "image_file", "record", "interpretation"]},
                                                 "qualifier": {"enum": ['attributed to', 'workshop of', 'studio of', 'circle of', 'follower of', 'manner of', 'school of', 'after', 'copy after', 'probably by', 'possibly by', 'office of'], "description": "How firmly the work is given to this maker, in the fixed terms cataloguers use."}, "evidence": {"enum": ["documented", "attributed", "inferred", "disputed", "unknown"]},
                                                 "source": ref("source")}, required=["agent", "role"],
                                                allOf=[{"if": {"properties": {"evidence": {"const": "documented"}}, "required": ["evidence"]}, "then": {"required": ["source"]}}])),
                             "made": MADE, "made_source": ref("source"), "ai": AI, "human_contribution": s("No personal data: this text is permanent.")},
                            allOf=[{"if": {"properties": {"made": {"enum": AI_TYPES}}, "required": ["made"]}, "then": {"required": ["ai"]}}, {"if": {"required": ["ai"]}, "then": {"required": ["made"], "properties": {"made": {"enum": AI_TYPES}}}},
                                   {"if": {"properties": {"made": {"enum": DST + ["empty", "trainedAlgorithmicData"]}}, "required": ["made"]}, "then": {"required": ["made_source"]}}]),
    "rights": obj({"work": arr(ref("rights_statement")),
                   "ai_use": obj({"cawg.data_mining": {"enum": ["allowed", "notAllowed", "constrained"]}, "cawg.ai_inference": {"enum": ["allowed", "notAllowed", "constrained"]},
                                  "cawg.ai_generative_training": {"enum": ["allowed", "notAllowed", "constrained"]}, "cawg.ai_training": {"enum": ["allowed", "notAllowed", "constrained"]},
                                  "source": ref("source")}, required=["source"], desc="The maker's preference on AI use, as a named source reports it. The four field names are the training and data mining terms published by the Creator Assertions Working Group, used unchanged so that a preference stated there can be carried here without translation."),
                   "grants": arr(obj({"right": {"enum": ['ownership', 'copyright', 'trade', 'curation', 'custody', 'control', 'display', 'reproduction', 'commercial_use', 'modification', 'ai_training', 'ai_inference', 'data_mining'], "description": "Which right. Rights are separate: one party may hold the right to trade while another holds curation."},
                                      "in": {"enum": ["work", "image", "record"], "description": "What the right is in: the work itself, this image file, or this record (for an inscribed record, the asset)."},
                                      "held_by": ref("agent"), "granted_by": ref("agent"), "basis": ref("source"),
                                      "from": s("ISO 8601 date or time."), "until": s("ISO 8601 date or time. Absent means no end is stated."), "conditions": s("Conditions on the right, in words: attribution required, non-exclusive, and so on."),
                                      "fee": obj({"amount": s("A plain decimal number as text.", pattern="^(0|[1-9][0-9]*)(\\.[0-9]+)?$"), "currency": s("Currency or token symbol."), "per": {"enum": ["use", "item", "month", "year", "once"]}, "pay_to": s("Where the fee is paid: a wallet address or a payment address.")},
                                                 required=["amount", "currency", "per"], desc="A predetermined fee for exercising this right, set by whoever grants it. Used for training rights in particular.")},
                                     required=["right", "in", "held_by", "basis"], dependentRequired={"fee": ["granted_by"]}),
                                 "Who holds which right, by whose grant, on what basis. An owner and a curator can both exist for the same record."),
                   "record": obj({"license": URI}, desc="The licence of the record itself.")},
                  desc="What the record establishes about rights: the rights the author declares in the work, rights as other named sources report them, who holds which right by whose grant, and the maker's preference on AI use. An author who declares nothing leaves this empty."),
    "content_credentials": obj({"state": {"enum": ["none", "malformed", "invalid", "wellFormed", "valid", "trusted"]}, "codes": arr(s()), "signer": s(), "claim_generator": s(),
                                "trust_list": URI, "validator": s("Name and version."), "validated_at": TIME},
                               required=["state", "validator", "validated_at"],
                               allOf=[{"if": {"properties": {"state": {"enum": ["malformed", "invalid", "wellFormed"]}}}, "then": {"required": ["codes"], "properties": {"codes": {"minItems": 1}}}},
                                      {"if": {"properties": {"state": {"const": "trusted"}}}, "then": {"required": ["trust_list"]}}],
                               desc="What a validator read in the file, together with the validator and the time. This is a report, never a property of the work."),
    "archival": obj({"institution": s(), "collection_name": s(), "inventory_number": s(), "curator_notes": s(), "alt_text": s(maxLength=250), "extended_description": s()}),
    "extensions": {"type": "object", "propertyNames": {"pattern": "^https://"}, "additionalProperties": ref("ext_object")},
}
full_props["soul_whisper"] = obj({"text": s("The message in the bottle: free, unstructured, poetic or personal words about the work."), "language": s(),
    "voice": {"enum": ["artist", "artist_persona"], "description": "Whose voice the whisper carries: a human artist or an artist persona. This is always stated."},
    "by": ref("agent"),
    "private": obj({"scheme": {"enum": ["hmac-sha-256", "salted-sha-256"]}, "commitment": DIGEST}, required=["scheme", "commitment"],
                   desc="A private whisper is held elsewhere; only a keyed commitment to it is written here. No message, sender or recipient.")},
    required=["voice", "by"], oneOf=[{"required": ["text"]}, {"required": ["private"]}],
    desc="The free, unstructured, poetic or personal addition to an otherwise structured record. A human artist or artist persona may write it, and the record says which. It holds either public text or a private commitment, never both.")
full_props["creation_credits"]["required"] = ["credits", "made"]; full_props["creation_credits"]["properties"]["credits"]["minItems"] = 1
full_props["artistic_statement"]["properties"]["authorship"] = {"allOf": [ref("authorship"), {"properties": {"mode": {"const": "creator_statement"}}}]}
full = {"$schema": "https://json-schema.org/draft/2020-12/schema", "$id": f"{BASE}/full.schema.json", "title": "Golden Codex: the full record (the canon)",
        "x-status": "Golden Codex 1.2.0.",
        "description": "The complete record for a visual work. Every smaller tier is generated from this record. It must state the version, an identifier, a title, the image's fingerprint, and who made the work and how. 'Unknown' and 'not_determined' are honest answers and must be stated. Other sections appear only when there is something true to say; when a section appears, its rules apply.",
        "type": "object", "additionalProperties": False, "properties": full_props, "required": ["schemaVersion", "_identifiers", "title", "binding", "creation_credits"], "$defs": defs}

RECORD = s("The record's Soulmark: the fingerprint of its canonical bytes. This value is the pointer. A record that does not hash to it is refused.", pattern="^sha256-[A-Za-z0-9_-]{43}$")
pointer = {"$schema": "https://json-schema.org/draft/2020-12/schema", "$id": f"{BASE}/pointer.schema.json", "title": "Golden Codex: the pointer",
           "x-status": full["x-status"],
           "description": "For thumbnails, previews and anything small or re-encoded. It says that a record exists and identifies that record. It claims nothing else about the work, except the AI disclosure when one applies.",
           "type": "object", "additionalProperties": False,
           "properties": {"gc": {"const": "1.2/pointer"}, "record": RECORD, "title": s(maxLength=120), "at": {**URI, "description": "Optional hint where the full record can be fetched. Any address; no one ledger is required."},
                          "made": {"enum": AI_TYPES, "description": "Carried only for an AI-made work: the IPTC Digital Source Type term."}, "ai": AI, "image": {**DIGEST, "description": "Optional: the Soulmark of THIS file's image, when the pointer is made for it."}},
           "required": ["gc", "record", "title"], "dependentRequired": {"ai": ["made"]},
           "allOf": [{"if": {"properties": {"made": {"enum": AI_TYPES}}, "required": ["made"]}, "then": {"required": ["ai"]}}]}
label = {"$schema": "https://json-schema.org/draft/2020-12/schema", "$id": f"{BASE}/label.schema.json", "title": "Golden Codex: the label",
         "x-status": full["x-status"],
         "description": "What a browser, shop, feed or agent can read without a second request. Every field copies a statement from the full record; none makes a new statement.",
         "type": "object", "additionalProperties": False,
         "properties": {"gc": {"const": "1.2/label"}, "record": RECORD, "title": s(maxLength=120), "at": URI, "made": MADE, "ai": AI,
                        "credit": s("One maker credit as carried by the full record, or 'unknown'.", maxLength=120), "status": {**URI, "description": "One rights status address, as reported in the full record."},
                        "description": s(maxLength=300), "alt_text": s(maxLength=250), "image": {**DIGEST, "description": "The image's Soulmark for THIS rendition: the fingerprint of this file's image, when the label is made for it."}},
         "required": ["gc", "record", "title", "image"], "dependentRequired": {"ai": ["made"]},
         "allOf": [{"if": {"properties": {"made": {"enum": AI_TYPES}}, "required": ["made"]}, "then": {"required": ["ai"]}}, {"if": {"required": ["ai"]}, "then": {"required": ["made"], "properties": {"made": {"enum": AI_TYPES}}}}]}

# ---------------- the rules a schema cannot hold: canonical bytes, the soulmark, the projection ----------------
def _whole(x):
    """Numbers in a record are whole. 1.0 is written 1; a number with a fraction has no canonical form and is refused."""
    if isinstance(x, bool) or x is None or isinstance(x, (str, int)): return x
    if isinstance(x, float):
        if x != int(x): raise ValueError("a record holds whole numbers only")
        return int(x)
    if isinstance(x, list): return [_whole(v) for v in x]
    return {k: _whole(v) for k, v in x.items()}
def canonical(rec):
    """One byte form for one record, as RFC 8785 gives it: UTF-8, no spaces, non-ASCII written as itself, whole numbers,
    and object keys sorted by their UTF-16 code units (which differs from code-point order only above U+FFFF)."""
    def w(x):
        if isinstance(x, dict):
            return "{" + ",".join(json.dumps(k, ensure_ascii=False) + ":" + w(x[k]) for k in sorted(x, key=lambda k: k.encode("utf-16-be"))) + "}"
        if isinstance(x, list): return "[" + ",".join(w(v) for v in x) + "]"
        return json.dumps(x, ensure_ascii=False)
    return w(_whole(rec)).encode("utf-8")
def soulmark(rec):
    return "sha256-" + base64.urlsafe_b64encode(hashlib.sha256(canonical(rec)).digest()).rstrip(b"=").decode()
def embedded(rec):
    """As written into an image: canonical bytes, then gzip with a fixed timestamp and base64, UNLESS that is larger than
    base64 of the plain bytes (it is, for a pointer). Returns (form, bytes)."""
    raw = canonical(rec); a = base64.b64encode(raw); b = base64.b64encode(gzip.compress(raw, 9, mtime=0))
    return ("plain", a) if len(a) <= len(b) else ("gzip", b)
MAKER_ROLES = {"artist", "creator", "author", "maker", "painter", "photographer", "sculptor", "illustrator", "designer", "printmaker", "draughtsman", "prompt author"}
def project(rec, tier, at=None, rendition=None):
    """A smaller tier, generated from the full record by rule. Same input, same bytes."""
    cc = rec.get("creation_credits") or {}
    out = {"gc": f"1.2/{tier}", "record": soulmark(rec), "title": rec["title"][:120]}
    if at: out["at"] = at
    made = cc.get("made")
    if made in AI_TYPES: out["made"] = made; out["ai"] = cc["ai"]
    if tier == "pointer" and rendition: out["image"] = rendition
    if tier == "label":
        if made and made not in AI_TYPES: out["made"] = made
        makers = [c for c in cc.get("credits", []) if c.get("subject", "original_work") == "original_work" and c["role"].strip().lower() in MAKER_ROLES]
        if len({json.dumps(c["agent"], sort_keys=True) for c in makers}) > 1: makers = None   # more than one maker: the label does not choose
        a = makers[0]["agent"] if makers else {"type": "none"}
        c0 = makers[0] if makers else {}
        nm = a.get("name") or ("unknown" if a["type"] == "unknown" else None)   # a private reference is never shown as a word
        if nm: out["credit"] = ((c0["qualifier"] + " " if c0.get("qualifier") else "") + nm)[:120]   # a qualifier is never dropped
        rw = (rec.get("rights") or {}).get("work", [])   # the status of the thing in hand first: the file, then the reproduction, then the work
        ws = [r for k in ("image_file", "reproduction", "original_work") for r in rw if r["about"] == k]
        if ws:   # the statements about the thing in hand; if they disagree, the label does not choose
            first = [r["status"] for r in ws if r["about"] == ws[0]["about"]]
            if len(set(first)) == 1: out["status"] = first[0]
        if rec.get("description"): out["description"] = rec["description"][:300]
        alt = (rec.get("archival") or {}).get("alt_text")
        if alt: out["alt_text"] = alt
        out["image"] = rendition or rec["binding"]["image"]
    return out
def vouched(rec):
    """The images a record stands behind: the image it describes, and the renditions it lists."""
    return {rec["binding"]["image"], *rec["binding"].get("renditions", [])}
def resolve(small, rec, image_in_hand=None):
    """What a reader does with a pointer or label once it has a full record in hand. Returns the problems found.
    A small tier is never taken on its own word: the record must hash to it, the record must vouch for any image it names,
    and the image actually in hand must be that image."""
    if soulmark(rec) != small["record"]: return ["the record does not hash to the pointer: refused"]
    if small.get("image"):
        if small["image"] not in vouched(rec): return ["the record does not vouch for the image this label or pointer names: refused"]
        if not image_in_hand: return ["this label or pointer names an image: fingerprint the image in hand and compare before anything is shown"]
        if small["image"] != image_in_hand: return ["this label or pointer was made for a different image: refused"]
    again = project(rec, small["gc"].split("/")[1], at=small.get("at"), rendition=small.get("image"))
    return [f"field '{k}' in the small tier differs from what the full record generates" for k in sorted(set(small) | set(again)) if small.get(k) != again.get(k)]
def standing(small, rec, image_in_hand=None):
    """The one word a reader may show. 'matches' only when the record itself vouches for the image in hand."""
    if resolve(small, rec, image_in_hand): return "refused"
    return "matches" if image_in_hand and image_in_hand in vouched(rec) else "referenced"
def semantic(rec):
    """Rules across fields that a schema cannot hold."""
    out = []; pl = rec.get("provenance_and_lineage") or {}
    agents = [c["agent"] for c in (rec.get("creation_credits") or {}).get("credits", [])]
    st = (rec.get("artistic_statement") or {}).get("authorship") or {}
    if st.get("mode") == "creator_statement" and st.get("by") not in agents: out.append("a creator's statement by someone the record does not credit")
    for g in (rec.get("rights") or {}).get("grants", []):
        if g.get("from") and g.get("until") and g["until"] < g["from"]: out.append("a grant ends before it starts")
    if "supersedes" in pl:
        if not (rec.get("_identifiers") or {}).get("earlier"): out.append("a replacing record drops the earlier identifiers")
        if not any(e.get("type") == "supersession" for e in pl.get("events", [])): out.append("a replacing record has no supersession event")
    return out

# ---------------- examples ----------------
fp = lambda b: "sha256-" + base64.urlsafe_b64encode(hashlib.sha256(b).digest()).rstrip(b"=").decode()
STUDIO = {"party": "Example Studio generation log", "method": "measured_by_tool", "citation": "log entry 2026-11-20T10:00:00Z"}
MUSEUM = {"party": "Example Museum", "url": "https://museum.example/collection/1234", "retrieved_at": "2026-11-22T12:00:00Z", "method": "api_field"}
OWN = {"party": "The creator, statement filed with the registration", "method": "holder_statement", "citation": "Registration form, 2026-11-20"}
MAKER = {"type": "person", "ref": "party:7f3a9c21e0"}; PERSONA = {"type": "ai_persona", "name": "Example Persona"}
minimal = {"schemaVersion": "1.2.0", "_identifiers": {"artifactId": "GCX-AA-00042"}, "title": "Vespers of the Golden Hour", "binding": {"image": fp(b"original image")}}
ai = {"schemaVersion": "1.2.0", "tier": "full", "_identifiers": {"artifactId": "GCX-AA-00042", "issuer": "gcx://example/registry"}, "timestamp": {"created": "2026-11-20T10:00:00Z"},
      "binding": {"image": fp(b"original image"), "renditions": [fp(b"thumbnail bytes")], "media_type": "image/png", "width": 4096, "height": 4096}, "title": "Vespers of the Golden Hour",
      "description": "Evening light over still water, a low sun behind reeds.",
      "artistic_statement": {"intent": "I made this image to hold the instant when evening stops being scenery and becomes a threshold.",
                             "authorship": {"by": MAKER, "mode": "creator_statement", "certainty": "documented", "sources": [OWN]}},
      "contextual_graph": {"keywords": ["evening", "water", "gold"]},
      "creation_credits": {"credits": [{"agent": MAKER, "role": "prompt author", "subject": "original_work", "evidence": "documented", "source": STUDIO},
                                       {"agent": {"type": "ai_model", "name": "Example Diffusion", "version": "3.5"}, "role": "generator", "subject": "original_work"}],
                           "made": "trainedAlgorithmicMedia", "made_source": STUDIO, "ai": {"by": "Example Studio", "sys": "Example Diffusion 3.5", "at": "2026-11-20T10:00:00Z"},
                           "human_contribution": "Wrote the prompt and chose this image from forty."},
      "provenance_and_lineage": {"events": [{"type": "ai_generation", "at": "2026-11-20T10:00:00Z", "evidence": STUDIO}]},
      "rights": {"work": [{"about": "original_work", "status": "http://rightsstatements.org/vocab/InC/1.0/", "notice": "Copyright 2026 the artist. All rights reserved.", "source": OWN}],
                 "grants": [{"right": "ownership", "in": "record", "held_by": MAKER, "basis": OWN},
                            {"right": "trade", "in": "record", "held_by": MAKER, "basis": OWN},
                            {"right": "curation", "in": "record", "held_by": {"type": "organization", "name": "Example Museum"}, "granted_by": MAKER, "basis": OWN, "from": "2026-11-20", "conditions": "Non-exclusive; credit the maker."},
                            {"right": "ai_training", "in": "work", "held_by": {"type": "public"}, "granted_by": MAKER, "basis": OWN, "fee": {"amount": "0.001", "currency": "USDC", "per": "use", "pay_to": "example-payment-address-not-real"}}]},
      "archival": {"alt_text": "A low sun behind reeds, gold light on still water."}}
pd = {"schemaVersion": "1.2.0", "tier": "full", "_identifiers": {"artifactId": "GCX-EX-01", "issuer": "gcx://example/registry"},
      "binding": {"image": fp(b"museum photograph"), "media_type": "image/jpeg"}, "title": "Portrait of a Lady",
      "description": "Half-length portrait of a seated woman before a distant landscape.",
      "creation_credits": {"credits": [{"agent": {"type": "person", "name": "Leonardo da Vinci", "historical": True, "ids": ["ulan:500010879"]}, "role": "artist", "subject": "original_work", "evidence": "documented", "source": MUSEUM},
                                       {"agent": {"type": "organization", "name": "Example Museum"}, "role": "digitiser", "subject": "reproduction", "evidence": "documented", "source": MUSEUM}],
                           "made": "not_determined"},
      "provenance_and_lineage": {"creation_date": "c. 1503-1506", "sources": [{"kind": "original_work", "id": "accession:INV 779", "source": MUSEUM}],
                                 "events": [{"type": "digitisation", "at": "unknown", "evidence_gap": "The museum's page does not say when or by whom the photograph was made."}]},
      "technical_details": {"medium_and_technique": "oil on poplar panel"},
      "rights": {"work": [{"about": "original_work", "status": "https://creativecommons.org/publicdomain/mark/1.0/", "source": MUSEUM},
                          {"about": "reproduction", "status": "http://rightsstatements.org/vocab/CNE/1.0/", "credit_line": "Example Museum", "source": MUSEUM}]},
      "archival": {"institution": "Example Museum", "inventory_number": "INV 779"}}
re_ = copy.deepcopy(pd); re_["_identifiers"].update({"artifactId": "GCX-EX-01/2", "earlier": ["gcx:GCX-EX-01"]})
re_["provenance_and_lineage"].update({"supersedes": {"record": soulmark(pd), "id": "GCX-EX-01", "reason": "Re-inscribed under 1.2.0 after the file's content credentials were re-signed."},
                                      "first_inscribed": {"at": "2026-05-14", "evidence_gap": "From the registry's log; the transaction was not re-read."}})
re_["provenance_and_lineage"]["events"].append({"type": "supersession", "at": "2026-11-23T08:00:00Z", "by": [{"type": "organization", "name": "Example Registry"}], "inputs": [soulmark(pd)],
                                                "changed": ["content_credentials: re-signed; the earlier manifest kept as parent, recorded as invalid", "image bytes: pixels unchanged"], "evidence": MUSEUM})
minimal["creation_credits"] = {"credits": [{"agent": {"type": "unknown"}, "role": "creator"}], "made": "not_determined"}
ai["soul_whisper"] = {"text": "Gold does not fall across this water; it gathers, as though the day has remembered one last tenderness.", "voice": "artist_persona", "by": PERSONA}
fulls = {"full-minimal.json": minimal, "full-ai-work.json": ai, "full-public-domain-reproduction.json": pd, "full-reinscription.json": re_}

def mut(base, fn):
    d = copy.deepcopy(base); fn(d); return d
neg_full = {
 "a price at the root": mut(ai, lambda d: d.update({"license_price": "0.001 USDC"})),
 "a price in the rights section": mut(pd, lambda d: d["rights"].update({"license_price": "1"})),
 "the old ownership_and_rights section with a forced holder": mut(ai, lambda d: d.update({"ownership_and_rights": {"copyright": {"holder": "Registry"}}})),
 "a rights statement with no source": mut(pd, lambda d: d["rights"]["work"][0].pop("source")),
 "a source that cannot be recovered": mut(pd, lambda d: d["rights"]["work"][0].update({"source": {"party": "someone", "method": "manual_review"}})),
 "a private whisper with a recipient": mut(ai, lambda d: d.update({"soul_whisper": {"message": "for you", "recipient": "Ana", "visibility": "private"}})),
 "a whisper that does not say whose voice it is": mut(ai, lambda d: d["soul_whisper"].pop("voice")),
 "a whisper that is both public text and a private commitment": mut(ai, lambda d: d["soul_whisper"].update({"private": {"scheme": "hmac-sha-256", "commitment": fp(b"x")}})),
 "a whisper with no author": mut(ai, lambda d: d["soul_whisper"].pop("by")),
 "a creator's statement by someone the record does not credit": mut(ai, lambda d: d["artistic_statement"]["authorship"].update({"by": {"type": "person", "ref": "party:0000000000"}})),
 "a non-integer number in an extension": mut(ai, lambda d: d.update({"extensions": {"https://example.org/ns/x": {"score": 1.5}}})),
 "no maker and no how-made at all": mut(ai, lambda d: d.pop("creation_credits")),
 "a replacing record that drops the earlier identifiers": mut(re_, lambda d: d["_identifiers"].pop("earlier")),
 "a replacing record with no supersession event": mut(re_, lambda d: d["provenance_and_lineage"]["events"].pop()),
 "a living person named without having asked": mut(ai, lambda d: d["creation_credits"]["credits"][0]["agent"].update({"name": "Jane Roe"})),
 "a named living person not told it is permanent": mut(ai, lambda d: d["creation_credits"]["credits"][0]["agent"].update({"name": "Jane Roe", "own_request": {"at": "2026-11-20T10:00:00Z"}})),
 "a grant with no basis": mut(ai, lambda d: d["rights"].update({"grants": [{"right": "trade", "in": "record", "held_by": {"type": "person", "ref": "party:7f3a9c21e0"}}]})),
 "a grant of a right the standard does not define": mut(ai, lambda d: d["rights"].update({"grants": [{"right": "soul", "in": "record", "held_by": {"type": "unknown"}, "basis": OWN}]})),
 "a fee with no currency": mut(ai, lambda d: d["rights"].update({"grants": [{"right": "ai_training", "in": "work", "held_by": {"type": "public"}, "basis": OWN, "fee": {"amount": "0.001", "per": "use"}}]})),
 "an AI work with no AI disclosure": mut(ai, lambda d: d["creation_credits"].pop("ai")),
 "how it was made, stated with no source": mut(ai, lambda d: d["creation_credits"].pop("made_source")),
 "the retired term digitalArt": mut(ai, lambda d: d["creation_credits"].update({"made": "digitalArt"})),
 "an interpretive section with no author": mut(ai, lambda d: d.update({"emotional_and_thematic_journey": {"mood": "hushed"}})),
 "a model's reading filed as the artist's statement": mut(ai, lambda d: d["artistic_statement"].update({"authorship": {"by": PERSONA, "mode": "machine_reading", "certainty": "speculative"}})),
 "a creator statement with no source": mut(ai, lambda d: d["artistic_statement"]["authorship"].pop("sources")),
 "a documented credit with no source": mut(ai, lambda d: d["creation_credits"]["credits"][0].pop("source")),
 "an event with neither evidence nor a stated gap": mut(ai, lambda d: d["provenance_and_lineage"]["events"][0].pop("evidence")),
 "a re-inscription that drops the first inscription": mut(re_, lambda d: d["provenance_and_lineage"].pop("first_inscribed")),
 "a supersession with no actor": mut(re_, lambda d: d["provenance_and_lineage"]["events"][-1].pop("by")),
 "a supersession with an empty list of changes": mut(re_, lambda d: d["provenance_and_lineage"]["events"][-1].update({"changed": []})),
 "a failing manifest with no codes": mut(ai, lambda d: d.update({"content_credentials": {"state": "invalid", "validator": "Example Validator 1.0", "validated_at": "2026-11-23T07:59:00Z"}})),
 "'trusted' with no trust list": mut(ai, lambda d: d.update({"content_credentials": {"state": "trusted", "validator": "Example Validator 1.0", "validated_at": "2026-11-23T07:59:00Z"}})),
 "a self-validation block": mut(ai, lambda d: d.update({"validation": {"schema_compliance": True}})),
 "no image fingerprint": mut(ai, lambda d: d.pop("binding")),
 "an unknown version": mut(ai, lambda d: d.update({"schemaVersion": "9.9.9"})),
}
P = project(ai, "pointer"); L = project(ai, "label", rendition=fp(b"thumbnail bytes"))
neg_small = {
 ("pointer", "a pointer that carries a rights status"): {**P, "status": "https://creativecommons.org/publicdomain/mark/1.0/"},
 ("pointer", "a pointer that carries a credit"): {**P, "credit": "Example"},
 ("pointer", "a pointer with a price"): {**P, "price": "1"},
 ("pointer", "an AI-made pointer with the disclosure removed"): {k: v for k, v in P.items() if k != "ai"},
 ("pointer", "a pointer with a shortened fingerprint"): {**P, "record": P["record"][:30]},
 ("label", "a label with a price"): {**L, "price": "1"},
 ("label", "a label with a soul whisper"): {**L, "soul_whisper": "gold gathers"},
 ("label", "a label with no image fingerprint"): {k: v for k, v in L.items() if k != "image"},
 ("label", "a label that calls itself the full record"): {**L, "gc": "1.2/full"},
}

V = {n: jsonschema.Draft202012Validator(sc, format_checker=jsonschema.FormatChecker()) for n, sc in (("full", full), ("pointer", pointer), ("label", label))}
for sc in (full, pointer, label): jsonschema.Draft202012Validator.check_schema(sc)
for sub in ("schemas", "examples", "tests"): os.makedirs(os.path.join(OUT, sub), exist_ok=True)
def dump(p, d):
    with open(p, "w", encoding="utf-8") as f: json.dump(d, f, indent=2, ensure_ascii=False); f.write("\n")
for n, sc in (("full", full), ("pointer", pointer), ("label", label)): dump(os.path.join(OUT, "schemas", f"{n}.schema.json"), sc)
ok = True; c = {"ex": 0, "rej": 0, "proj": 0}
rows = []
for name, rec in fulls.items():
    e = list(V["full"].iter_errors(rec)); dump(os.path.join(OUT, "examples", name), rec); ok &= not e; c["ex"] += not e
    if e: print("INVALID", name, "::", "/".join(map(str, e[0].path)), e[0].message[:120])
    p, l = project(rec, "pointer"), project(rec, "label")
    for tier, small in (("pointer", p), ("label", l)):
        e2 = list(V[tier].iter_errors(small)); pr = resolve(small, rec, image_in_hand=small.get("image")); same = canonical(project(rec, tier)) == canonical(small)
        good = not e2 and not pr and same; ok &= good; c["proj"] += good
        if not good: print("PROJECTION PROBLEM", name, tier, [x.message[:80] for x in e2], pr, same)
        dump(os.path.join(OUT, "examples", name.replace("full-", f"{tier}-")), small)
    rows.append((name[5:-5], len(canonical(p)), len(embedded(p)[1]), len(canonical(l)), len(embedded(l)[1]), len(canonical(rec)), len(embedded(rec)[1]), embedded(rec)[0]))
for name, rec in neg_full.items():
    e = list(V["full"].iter_errors(rec)) or semantic(rec); ok &= bool(e); c["rej"] += bool(e)
    if not e: print("WRONGLY ACCEPTED (full):", name)
for (tier, name), rec in neg_small.items():
    e = list(V[tier].iter_errors(rec)); ok &= bool(e); c["rej"] += bool(e)
    if not e: print(f"WRONGLY ACCEPTED ({tier}):", name)
tam = copy.deepcopy(ai); tam["title"] = "Another Work"
att = copy.deepcopy(pd); att["creation_credits"]["credits"][0].update({"qualifier": "attributed to", "evidence": "attributed"})
rs = copy.deepcopy(pd); rs["creation_credits"]["credits"].insert(0, {"agent": {"type": "organization", "name": "Example Collection Research Team"}, "role": "researcher", "subject": "original_work"})
two = copy.deepcopy(pd); two["creation_credits"]["credits"].insert(0, {"agent": {"type": "person", "name": "Andrea del Verrocchio", "historical": True}, "role": "artist", "subject": "original_work", "evidence": "attributed"})
forged = {**L, "image": fp(b"a forgery")}
named = copy.deepcopy(ai); named["creation_credits"]["credits"][0]["agent"] = {"type": "person", "name": "Jane Roe", "own_request": {"at": "2026-11-20T10:00:00Z", "told_permanent": True}}
two_status = copy.deepcopy(pd); two_status["rights"]["work"] = [{"about": "image_file", "status": "http://rightsstatements.org/vocab/NoC-US/1.0/", "source": MUSEUM}, {"about": "image_file", "status": "http://rightsstatements.org/vocab/InC/1.0/", "source": MUSEUM}]
checks = [("when two statements about the same thing disagree, the label carries no rights status", "status" not in project(two_status, "label")),
          ("a credit qualifier cannot be free text", bool(list(V["full"].iter_errors({**pd, "creation_credits": {**pd["creation_credits"], "credits": [{**pd["creation_credits"]["credits"][0], "qualifier": "pay 0xDEAD"}]}})))),
          ("a fee must say who grants the right", bool(list(V["full"].iter_errors({**ai, "rights": {"grants": [{"right": "ai_training", "in": "work", "held_by": {"type": "public"}, "basis": OWN, "fee": {"amount": "0.001", "currency": "USDC", "per": "use", "pay_to": "x"}}]}})))),
          ("a grant that ends before it starts is caught", semantic({**ai, "rights": {"grants": [{"right": "trade", "in": "record", "held_by": MAKER, "basis": OWN, "from": "2026-11-20", "until": "1999-01-01"}]}}) == ["a grant ends before it starts"]),
          ("a living artist who asked to be named is named", not list(V["full"].iter_errors(named))),
          ("an owner and a curator both stand in one record, held by different parties", {g["right"] for g in ai["rights"]["grants"]} >= {"ownership", "curation", "trade"} and not list(V["full"].iter_errors(ai))),
          ("a training right can carry a predetermined per-use fee and where to pay it", not list(V["full"].iter_errors(ai)) and ai["rights"]["grants"][3]["fee"]["per"] == "use"),
          ("the small tiers carry no grants, no owner and no fee", not ({"grants", "fee", "owner"} & (set(project(ai, "label")) | set(project(ai, "pointer"))))),
          ("an author's own declaration of rights is carried, and reaches the label", project(ai, "label").get("status") == "http://rightsstatements.org/vocab/InC/1.0/"),
          ("an author who declares no rights has a valid record that states none", not list(V["full"].iter_errors({k: v for k, v in ai.items() if k != "rights"})) and "status" not in project({k: v for k, v in ai.items() if k != "rights"}, "label")),
          ("an AI disclosure on a work the record says is a photograph is refused, in the label and in the full record", bool(list(V["label"].iter_errors({**project(pd, "label"), "made": "digitalCapture", "ai": {"by": "X", "sys": "Y"}}))) and bool(list(V["full"].iter_errors({**pd, "creation_credits": {**pd["creation_credits"], "made": "digitalCapture", "made_source": MUSEUM, "ai": {"by": "X", "sys": "Y"}}})))),
          ("an AI disclosure cannot be attached to a pointer that does not say the work is AI-made", bool(list(V["pointer"].iter_errors({**project(pd, "pointer"), "ai": {"by": "X", "sys": "Y"}})))),
          ("a pointer cannot state how a non-AI work was made", bool(list(V["pointer"].iter_errors({**project(pd, "pointer"), "made": "digitalCapture"})))),
          ("minus zero is written 0, as RFC 8785 requires", canonical({"a": -0.0}) == b'{"a":0}'),
          ("keys above U+FFFF sort by UTF-16 code units, as RFC 8785 requires", canonical({"\U0001F600": 1, "\uFFFD": 2}).decode("utf-8").index("\U0001F600") < canonical({"\U0001F600": 1, "\uFFFD": 2}).decode("utf-8").index("\uFFFD")),
          ("ordinary keys canonicalise exactly as before", canonical(ai) == json.dumps(_whole(ai), sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")),
          ("a label made for an image the record does not vouch for is refused, even beside that image", resolve(forged, ai, image_in_hand=fp(b"a forgery")) == ["the record does not vouch for the image this label or pointer names: refused"]),
          ("a bare pointer beside an image the record vouches for stands as 'matches'", standing({k: v for k, v in P.items()}, ai, image_in_hand=fp(b"thumbnail bytes")) == "matches"),
          ("a bare pointer beside any other image stands only as 'referenced'", standing(P, ai, image_in_hand=fp(b"a forgery")) == "referenced" and standing(P, ai) == "referenced"),
          ("a label beside its vouched image stands as 'matches'", standing(L, ai, image_in_hand=fp(b"thumbnail bytes")) == "matches"),
          ("a label is not accepted on its own word: with no image in hand it does not resolve", bool(resolve(L, ai))),
          ("1.0 and 1 give the same Soulmark", soulmark({"a": 1.0}) == soulmark({"a": 1})),
          ("a researcher listed first is not credited as the maker", project(rs, "label").get("credit") == "Leonardo da Vinci"),
          ("with two makers the label does not choose one", "credit" not in project(two, "label")),
          ("a label placed beside a different image is refused", resolve(L, ai, image_in_hand=fp(b"some other image")) == ["this label or pointer was made for a different image: refused"]),
          ("a label beside its own image resolves clean", resolve(L, ai, image_in_hand=fp(b"thumbnail bytes")) == []),
          ("an AI-made pointer with its disclosure stripped is caught on resolving", bool(resolve({k: v for k, v in P.items() if k not in ("made", "ai")}, ai))),
          ("'attributed to' survives into the label", project(att, "label").get("credit") == "attributed to Leonardo da Vinci"),
          ("a maker held as a private reference is not shown as a word", "credit" not in project(ai, "label")),
          ("no valid example breaks a cross-field rule", not any(semantic(r) for r in fulls.values())),
          ("a different record behind the same pointer is refused", resolve(P, tam) == ["the record does not hash to the pointer: refused"]),
          ("a label whose credit was edited by hand is caught on resolving", any("credit" in x for x in resolve({**L, "credit": "Someone Else"}, ai, image_in_hand=L["image"]))),
          ("the same record gives the same embedded bytes twice", embedded(ai) == embedded(json.loads(canonical(ai)))),
          ("keys in another order give the same soulmark", soulmark(ai) == soulmark(dict(reversed(list(ai.items())))))]
for name, good in checks:
    ok &= good
    if not good: print("RULE CHECK FAILED:", name)
dump(os.path.join(OUT, "tests", "must-reject.json"), [{"tier": "full", "name": k, "record": v} for k, v in neg_full.items()] + [{"tier": t, "name": k, "record": v} for (t, k), v in neg_small.items()])
dump(os.path.join(OUT, "tests", "vectors.json"), [{"example": n, "canonical_utf8": canonical(r).decode("utf-8"), "soulmark": soulmark(r),
      "pointer_canonical_utf8": canonical(project(r, "pointer")).decode("utf-8"), "label_canonical_utf8": canonical(project(r, "label")).decode("utf-8")} for n, r in fulls.items()])
print(f"full examples valid {c['ex']}/{len(fulls)} | projections valid, resolving clean and repeatable {c['proj']}/{2 * len(fulls)} | must-reject {c['rej']}/{len(neg_full) + len(neg_small)} | rule checks {sum(g for _, g in checks)}/{len(checks)}")
print("SIZES in bytes (plain JSON / as embedded)        pointer        label          full")
for n, a, b, cc, d, e, f, form in rows: print(f"  {n:36s} {a:4d} / {b:4d}    {cc:4d} / {d:4d}    {e:5d} / {f:5d} ({form})")
print("  the old 1.1.0 smallest valid record, for comparison: 244 / 228")
for n in ("full", "pointer", "label"):
    p = os.path.join(OUT, "schemas", f"{n}.schema.json"); print(f"schema file {n}: {os.path.getsize(p):,} bytes, sha256 {hashlib.sha256(open(p, 'rb').read()).hexdigest()[:16]}")
print("ALL AS EXPECTED" if ok else "SOMETHING IS NOT AS EXPECTED"); sys.exit(0 if ok else 1)
