#!/usr/bin/env python3
"""GEAIRM 0.1 cross-artifact reconciliation runner (A13).

Reconciles the frozen A1-A12 executable artifacts without altering semantic
meaning. The script is offline and deterministic and emits a JSON report.
Exit codes: 0 reconciliation PASS, 1 reconciliation mismatch, 2 execution error.
"""
from __future__ import annotations
from pathlib import Path
import argparse, hashlib, json, re, sys
from collections import Counter
import yaml
from rdflib import Graph, URIRef, Literal, RDF, OWL, Namespace

GEAIRM_NS = "https://aips.kivanura.org/spec/aips/geairm/0.1/"
GEAIRM_META_NS = "https://aips.kivanura.org/spec/aips/geairm/0.1/meta/"
GEAIRM_INV_NS = "https://aips.kivanura.org/spec/aips/geairm/0.1/invariant/"
SH_NS = "http://www.w3.org/ns/shacl#"

class Checks:
    def __init__(self): self.items=[]
    def add(self, check, passed, detail="", category="general"):
        self.items.append({"check":check,"category":category,"passed":bool(passed),"detail":str(detail)})
    def equal(self, check, actual, expected, category="general"):
        self.add(check, actual==expected, f"actual={actual!r}; expected={expected!r}", category)
    def subset(self, check, required, actual, category="general"):
        missing=sorted(set(required)-set(actual)); self.add(check, not missing, f"missing={missing}", category)
    @property
    def passed(self): return sum(1 for x in self.items if x["passed"])
    @property
    def failed(self): return sum(1 for x in self.items if not x["passed"])

def enum_values(defn):
    if isinstance(defn,dict) and "enum" in defn: return list(defn["enum"])
    out=[]
    for arm in defn.get("anyOf",[]) if isinstance(defn,dict) else []: out.extend(arm.get("enum",[]))
    return out

def sha256(p):
    h=hashlib.sha256();
    with open(p,'rb') as f:
        for b in iter(lambda:f.read(1024*1024),b''): h.update(b)
    return h.hexdigest()

def context_iri(v): return v.get("@id") if isinstance(v,dict) else v

def reconcile(project_root: Path):
    b=project_root/'static/spec/aips/geairm/0.1'; c=Checks()
    req=[
      'geairm-0.1.concept-registry.yaml','geairm-0.1.relationship-registry.yaml','geairm-0.1.invariant-catalogue.yaml',
      'geairm-0.1.ttl','geairm-0.1.context.jsonld','geairm-0.1.shacl.ttl','geairm-0.1.schema.json','geairm-0.1.profile.schema.json',
      'examples/geairm-0.1.examples.json','testcases/geairm-0.1.positive-testcases.json','testcases/geairm-0.1.negative-testcases.json',
      'conformance/geairm-0.1.runner-manifest.json','conformance/geairm-0.1.conformance-report.json','docs-placeholder'
    ]
    for rel in req[:-1]: c.add(f"required artifact exists: {rel}",(b/rel).is_file(),category='artifact-presence')
    spec=project_root/'docs/geairm/0.1/geairm-0.1-specification.md'; c.add('required artifact exists: human-readable specification',spec.is_file(),category='artifact-presence')

    a1=yaml.safe_load((b/'geairm-0.1.concept-registry.yaml').read_text())
    a2=yaml.safe_load((b/'geairm-0.1.relationship-registry.yaml').read_text())
    a3=yaml.safe_load((b/'geairm-0.1.invariant-catalogue.yaml').read_text())
    ctx=json.loads((b/'geairm-0.1.context.jsonld').read_text())['@context']
    a7=json.loads((b/'geairm-0.1.schema.json').read_text()); a8=json.loads((b/'geairm-0.1.profile.schema.json').read_text())
    ex=json.loads((b/'examples/geairm-0.1.examples.json').read_text())
    pos=json.loads((b/'testcases/geairm-0.1.positive-testcases.json').read_text())
    neg=json.loads((b/'testcases/geairm-0.1.negative-testcases.json').read_text())
    rm=json.loads((b/'conformance/geairm-0.1.runner-manifest.json').read_text())
    rr=json.loads((b/'conformance/geairm-0.1.conformance-report.json').read_text())
    g=Graph(); g.parse(b/'geairm-0.1.ttl',format='turtle')
    sg=Graph(); sg.parse(b/'geairm-0.1.shacl.ttl',format='turtle')
    GMR=Namespace(GEAIRM_META_NS); SH=Namespace(SH_NS)

    owned=a1['ownedElements']; rels=a2['canonicalRelationships']; invs=a3['invariants']; bridges=a2['externalRelationshipBridges']
    # Registry integrity and canonical counts
    c.equal('A1 owned element count',len(owned),39,'registry-counts'); c.equal('A1 count metadata',a1['counts']['geairmOwnedElements'],len(owned),'registry-counts')
    kinds=Counter(x['elementKind'] for x in owned)
    for k,exp in [('Concept',28),('Role',6),('State',1),('Classification',1),('Classification value',3)]: c.equal(f'A1 kind count {k}',kinds[k],exp,'registry-counts')
    c.equal('A1 external reference count',len(a1['externalReferences']),57,'registry-counts'); c.equal('A1 external vocabulary count',len(a1['externalControlledVocabularies']),20,'registry-counts')
    c.equal('A1 editorial term count',len(a1['editorialAndNonEntityTerms']),12,'registry-counts')
    c.equal('A2 relationship count',len(rels),41,'registry-counts'); c.equal('A2 bridge count',len(bridges),15,'registry-counts'); c.equal('A2 family count',len(a2['relationshipFamilies']),9,'registry-counts')
    c.equal('A3 invariant count',len(invs),36,'registry-counts'); c.equal('A3 invariant count metadata',a3['counts']['total'],36,'registry-counts')
    for label,arr,key in [('A1 IDs',owned,'id'),('A1 local names',owned,'localName'),('A1 IRIs',owned,'iri'),('A2 IDs',rels,'id'),('A2 local names',rels,'localName'),('A2 IRIs',rels,'iri'),('A3 IDs',invs,'id')]:
        vals=[x[key] for x in arr]; c.equal(f'{label} unique',len(vals),len(set(vals)),'registry-identity')

    # A1 -> A4/A5/A7/A8
    a7_elem=set(enum_values(a7['$defs']['ElementReference'])); a7_type=set(enum_values(a7['$defs']['TypeReference'])); a8_elem=set(enum_values(a8['$defs']['CanonicalElementReference']))
    type_eligible=[]
    for x in owned:
        forms={x['id'],x['localName'],x['qname'],x['iri']}
        c.subset(f"A7 element reference forms {x['id']}",forms,a7_elem,'concept-crosswalk')
        c.subset(f"A8 canonical element forms {x['id']}",forms,a8_elem,'concept-crosswalk')
        c.equal(f"A5 term IRI {x['id']}",context_iri(ctx.get(x['localName'])),x['iri'],'concept-crosswalk')
        s=URIRef(x['iri']); c.add(f"A4 registryId {x['id']}",(s,GMR.registryId,Literal(x['id'])) in g,category='concept-crosswalk')
        if x['elementKind'] in {'Concept','Role','State','Classification'}:
            c.add(f"A4 owl:Class {x['id']}",(s,RDF.type,OWL.Class) in g,category='concept-crosswalk'); type_eligible.append(x)
        elif x['elementKind']=='Classification value':
            c.add(f"A4 owl:NamedIndividual {x['id']}",(s,RDF.type,OWL.NamedIndividual) in g,category='concept-crosswalk')
    for x in type_eligible:
        c.subset(f"A7 type reference forms {x['id']}",{x['localName'],x['qname'],x['iri']},a7_type,'concept-crosswalk')
    c.equal('A7 type-eligible owned element count',a7['x-geairm-counts']['typeEligibleOwnedElements'],len(type_eligible),'schema-counts')

    # A2 -> A4/A5/A7/A8
    a7_rel=set(enum_values(a7['$defs']['RelationshipReference'])); a8_rel=set(enum_values(a8['$defs']['CanonicalRelationshipReference']))
    for x in rels:
        forms={x['id'],x['localName'],x['qname'],x['iri']}
        c.subset(f"A7 relationship reference forms {x['id']}",forms,a7_rel,'relationship-crosswalk')
        c.subset(f"A8 canonical relationship forms {x['id']}",forms,a8_rel,'relationship-crosswalk')
        c.equal(f"A5 relationship term IRI {x['id']}",context_iri(ctx.get(x['localName'])),x['iri'],'relationship-crosswalk')
        s=URIRef(x['iri']); c.add(f"A4 rdf:Property {x['id']}",(s,RDF.type,RDF.Property) in g,category='relationship-crosswalk'); c.add(f"A4 registryId relationship {x['id']}",(s,GMR.registryId,Literal(x['id'])) in g,category='relationship-crosswalk')

    # A3 -> A4/A5/A6/A7/A8
    a7_inv=set(enum_values(a7['$defs']['InvariantReference'])); a8_inv=set(enum_values(a8['$defs']['InvariantReference']))
    implemented=set(str(o).replace(GEAIRM_INV_NS,'') for o in sg.objects(None,URIRef('https://aips.kivanura.org/spec/aips/geairm/0.1/shacl/implementsInvariant')))
    # fallback identify implementsInvariant by local predicate name
    if not implemented:
        for p in set(sg.predicates()):
            if str(p).endswith('implementsInvariant'):
                implemented.update(str(o).replace(GEAIRM_INV_NS,'') for o in sg.objects(None,p))
    for x in invs:
        iid=x['id']; iri=GEAIRM_INV_NS+iid
        c.subset(f"A7 invariant reference {iid}",{iid},a7_inv,'invariant-crosswalk'); c.subset(f"A8 invariant reference {iid}",{iid},a8_inv,'invariant-crosswalk')
        c.equal(f"A5 invariant term {iid}",context_iri(ctx.get(iid)),iri,'invariant-crosswalk')
        c.add(f"A4 invariant resource {iid}",(URIRef(iri),None,None) in g,category='invariant-crosswalk')
    c.equal('A6 NodeShape count',len(set(sg.subjects(RDF.type,SH.NodeShape))),24,'shacl-profile')
    c.equal('A6 SPARQLConstraint count',len(set(sg.objects(None,SH.sparql))),34,'shacl-profile')
    c.subset('A6 implemented invariant IDs belong to A3',implemented,{x['id'] for x in invs},'invariant-crosswalk')

    # Metadata count reconciliation
    for label,d in [('A7',a7),('A8',a8)]:
        counts=d['x-geairm-counts']; c.equal(f'{label} owned-element metadata',counts['ownedElements'],39,'schema-counts'); c.equal(f'{label} relationship metadata',counts['canonicalRelationships'],41,'schema-counts'); c.equal(f'{label} invariant metadata',counts['semanticInvariants'],36,'schema-counts')
    c.equal('A7 external bridge metadata',a7['x-geairm-counts']['externalRelationshipBridges'],15,'schema-counts')
    c.add('A5 has no default @vocab','@vocab' not in ctx,category='namespace-policy')
    c.equal('A5 geairm namespace',context_iri(ctx.get('geairm')),GEAIRM_NS,'namespace-policy')

    # A9 examples/index and A10 positive suite
    examples=ex['examples']; c.equal('A9 example count',len(examples),17,'example-test-reconciliation'); c.equal('A9 count metadata',ex['counts']['totalExamples'],17,'example-test-reconciliation')
    for e in examples:
        fp=b/'examples'/e['file']; c.add(f"A9 example exists {e['file']}",fp.is_file(),category='example-test-reconciliation')
    pt=pos['testcases']; nt=neg['testcases']; c.equal('A10 positive testcase count',len(pt),17,'example-test-reconciliation'); c.equal('A11 negative testcase count',len(nt),36,'example-test-reconciliation')
    c.equal('A10 count metadata',pos['counts']['totalPositiveTestcases'],17,'example-test-reconciliation'); c.equal('A11 count metadata',neg['counts']['totalNegativeTestcases'],36,'example-test-reconciliation')
    # Positive sources must map to A9 and hashes remain pinned
    a9files={e['file'] for e in examples}
    for t in pt:
        src=t['sourceA9Example']; inp=t['inputFile'];
        c.add(f"A10 source example indexed {t['testcaseId']}",Path(src).name in a9files,category='example-test-reconciliation')
        sp=((b/'testcases')/src).resolve() if not Path(src).is_absolute() else Path(src); ip=((b/'testcases')/inp).resolve() if not Path(inp).is_absolute() else Path(inp)
        c.add(f"A10 source exists {t['testcaseId']}",sp.is_file(),category='example-test-reconciliation'); c.add(f"A10 fixture exists {t['testcaseId']}",ip.is_file(),category='example-test-reconciliation')
        if sp.is_file() and ip.is_file():
            c.equal(f"A10 byte-identical source/fixture {t['testcaseId']}",sha256(sp),sha256(ip),'example-test-reconciliation')
            c.equal(f"A10 source checksum {t['testcaseId']}",sha256(sp),t['sourceSha256'],'example-test-reconciliation'); c.equal(f"A10 fixture checksum {t['testcaseId']}",sha256(ip),t['inputSha256'],'example-test-reconciliation')
        c.subset(f"A10 invariant references valid {t['testcaseId']}",[v['id'] if isinstance(v,dict) else v for v in t.get('applicableInvariants',[])],{x['id'] for x in invs},'test-invariants')
    for t in nt:
        c.subset(f"A11 invariant references valid {t['testcaseId']}",[v['id'] if isinstance(v,dict) else v for v in t.get('applicableInvariants',[])],{x['id'] for x in invs},'test-invariants')
        ip=((b/'testcases')/t['inputFile']).resolve(); c.add(f"A11 fixture exists {t['testcaseId']}",ip.is_file(),category='example-test-reconciliation')

    # A12 runner manifest/report reconciliation
    suites=rm['authoritativeSuites']; c.equal('A12 suite declaration count',len(suites),2,'runner-reconciliation')
    declared=sum(s['testcases'] for s in suites); c.equal('A12 declared testcase total',declared,53,'runner-reconciliation'); c.equal('A12 actual manifest testcase total',len(pt)+len(nt),53,'runner-reconciliation')
    sm=rr['summary']; c.equal('A12 report testcase count',sm['testcasesExecuted'],53,'runner-reconciliation'); c.equal('A12 report testcase expectations matched',sm['testcaseExpectationsMatched'],53,'runner-reconciliation'); c.equal('A12 report testcase mismatches',sm['testcaseExpectationMismatches'],0,'runner-reconciliation')
    c.equal('A12 report executable checks matched',sm['executableLayerExpectationsMatched'],sm['executableLayerChecks'],'runner-reconciliation'); c.equal('A12 report executable mismatches',sm['executableLayerExpectationMismatches'],0,'runner-reconciliation')
    c.equal('A12 semantic assessments executed',sm['semanticAssessmentsExecuted'],0,'runner-reconciliation'); c.equal('A12 complete semantic claims',sm['completeSemanticConformanceClaims'],0,'runner-reconciliation')
    c.equal('A12 report status',rr['status'],'PASS','runner-reconciliation')

    # Specification publication/download links: all current A1-A12 machine assets referenced and local target exists.
    spec_text=spec.read_text()
    required_pub=[
      'geairm-0.1.concept-registry.yaml','geairm-0.1.relationship-registry.yaml','geairm-0.1.invariant-catalogue.yaml','geairm-0.1.ttl','geairm-0.1.context.jsonld','geairm-0.1.shacl.ttl','geairm-0.1.schema.json','geairm-0.1.profile.schema.json',
      'examples/README.md','examples/geairm-0.1.examples.json','testcases/README.md','testcases/geairm-0.1.positive-testcases.json','testcases/negative/README.md','testcases/geairm-0.1.negative-testcases.json','conformance/README.md','conformance/geairm-0.1-conformance-runner.py','conformance/geairm-0.1.runner-manifest.json','conformance/geairm-0.1.conformance-report.json','reconciliation/README.md','reconciliation/geairm-0.1-reconcile.py','reconciliation/geairm-0.1.reconciliation-report.json']
    for rel in required_pub:
        url='/spec/aips/geairm/0.1/'+rel; c.add(f"spec publication link present {rel}",url in spec_text,category='publication-reconciliation'); c.add(f"publication target exists {rel}",(b/rel).is_file(),category='publication-reconciliation')

    # Frozen-semantic guardrails
    c.equal('canonical owned concepts preserved',len(owned),39,'semantic-freeze'); c.equal('canonical relationships preserved',len(rels),41,'semantic-freeze'); c.equal('canonical invariants preserved',len(invs),36,'semantic-freeze')
    c.equal('A12 semantic claim boundary preserved',sm['completeSemanticConformanceClaims'],0,'semantic-freeze')

    bycat={}
    for x in c.items:
        z=bycat.setdefault(x['category'],{'checks':0,'passed':0,'failed':0}); z['checks']+=1; z['passed']+=int(x['passed']); z['failed']+=int(not x['passed'])
    return {
      'artifact':'GEAIRM-A13 Cross-Artifact Reconciliation Report','version':'0.1','stage':'GEAIRM-A13','status':'PASS' if c.failed==0 else 'FAIL',
      'semanticClaimBoundary':'A13 reconciles consistency and traceability across A1-A12 artifacts. A13 PASS does not establish complete semantic conformance, AIPS Product qualification, governance approval, or architecture approval.',
      'summary':{'checks':len(c.items),'passed':c.passed,'failed':c.failed,'categories':bycat,'canonicalCounts':{'ownedElements':len(owned),'canonicalRelationships':len(rels),'semanticInvariants':len(invs),'externalRelationshipBridges':len(bridges),'a9Examples':len(examples),'a10PositiveTestcases':len(pt),'a11NegativeTestcases':len(nt),'a12TestcasesExecuted':sm['testcasesExecuted']}},
      'checks':c.items
    }

def main():
    ap=argparse.ArgumentParser(); ap.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[5]); ap.add_argument('--output',type=Path); args=ap.parse_args()
    try: report=reconcile(args.root)
    except Exception as e:
        print(f'GEAIRM-A13 reconciliation ERROR: {e}',file=sys.stderr); return 2
    out=args.output or (args.root/'static/spec/aips/geairm/0.1/reconciliation/geairm-0.1.reconciliation-report.json'); out.parent.mkdir(parents=True,exist_ok=True); out.write_text(json.dumps(report,indent=2)+"\n")
    print(f"GEAIRM-A13 reconciliation {report['status']}: {report['summary']['passed']}/{report['summary']['checks']} checks passed")
    if report['summary']['failed']:
        for x in report['checks']:
            if not x['passed']: print(f"FAIL: {x['check']} :: {x['detail']}")
        return 1
    return 0
if __name__=='__main__': raise SystemExit(main())
