#!/usr/bin/env python3
"""GEAIRM 0.1 automated conformance-support runner (A12).

This runner executes the authoritative A10 positive and A11 negative testcase
manifests. It validates only machine-executable layers and deliberately preserves
hybrid/assessment-only semantic obligations as NOT_EXECUTED.

The runner is offline and deterministic. It requires jsonschema and rdflib.
For GEAIRM-A6 it executes the exact SHACL profile currently used by
``geairm-0.1.shacl.ttl``: NodeShapes with sh:targetNode / sh:targetClass and
sh:SPARQLConstraint sh:select constraints. If the A6 artifact evolves beyond
that profile, the runner fails closed rather than silently skipping constraints.

Exit codes:
  0  all executable expectations matched
  1  one or more testcase/preflight expectations mismatched
  2  runner/configuration/dependency error
"""
from __future__ import annotations

import argparse
import copy
import hashlib
import importlib.metadata
import json
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable

try:
    from jsonschema import Draft202012Validator, FormatChecker
except Exception as exc:  # pragma: no cover - dependency guard
    print(f"ERROR: jsonschema dependency unavailable: {exc}", file=sys.stderr)
    raise SystemExit(2)

try:
    from rdflib import BNode, Graph, Literal, Namespace, RDF, URIRef
    from rdflib.plugins.sparql import prepareQuery
except Exception as exc:  # pragma: no cover - dependency guard
    print(f"ERROR: rdflib dependency unavailable: {exc}", file=sys.stderr)
    raise SystemExit(2)

RUNNER_VERSION = "0.1.0"
CANONICAL_CONTEXT_PATH = "/spec/aips/geairm/0.1/geairm-0.1.context.jsonld"

SH = Namespace("http://www.w3.org/ns/shacl#")
GEAIRMSH = Namespace("https://aips.kivanura.org/spec/aips/geairm/0.1/shacl/")
GEAIRMI = Namespace("https://aips.kivanura.org/spec/aips/geairm/0.1/invariant/")


class RunnerError(RuntimeError):
    """Configuration or execution error that prevents trustworthy execution."""


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as fh:
        for chunk in iter(lambda: fh.read(1024 * 1024), b""):
            h.update(chunk)
    return h.hexdigest()


def load_json(path: Path) -> Any:
    with path.open("r", encoding="utf-8") as fh:
        return json.load(fh)


def dump_json_deterministic(value: Any) -> str:
    return json.dumps(value, indent=2, ensure_ascii=False, sort_keys=False) + "\n"


def relative_display(path: Path, root: Path) -> str:
    try:
        return path.resolve().relative_to(root.resolve()).as_posix()
    except Exception:
        return str(path)


def package_version(name: str) -> str:
    try:
        return importlib.metadata.version(name)
    except Exception:
        return "unknown"


def term_text(term: Any) -> str:
    if isinstance(term, URIRef):
        return str(term)
    if isinstance(term, BNode):
        return f"_:{term}"
    if isinstance(term, Literal):
        return str(term)
    return str(term)


def invariant_id_from_uri(uri: Any) -> str | None:
    s = str(uri)
    marker = "/invariant/"
    if marker in s:
        return s.rsplit(marker, 1)[1]
    return None


@dataclass(frozen=True)
class Paths:
    root: Path
    spec: Path
    testcases: Path
    positive_manifest: Path
    negative_manifest: Path
    schema_a7: Path
    schema_a8: Path
    context_a5: Path
    ontology_a4: Path
    shapes_a6: Path

    @staticmethod
    def from_root(root: Path) -> "Paths":
        spec = root / "static" / "spec" / "aips" / "geairm" / "0.1"
        testcases = spec / "testcases"
        return Paths(
            root=root,
            spec=spec,
            testcases=testcases,
            positive_manifest=testcases / "geairm-0.1.positive-testcases.json",
            negative_manifest=testcases / "geairm-0.1.negative-testcases.json",
            schema_a7=spec / "geairm-0.1.schema.json",
            schema_a8=spec / "geairm-0.1.profile.schema.json",
            context_a5=spec / "geairm-0.1.context.jsonld",
            ontology_a4=spec / "geairm-0.1.ttl",
            shapes_a6=spec / "geairm-0.1.shacl.ttl",
        )


class A6ShaclSparqlExecutor:
    """Fail-closed executor for the exact SHACL profile used by GEAIRM-A6.

    This is intentionally not advertised as a general SHACL implementation.
    A6 currently contains only sh:NodeShape resources, sh:targetNode / targetClass
    targets, and sh:SPARQLConstraint resources carrying sh:select queries.
    """

    def __init__(self, shapes_path: Path):
        self.shapes_path = shapes_path
        self.graph = Graph()
        self.graph.parse(shapes_path, format="turtle")
        self.shapes = sorted(set(self.graph.subjects(RDF.type, SH.NodeShape)), key=str)
        self._verify_supported_profile()
        self.constraint_count = sum(1 for shape in self.shapes for _ in self.graph.objects(shape, SH.sparql))
        self._prepared_constraints: list[tuple[Any, Any, Any, str, str | None]] = []
        for shape in self.shapes:
            invariant_values = list(self.graph.objects(shape, GEAIRMSH.implementsInvariant))
            invariant_id = invariant_id_from_uri(invariant_values[0]) if invariant_values else None
            for constraint in self.graph.objects(shape, SH.sparql):
                select_term = next(iter(self.graph.objects(constraint, SH.select)), None)
                if select_term is None:
                    raise RunnerError(f"A6 constraint on {shape} is missing sh:select")
                messages = [str(x) for x in self.graph.objects(constraint, SH.message)]
                message = messages[0] if messages else "SHACL SPARQL constraint violation"
                try:
                    prepared = prepareQuery(str(select_term))
                except Exception as exc:
                    raise RunnerError(f"Unable to prepare A6 SPARQL constraint for {term_text(shape)}: {exc}") from exc
                self._prepared_constraints.append((shape, constraint, prepared, message, invariant_id))

    def _verify_supported_profile(self) -> None:
        property_shapes = list(self.graph.subjects(RDF.type, SH.PropertyShape))
        if property_shapes:
            raise RunnerError(
                "A6 SHACL artifact now contains PropertyShapes; A12 built-in executor "
                "supports only the frozen A6 NodeShape/SPARQL profile."
            )

        allowed_shape_predicates = {
            RDF.type,
            SH.targetNode,
            SH.targetClass,
            SH.sparql,
            SH.severity,
            GEAIRMSH.implementsInvariant,
            GEAIRMSH.constraintKind,
            GEAIRMSH.validationScope,
            GEAIRMSH.requiresSemanticAssessment,
        }
        unsupported: list[str] = []
        for shape in self.shapes:
            for predicate in set(self.graph.predicates(shape, None)):
                if predicate not in allowed_shape_predicates:
                    unsupported.append(f"{term_text(shape)} uses unsupported shape predicate {term_text(predicate)}")
            if not list(self.graph.objects(shape, SH.sparql)):
                unsupported.append(f"{term_text(shape)} has no sh:sparql constraint")
            for constraint in self.graph.objects(shape, SH.sparql):
                if (constraint, RDF.type, SH.SPARQLConstraint) not in self.graph:
                    unsupported.append(f"{term_text(shape)} sh:sparql node is not sh:SPARQLConstraint")
                selects = list(self.graph.objects(constraint, SH.select))
                if len(selects) != 1:
                    unsupported.append(f"{term_text(shape)} SPARQL constraint must have exactly one sh:select")
                for pred in set(self.graph.predicates(constraint, None)):
                    if pred not in {RDF.type, SH.message, SH.select, SH.prefixes, SH.deactivated, SH.severity}:
                        unsupported.append(
                            f"{term_text(shape)} constraint uses unsupported predicate {term_text(pred)}"
                        )
        if unsupported:
            raise RunnerError("Unsupported A6 SHACL profile detected: " + "; ".join(unsupported[:12]))

    def _focus_nodes(self, shape: Any, data: Graph) -> list[Any]:
        nodes: set[Any] = set(self.graph.objects(shape, SH.targetNode))
        for cls in self.graph.objects(shape, SH.targetClass):
            nodes.update(data.subjects(RDF.type, cls))
        return sorted(nodes, key=term_text)

    def validate(self, data: Graph) -> list[dict[str, Any]]:
        violations: list[dict[str, Any]] = []
        focus_cache: dict[Any, list[Any]] = {}
        for shape, _constraint, prepared, message, invariant_id in self._prepared_constraints:
            focus_nodes = focus_cache.setdefault(shape, self._focus_nodes(shape, data))
            for focus in focus_nodes:
                try:
                    rows = list(data.query(prepared, initBindings={"this": focus}))
                except Exception as exc:
                    raise RunnerError(
                        f"Failed executing A6 SPARQL constraint for {term_text(shape)}: {exc}"
                    ) from exc
                for row in rows:
                    violations.append(
                        {
                            "shape": term_text(shape),
                            "invariant": invariant_id,
                            "focusNode": term_text(focus),
                            "message": message,
                            "result": [term_text(v) for v in row],
                        }
                    )
        return violations


class ConformanceRunner:
    def __init__(self, paths: Paths, suite: str, verbose: bool):
        self.paths = paths
        self.suite = suite
        self.verbose = verbose
        self.preflight: list[dict[str, Any]] = []
        self.execution_errors: list[str] = []

        self._require_files()
        self.context_doc = load_json(paths.context_a5)
        self.schema_a7 = load_json(paths.schema_a7)
        self.schema_a8 = load_json(paths.schema_a8)
        Draft202012Validator.check_schema(self.schema_a7)
        Draft202012Validator.check_schema(self.schema_a8)
        self.validator_a7 = Draft202012Validator(self.schema_a7, format_checker=FormatChecker())
        self.validator_a8 = Draft202012Validator(self.schema_a8, format_checker=FormatChecker())

        self.ontology = Graph()
        self.ontology.parse(paths.ontology_a4, format="turtle")
        self.a6 = A6ShaclSparqlExecutor(paths.shapes_a6)

        self.positive_manifest = load_json(paths.positive_manifest)
        self.negative_manifest = load_json(paths.negative_manifest)
        self._preflight_manifests()

    def _log(self, line: str) -> None:
        if self.verbose:
            print(line)

    def _require_files(self) -> None:
        required = [
            self.paths.positive_manifest,
            self.paths.negative_manifest,
            self.paths.schema_a7,
            self.paths.schema_a8,
            self.paths.context_a5,
            self.paths.ontology_a4,
            self.paths.shapes_a6,
        ]
        missing = [str(p) for p in required if not p.is_file()]
        if missing:
            raise RunnerError("Required GEAIRM artifacts are missing: " + ", ".join(missing))

    def _preflight_manifests(self) -> None:
        positive = self.positive_manifest.get("testcases", [])
        negative = self.negative_manifest.get("testcases", [])
        checks = [
            ("A10 manifest testcase count", len(positive) == 17, f"observed={len(positive)} expected=17"),
            ("A11 manifest testcase count", len(negative) == 36, f"observed={len(negative)} expected=36"),
            (
                "global testcase IDs unique",
                len({tc.get('testcaseId') for tc in positive + negative}) == len(positive) + len(negative),
                f"observed_unique={len({tc.get('testcaseId') for tc in positive + negative})} total={len(positive)+len(negative)}",
            ),
            (
                "A5 canonical context has no default @vocab",
                isinstance(self.context_doc, dict)
                and isinstance(self.context_doc.get("@context"), dict)
                and "@vocab" not in self.context_doc["@context"],
                "default @vocab must remain absent",
            ),
            (
                "A6 frozen executable profile",
                len(self.a6.shapes) == 24 and self.a6.constraint_count == 34,
                f"nodeShapes={len(self.a6.shapes)} sparqlConstraints={self.a6.constraint_count}",
            ),
        ]
        for name, passed, detail in checks:
            self.preflight.append({"check": name, "passed": bool(passed), "detail": detail})
        if not all(x[1] for x in checks):
            raise RunnerError("A12 preflight failed; authoritative manifests/artifacts do not match the A11 baseline")

    def _fixture_path(self, input_file: str) -> Path:
        path = (self.paths.testcases / input_file).resolve()
        base = self.paths.testcases.resolve()
        if path != base and base not in path.parents:
            raise RunnerError(f"Testcase path escapes testcase root: {input_file}")
        return path

    def _checksum_result(self, tc: dict[str, Any], fixture: Path) -> dict[str, Any]:
        expected = tc.get("inputSha256")
        actual = sha256_file(fixture) if fixture.is_file() else None
        matched = bool(expected) and actual == expected
        return {
            "layer": "FIXTURE_SHA256",
            "expectedOutcome": "PASS",
            "actualOutcome": "PASS" if matched else "FAIL",
            "expectationMatched": matched,
            "detail": {"expectedSha256": expected, "actualSha256": actual},
        }

    @staticmethod
    def _schema_errors(validator: Draft202012Validator, instance: Any) -> list[dict[str, Any]]:
        errors = sorted(validator.iter_errors(instance), key=lambda e: (list(e.absolute_path), e.message))
        out = []
        for err in errors:
            out.append(
                {
                    "path": "/" + "/".join(str(x) for x in err.absolute_path),
                    "schemaPath": "/" + "/".join(str(x) for x in err.absolute_schema_path),
                    "message": err.message,
                }
            )
        return out

    def _json_syntax(self, fixture: Path, expected: str) -> tuple[dict[str, Any], Any | None]:
        try:
            instance = load_json(fixture)
            actual = "PASS"
            detail: Any = "valid JSON"
        except Exception as exc:
            instance = None
            actual = "FAIL"
            detail = str(exc)
        return (
            {
                "layer": "JSON_SYNTAX",
                "expectedOutcome": expected,
                "actualOutcome": actual,
                "expectationMatched": actual == expected,
                "detail": detail,
            },
            instance,
        )

    def _context_policy(self, instance: Any, expected: str) -> dict[str, Any]:
        actual_context = instance.get("@context") if isinstance(instance, dict) else None
        canonical_no_vocab = (
            isinstance(self.context_doc, dict)
            and isinstance(self.context_doc.get("@context"), dict)
            and "@vocab" not in self.context_doc["@context"]
        )
        ok = actual_context == CANONICAL_CONTEXT_PATH and canonical_no_vocab
        actual = "PASS" if ok else "FAIL"
        return {
            "layer": "A5_CONTEXT_NAMESPACE_POLICY",
            "expectedOutcome": expected,
            "actualOutcome": actual,
            "expectationMatched": actual == expected,
            "detail": {
                "fixtureContext": actual_context,
                "requiredContext": CANONICAL_CONTEXT_PATH,
                "canonicalContextHasDefaultVocab": not canonical_no_vocab,
            },
        }

    def _schema_layer(self, instance: Any, layer: str, expected: str) -> dict[str, Any]:
        if layer == "A7_STRUCTURAL_SCHEMA":
            validator = self.validator_a7
            artifact = relative_display(self.paths.schema_a7, self.paths.root)
        elif layer == "A8_STRUCTURAL_SCHEMA" or layer == "A8_PROFILE_EXTENSION_SCHEMA":
            validator = self.validator_a8
            artifact = relative_display(self.paths.schema_a8, self.paths.root)
        else:
            raise RunnerError(f"Unknown schema layer: {layer}")
        errors = self._schema_errors(validator, instance)
        actual = "PASS" if not errors else "FAIL"
        return {
            "layer": layer,
            "expectedOutcome": expected,
            "actualOutcome": actual,
            "expectationMatched": actual == expected,
            "detail": {
                "artifact": artifact,
                "errorCount": len(errors),
                "errors": errors[:10],
                "errorsTruncated": len(errors) > 10,
            },
        }

    def _localize_context(self, instance: Any) -> Any:
        doc = copy.deepcopy(instance)
        if isinstance(doc, dict) and "@context" in doc:
            doc["@context"] = self.context_doc["@context"]
        return doc

    def _graph_from_jsonld(self, instance: Any) -> Graph:
        doc = self._localize_context(instance)
        graph = Graph()
        graph.parse(data=json.dumps(doc, ensure_ascii=False), format="json-ld")
        return graph

    def _merged_with_ontology(self, extra: Graph) -> Graph:
        merged = Graph()
        for triple in self.ontology:
            merged.add(triple)
        for triple in extra:
            merged.add(triple)
        return merged

    def _a6_from_json(self, instance: Any, expected: str) -> dict[str, Any]:
        try:
            extra = self._graph_from_jsonld(instance)
            data = self._merged_with_ontology(extra)
            violations = self.a6.validate(data)
            actual = "PASS" if not violations else "FAIL"
            detail: Any = {
                "engine": "GEAIRM-A6 NodeShape/SPARQL subset executor over RDFLib",
                "fixtureTriples": len(extra),
                "dataTriplesWithA4Baseline": len(data),
                "violationCount": len(violations),
                "violations": violations[:20],
                "violationsTruncated": len(violations) > 20,
            }
        except Exception as exc:
            actual = "ERROR"
            detail = {"error": str(exc)}
        return {
            "layer": "A6_SHACL",
            "expectedOutcome": expected,
            "actualOutcome": actual,
            "expectationMatched": actual == expected,
            "detail": detail,
        }

    def _a6_from_turtle(self, fixture: Path, expected: str, expected_invariant: str | None) -> tuple[dict[str, Any], dict[str, Any]]:
        try:
            delta = Graph()
            delta.parse(fixture, format="turtle")
            parse_actual = "PASS"
            parse_detail: Any = {"tripleCount": len(delta)}
        except Exception as exc:
            delta = Graph()
            parse_actual = "FAIL"
            parse_detail = {"error": str(exc)}

        parse_result = {
            "layer": "RDF_TURTLE_PARSE",
            "expectedOutcome": "PASS",
            "actualOutcome": parse_actual,
            "expectationMatched": parse_actual == "PASS",
            "detail": parse_detail,
        }

        if parse_actual != "PASS":
            a6_result = {
                "layer": "A6_SHACL",
                "expectedOutcome": expected,
                "actualOutcome": "NOT_EXECUTED",
                "expectationMatched": False,
                "detail": {"reason": "Turtle parse failed"},
            }
            return parse_result, a6_result

        try:
            data = self._merged_with_ontology(delta)
            violations = self.a6.validate(data)
            actual = "PASS" if not violations else "FAIL"
            invariants = sorted({v.get("invariant") for v in violations if v.get("invariant")})
            expected_invariant_observed = expected_invariant in invariants if expected_invariant else True
            match = actual == expected and expected_invariant_observed
            detail = {
                "engine": "GEAIRM-A6 NodeShape/SPARQL subset executor over RDFLib",
                "fixtureTriples": len(delta),
                "dataTriplesWithA4Baseline": len(data),
                "violationCount": len(violations),
                "observedInvariants": invariants,
                "expectedInvariant": expected_invariant,
                "expectedInvariantObserved": expected_invariant_observed,
                "violations": violations[:20],
                "violationsTruncated": len(violations) > 20,
            }
        except Exception as exc:
            actual = "ERROR"
            match = False
            detail = {"error": str(exc), "expectedInvariant": expected_invariant}

        a6_result = {
            "layer": "A6_SHACL",
            "expectedOutcome": expected,
            "actualOutcome": actual,
            "expectationMatched": match,
            "detail": detail,
        }
        return parse_result, a6_result

    def _semantic_result(self, layer_def: dict[str, Any]) -> dict[str, Any]:
        expected = layer_def.get("expectedOutcome", "ASSESSMENT_REQUIRED")
        return {
            "layer": "SEMANTIC_ASSESSMENT",
            "expectedOutcome": expected,
            "actualOutcome": "NOT_EXECUTED",
            "expectationMatched": None,
            "executionStatus": "DEFERRED_TO_GOVERNED_ASSESSMENT",
            "claimBoundary": (
                "A12 deliberately does not machine-prove hybrid-assessment or assessment-only semantics. "
                "The declared semantic expectation is preserved for governed assessment."
            ),
        }

    def _execute_positive(self, tc: dict[str, Any]) -> dict[str, Any]:
        fixture = self._fixture_path(tc["inputFile"])
        layers: list[dict[str, Any]] = [self._checksum_result(tc, fixture)]
        instance: Any | None = None
        for layer_def in tc.get("applicableValidationLayers", []):
            layer = layer_def.get("layer")
            expected = layer_def.get("expectedOutcome")
            if layer == "JSON_SYNTAX":
                result, instance = self._json_syntax(fixture, expected)
                layers.append(result)
            elif layer == "A5_CONTEXT_NAMESPACE_POLICY":
                if instance is None:
                    try:
                        instance = load_json(fixture)
                    except Exception:
                        instance = None
                layers.append(self._context_policy(instance, expected))
            elif layer in {"A7_STRUCTURAL_SCHEMA", "A8_STRUCTURAL_SCHEMA", "A8_PROFILE_EXTENSION_SCHEMA"}:
                if instance is None:
                    try:
                        instance = load_json(fixture)
                    except Exception:
                        instance = None
                layers.append(self._schema_layer(instance, layer, expected))
            elif layer == "A6_SHACL":
                if expected == "NOT_APPLICABLE":
                    layers.append(
                        {
                            "layer": layer,
                            "expectedOutcome": expected,
                            "actualOutcome": "NOT_APPLICABLE",
                            "expectationMatched": True,
                            "detail": {"reason": layer_def.get("reason")},
                        }
                    )
                else:
                    if instance is None:
                        instance = load_json(fixture)
                    layers.append(self._a6_from_json(instance, expected))
            elif layer == "SEMANTIC_ASSESSMENT":
                layers.append(self._semantic_result(layer_def))
            else:
                layers.append(
                    {
                        "layer": str(layer),
                        "expectedOutcome": expected,
                        "actualOutcome": "ERROR",
                        "expectationMatched": False,
                        "detail": {"error": "Unsupported manifest layer"},
                    }
                )

        executable = [r for r in layers if r.get("expectationMatched") is not None]
        passed = all(bool(r.get("expectationMatched")) for r in executable)
        semantic = next((r for r in layers if r["layer"] == "SEMANTIC_ASSESSMENT"), None)
        machine_layers = [r for r in layers if r["layer"] not in {"SEMANTIC_ASSESSMENT", "FIXTURE_SHA256"}]
        machine_accept = all(r.get("actualOutcome") in {"PASS", "NOT_APPLICABLE"} for r in machine_layers)
        return {
            "testcaseId": tc.get("testcaseId"),
            "suite": "positive",
            "category": "POSITIVE",
            "title": tc.get("title"),
            "inputFile": tc.get("inputFile"),
            "expectationMatchStatus": "PASS" if passed else "FAIL",
            "machineBoundaryOutcome": "ACCEPT" if machine_accept else "REJECT_OR_ERROR",
            "semanticAssessmentStatus": semantic.get("actualOutcome") if semantic else "NOT_DECLARED",
            "completeSemanticConformanceEstablished": False,
            "layerResults": layers,
        }

    def _execute_negative(self, tc: dict[str, Any]) -> dict[str, Any]:
        fixture = self._fixture_path(tc["inputFile"])
        layers: list[dict[str, Any]] = [self._checksum_result(tc, fixture)]
        instance: Any | None = None
        expected_layers = tc.get("expectedLayers", [])
        category = tc.get("category")
        turtle_done = False

        for layer_def in expected_layers:
            layer = layer_def.get("layer")
            expected = layer_def.get("expectedOutcome")
            if layer == "JSON_SYNTAX":
                result, instance = self._json_syntax(fixture, expected)
                layers.append(result)
            elif layer in {"A7_STRUCTURAL_SCHEMA", "A8_STRUCTURAL_SCHEMA", "A8_PROFILE_EXTENSION_SCHEMA"}:
                if instance is None:
                    try:
                        instance = load_json(fixture)
                    except Exception:
                        instance = None
                layers.append(self._schema_layer(instance, layer, expected))
            elif layer == "RDF_TURTLE_PARSE":
                parse_result, a6_result = self._a6_from_turtle(
                    fixture,
                    next((x.get("expectedOutcome") for x in expected_layers if x.get("layer") == "A6_SHACL"), "FAIL"),
                    tc.get("applicableInvariant"),
                )
                layers.append(parse_result)
                self._cached_a6_turtle = a6_result
                turtle_done = True
            elif layer == "A6_SHACL":
                if category == "A6_EXECUTABLE_BOUNDARY":
                    if not turtle_done:
                        parse_result, a6_result = self._a6_from_turtle(
                            fixture, expected, tc.get("applicableInvariant")
                        )
                        layers.append(parse_result)
                    else:
                        a6_result = self._cached_a6_turtle
                    layers.append(a6_result)
                else:
                    if instance is None:
                        instance = load_json(fixture)
                    layers.append(self._a6_from_json(instance, expected))
            elif layer == "SEMANTIC_ASSESSMENT":
                layers.append(self._semantic_result(layer_def))
            else:
                layers.append(
                    {
                        "layer": str(layer),
                        "expectedOutcome": expected,
                        "actualOutcome": "ERROR",
                        "expectationMatched": False,
                        "detail": {"error": "Unsupported manifest layer"},
                    }
                )

        executable = [r for r in layers if r.get("expectationMatched") is not None]
        passed = all(bool(r.get("expectationMatched")) for r in executable)
        semantic = next((r for r in layers if r["layer"] == "SEMANTIC_ASSESSMENT"), None)
        machine_layers = [r for r in layers if r["layer"] not in {"SEMANTIC_ASSESSMENT", "FIXTURE_SHA256"}]
        machine_rejected = any(r.get("actualOutcome") == "FAIL" for r in machine_layers)
        if category == "CANONICAL_SEMANTIC_COUNTEREXAMPLE":
            boundary_outcome = "ACCEPT_AT_MACHINE_LAYERS_SEMANTIC_REJECTION_EXPECTED"
        else:
            boundary_outcome = "REJECT" if machine_rejected else "ACCEPT_OR_ERROR"
        return {
            "testcaseId": tc.get("testcaseId"),
            "suite": "negative",
            "category": category,
            "title": tc.get("title"),
            "inputFile": tc.get("inputFile"),
            "expectationMatchStatus": "PASS" if passed else "FAIL",
            "machineBoundaryOutcome": boundary_outcome,
            "semanticAssessmentStatus": semantic.get("actualOutcome") if semantic else "NOT_REQUIRED_OR_NOT_DECLARED",
            "completeSemanticConformanceEstablished": False,
            "layerResults": layers,
        }

    def run(self) -> dict[str, Any]:
        tests: list[dict[str, Any]] = []
        if self.suite in {"all", "positive"}:
            for tc in self.positive_manifest.get("testcases", []):
                result = self._execute_positive(tc)
                tests.append(result)
                self._log(f"{result['expectationMatchStatus']:<4} {result['testcaseId']} {result['machineBoundaryOutcome']}")
        if self.suite in {"all", "negative"}:
            for tc in self.negative_manifest.get("testcases", []):
                result = self._execute_negative(tc)
                tests.append(result)
                self._log(f"{result['expectationMatchStatus']:<4} {result['testcaseId']} {result['machineBoundaryOutcome']}")

        exec_layer_results = [
            layer
            for tc in tests
            for layer in tc["layerResults"]
            if layer.get("expectationMatched") is not None
        ]
        semantic_layers = [
            layer for tc in tests for layer in tc["layerResults"] if layer.get("layer") == "SEMANTIC_ASSESSMENT"
        ]
        testcase_passed = sum(1 for tc in tests if tc["expectationMatchStatus"] == "PASS")
        testcase_failed = len(tests) - testcase_passed
        layer_passed = sum(1 for r in exec_layer_results if r.get("expectationMatched") is True)
        layer_failed = len(exec_layer_results) - layer_passed
        status = "PASS" if testcase_failed == 0 and layer_failed == 0 and all(x["passed"] for x in self.preflight) else "FAIL"

        counts_by_category: dict[str, int] = {}
        for tc in tests:
            counts_by_category[tc["category"]] = counts_by_category.get(tc["category"], 0) + 1

        return {
            "artifact": "GEAIRM-A12 Automated Conformance Runner Report",
            "version": "0.1",
            "runnerVersion": RUNNER_VERSION,
            "status": status,
            "suiteSelection": self.suite,
            "semanticClaimBoundary": (
                "A12 validates only declared machine-executable layers. Machine PASS does not establish complete "
                "GEAIRM semantic conformance, AIPS Product qualification, governance approval, or architecture approval. "
                "Hybrid-assessment and assessment-only obligations remain NOT_EXECUTED and require governed assessment."
            ),
            "summary": {
                "testcasesExecuted": len(tests),
                "testcaseExpectationsMatched": testcase_passed,
                "testcaseExpectationMismatches": testcase_failed,
                "executableLayerChecks": len(exec_layer_results),
                "executableLayerExpectationsMatched": layer_passed,
                "executableLayerExpectationMismatches": layer_failed,
                "semanticAssessmentDeclarations": len(semantic_layers),
                "semanticAssessmentsExecuted": 0,
                "completeSemanticConformanceClaims": 0,
                "countsByCategory": counts_by_category,
            },
            "engine": {
                "python": sys.version.split()[0],
                "jsonschema": package_version("jsonschema"),
                "rdflib": package_version("rdflib"),
                "jsonSchemaDialect": "Draft 2020-12",
                "shaclExecution": {
                    "engine": "GEAIRM-A6 NodeShape/SPARQL subset executor over RDFLib",
                    "genericShaclImplementationClaim": False,
                    "failClosedOnUnsupportedA6Features": True,
                    "nodeShapes": len(self.a6.shapes),
                    "sparqlConstraints": self.a6.constraint_count,
                    "supportedTargets": ["sh:targetNode", "sh:targetClass"],
                    "supportedConstraint": "sh:SPARQLConstraint / sh:select",
                },
                "networkAccessRequired": False,
            },
            "artifacts": {
                "A4": relative_display(self.paths.ontology_a4, self.paths.root),
                "A5": relative_display(self.paths.context_a5, self.paths.root),
                "A6": relative_display(self.paths.shapes_a6, self.paths.root),
                "A7": relative_display(self.paths.schema_a7, self.paths.root),
                "A8": relative_display(self.paths.schema_a8, self.paths.root),
                "A10Manifest": relative_display(self.paths.positive_manifest, self.paths.root),
                "A11Manifest": relative_display(self.paths.negative_manifest, self.paths.root),
            },
            "preflight": self.preflight,
            "testcases": tests,
        }


def derive_default_root() -> Path:
    # script = <root>/static/spec/aips/geairm/0.1/conformance/<file>
    here = Path(__file__).resolve()
    try:
        return here.parents[6]
    except IndexError as exc:
        raise RunnerError("Unable to derive repository root from runner location") from exc


def parse_args(argv: list[str]) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Run GEAIRM 0.1 A10/A11 conformance-support testcases.")
    parser.add_argument(
        "--root",
        type=Path,
        default=None,
        help="Repository root. Defaults to the root derived from this script's canonical repository path.",
    )
    parser.add_argument(
        "--suite",
        choices=["all", "positive", "negative"],
        default="all",
        help="Authoritative manifest suite to execute (default: all).",
    )
    parser.add_argument(
        "--report",
        type=Path,
        default=None,
        help="Write deterministic JSON report to this path.",
    )
    parser.add_argument("--quiet", action="store_true", help="Suppress per-test console output.")
    return parser.parse_args(argv)


def main(argv: list[str] | None = None) -> int:
    args = parse_args(list(argv) if argv is not None else sys.argv[1:])
    try:
        root = (args.root or derive_default_root()).resolve()
        runner = ConformanceRunner(Paths.from_root(root), args.suite, verbose=not args.quiet)
        report = runner.run()
        if args.report:
            args.report.parent.mkdir(parents=True, exist_ok=True)
            args.report.write_text(dump_json_deterministic(report), encoding="utf-8")
        if not args.quiet:
            summary = report["summary"]
            print(
                f"GEAIRM-A12 {report['status']}: {summary['testcaseExpectationsMatched']}/"
                f"{summary['testcasesExecuted']} testcase expectations matched; "
                f"{summary['executableLayerExpectationsMatched']}/"
                f"{summary['executableLayerChecks']} executable layer expectations matched; "
                f"semantic assessments executed=0."
            )
        return 0 if report["status"] == "PASS" else 1
    except RunnerError as exc:
        print(f"GEAIRM-A12 RUNNER ERROR: {exc}", file=sys.stderr)
        return 2
    except Exception as exc:
        print(f"GEAIRM-A12 UNEXPECTED ERROR: {exc}", file=sys.stderr)
        return 2


if __name__ == "__main__":
    raise SystemExit(main())
