# tfl-shell-to-ars-metadata_validate.py  (workflow: tfl-shell-to-ars-metadata)
# Needs: Python 3 and the jsonschema package (pip install jsonschema).
# Tested with Python 3.14.3. Run with: python -I tfl-shell-to-ars-metadata_validate.py ...  (see the usage in the docstring below).
# Data and documents it reads are public and are NOT included: CDISC pilot files from https://github.com/cdisc-org/sdtm-adam-pilot-project,
# credited to CDISC. Code licence: MIT (see README.md in the scripts folder).
# Only this header was added; the logic is unchanged.
"""Validate AI-drafted ARS JSON against the real CDISC ARS JSON schema.

Usage:  python -I tfl-shell-to-ars-metadata_validate.py SCHEMA.json OUTPUT_TEXT [OUTPUT_TEXT ...]
SCHEMA.json = model/ars_ldm.json from https://github.com/cdisc-org/analysis-results-standard
              (commit bbebea4f5de870eaf09456ee147233c6f26d0e48, 2026-04-28; $id https://www.cdisc.org/ars/1-0;
              JSON Schema draft-07; MIT licence). The schema is NOT copied into this project: clone the repo.
OUTPUT_TEXT = the model's saved reply; the first ```json block (or first top-level JSON object) is parsed.
Needs: pip install jsonschema (tested with 4.x).
Passing the schema means the JSON is well formed ARS. It does not mean the content is right.
"""
import json, re, sys
from jsonschema import Draft7Validator

def extract(text):
    m = re.search(r"```json\s*(.*?)```", text, re.S)
    if m:
        return json.loads(m.group(1))
    dec = json.JSONDecoder()
    i = text.index("{")
    obj, _ = dec.raw_decode(text[i:])
    return obj

def collect_ids(node, bag):
    """Collect every 'id' value by walking the document, keyed by the parent list name."""
    if isinstance(node, dict):
        for k, v in node.items():
            if isinstance(v, list):
                for it in v:
                    if isinstance(it, dict) and "id" in it:
                        bag.setdefault(k, set()).add(it["id"])
            collect_ids(v, bag)
    elif isinstance(node, list):
        for it in node:
            collect_ids(it, bag)

REFS = {  # reference property -> list name that must hold the id (ARS v1.0 property names)
    "analysisSetId": "analysisSets", "dataSubsetId": "dataSubsets", "methodId": "methods",
    "groupingId": "analysisGroupings", "outputId": "outputs", "analysisId": "analyses",
}

def check_refs(doc):
    """Dangling-reference check. Our addition: the JSON schema does not test that ids resolve."""
    bag = {}
    collect_ids(doc, bag)
    bad = []
    def walk(n, path):
        if isinstance(n, dict):
            for k, v in n.items():
                if k in REFS and isinstance(v, str) and v not in bag.get(REFS[k], set()):
                    bad.append("%s/%s = %r not found in %s" % (path, k, v, REFS[k]))
                if k == "categoryIds" and isinstance(v, list):
                    allc = set()
                    for c in doc.get("analysisOutputCategorizations", []):
                        for cat in c.get("categories", []):
                            allc.add(cat.get("id"))
                    for x in v:
                        if x not in allc:
                            bad.append("%s/categoryIds %r not found in analysisOutputCategorizations" % (path, x))
                walk(v, path + "/" + k)
        elif isinstance(n, list):
            for i, it in enumerate(n):
                walk(it, "%s[%d]" % (path, i))
    walk(doc, "")
    return bad

def main(schema_path, paths):
    schema = json.load(open(schema_path, encoding="utf-8"))
    Draft7Validator.check_schema(schema)
    v = Draft7Validator(schema)
    # The published schema has additionalProperties: true at the ROOT only, so a misspelled top-level
    # key (for example analysisMethods instead of methods) is not an error. Second pass: same schema,
    # root additionalProperties forced to false. Our addition, not part of the CDISC schema.
    strict = dict(schema); strict["additionalProperties"] = False
    vs = Draft7Validator(strict)
    for p in paths:
        try:
            doc = extract(open(p, encoding="utf-8").read())
        except Exception as e:
            print(p, "-> could not parse JSON:", e); continue
        errs = sorted(v.iter_errors(doc), key=lambda e: list(map(str, e.absolute_path)))
        print("=" * 70)
        print(p, "->", "PASS" if not errs else "FAIL", "| schema errors (leaf, as reported by jsonschema):", len(errs))
        for e in errs:
            path = "/".join(map(str, e.absolute_path)) or "(root)"
            print("  -", path, "::", e.message[:200])
        unk = [k for k in doc if k not in schema["properties"]]
        serrs = list(vs.iter_errors(doc))
        print("  strict pass (root additionalProperties=false):", "PASS" if not serrs else "FAIL", "| errors:", len(serrs), "| unknown root keys:", unk)
        dang = check_refs(doc)
        print("  reference check (ids resolve):", "PASS" if not dang else "FAIL", "| dangling:", len(dang))
        for d in dang:
            print("    -", d)

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