#!/usr/bin/env python3
"""GEAIRM 0.1 regression suite (A14).

Locks the A1-A13 executable artifact surface, re-runs A12/A13 for behavioral
continuity, and executes negative controls proving that representative drift is
detected. It does not perform governed semantic assessment.

Exit codes: 0 regression PASS, 1 regression mismatch, 2 execution error.
"""
from __future__ import annotations
from pathlib import Path
import argparse, hashlib, json, shutil, subprocess, sys, tempfile
import yaml

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)
    @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 sha256(path: Path) -> str:
    h=hashlib.sha256()
    with path.open('rb') as f:
        for chunk in iter(lambda:f.read(1024*1024),b''): h.update(chunk)
    return h.hexdigest()

def canonical_hash(obj) -> str:
    payload=json.dumps(obj,sort_keys=True,separators=(',',':'),ensure_ascii=False).encode('utf-8')
    return hashlib.sha256(payload).hexdigest()

def a12_behavior(d):
    return {
      'status':d['status'],'summary':d['summary'],
      'preflight':[{'check':x['check'],'passed':x['passed']} for x in d.get('preflight',[])],
      'testcases':[
       {
        'testcaseId':t['testcaseId'],'suite':t['suite'],'category':t['category'],
        'expectationMatchStatus':t['expectationMatchStatus'],'machineBoundaryOutcome':t['machineBoundaryOutcome'],
        'semanticAssessmentStatus':t['semanticAssessmentStatus'],
        'completeSemanticConformanceEstablished':t['completeSemanticConformanceEstablished'],
        'layers':[
         {k:r.get(k) for k in ['layer','expectedOutcome','actualOutcome','expectationMatched','executionStatus'] if k in r}
         for r in t['layerResults']
        ]
       } for t in d['testcases']
      ]
    }

def a13_behavior(d):
    return {
      'stage':d['stage'],'status':d['status'],'summary':d['summary'],
      'checks':[{'check':x['check'],'category':x['category'],'passed':x['passed']} for x in d['checks']]
    }

def run(cmd, cwd: Path):
    return subprocess.run(cmd,cwd=cwd,text=True,capture_output=True)

def copy_project(root: Path, target: Path):
    shutil.copytree(root,target,dirs_exist_ok=False,ignore=shutil.ignore_patterns('.git','node_modules','build','.docusaurus'))

def regression(root: Path, manifest_path: Path):
    c=Checks(); manifest=json.loads(manifest_path.read_text())
    b=root/'static/spec/aips/geairm/0.1'

    # 1. A1-A13 predecessor byte lock.
    locks=manifest['predecessorArtifactSurface']['files']
    c.equal('locked predecessor artifact count',len(locks),manifest['predecessorArtifactSurface']['lockedFiles'],'baseline-lock')
    for item in locks:
        p=root/item['path']; exists=p.is_file()
        c.add(f"locked artifact exists {item['path']}",exists,category='baseline-lock')
        if exists:
            c.equal(f"locked artifact size {item['path']}",p.stat().st_size,item['sizeBytes'],'baseline-lock')
            c.equal(f"locked artifact sha256 {item['path']}",sha256(p),item['sha256'],'baseline-lock')

    # 2. Frozen semantic counts independently re-read from A1/A2/A3.
    cr=yaml.safe_load((b/'geairm-0.1.concept-registry.yaml').read_text())
    rr=yaml.safe_load((b/'geairm-0.1.relationship-registry.yaml').read_text())
    ir=yaml.safe_load((b/'geairm-0.1.invariant-catalogue.yaml').read_text())
    exp=manifest['expectedSemanticCounts']
    c.equal('owned element count frozen',len(cr['ownedElements']),exp['ownedElements'],'semantic-freeze')
    c.equal('canonical relationship count frozen',len(rr['canonicalRelationships']),exp['canonicalRelationships'],'semantic-freeze')
    c.equal('semantic invariant count frozen',len(ir['invariants']),exp['semanticInvariants'],'semantic-freeze')
    c.equal('external relationship bridge count frozen',len(rr['externalRelationshipBridges']),exp['externalRelationshipBridges'],'semantic-freeze')

    # 3. Re-run A12 and compare behavior, not environment metadata.
    with tempfile.TemporaryDirectory(prefix='geairm-a14-run-') as td:
        td=Path(td)
        a12out=td/'a12.json'; a13out=td/'a13.json'
        p12=run([sys.executable,str(b/'conformance/geairm-0.1-conformance-runner.py'),'--root',str(root),'--suite','all','--report',str(a12out),'--quiet'],root)
        c.equal('A12 reference rerun exit code',p12.returncode,0,'behavior-continuity')
        if a12out.is_file():
            d12=json.loads(a12out.read_text()); e12=manifest['expectedExecution']['A12']; sm=d12['summary']
            c.equal('A12 rerun status',d12['status'],e12['status'],'behavior-continuity')
            for k in ['testcasesExecuted','testcaseExpectationsMatched','executableLayerChecks','executableLayerExpectationsMatched','semanticAssessmentDeclarations','semanticAssessmentsExecuted','completeSemanticConformanceClaims']:
                c.equal(f'A12 rerun {k}',sm[k],e12[k],'behavior-continuity')
            c.equal('A12 normalized behavior digest',canonical_hash(a12_behavior(d12)),e12['behaviorDigest'],'behavior-continuity')
        else:
            c.add('A12 rerun report produced',False,p12.stderr,'behavior-continuity')

        p13=run([sys.executable,str(b/'reconciliation/geairm-0.1-reconcile.py'),'--root',str(root),'--output',str(a13out)],root)
        c.equal('A13 reconciliation rerun exit code',p13.returncode,0,'behavior-continuity')
        if a13out.is_file():
            d13=json.loads(a13out.read_text()); e13=manifest['expectedExecution']['A13']; sm=d13['summary']
            c.equal('A13 rerun status',d13['status'],e13['status'],'behavior-continuity')
            for k in ['checks','passed','failed']:
                c.equal(f'A13 rerun {k}',sm[k],e13[k],'behavior-continuity')
            c.equal('A13 normalized behavior digest',canonical_hash(a13_behavior(d13)),e13['behaviorDigest'],'behavior-continuity')
        else:
            c.add('A13 rerun report produced',False,p13.stderr,'behavior-continuity')

    # 4. Current A14 publication references must be visible and resolvable.
    spec=(root/'docs/geairm/0.1/geairm-0.1-specification.md').read_text()
    pubs=[
      'regression/README.md','regression/geairm-0.1-regression.py',
      'regression/geairm-0.1.regression-manifest.json','regression/geairm-0.1.regression-report.json'
    ]
    for rel in pubs:
        c.add(f'A14 publication link present {rel}',('/spec/aips/geairm/0.1/'+rel) in spec,category='publication-regression')
        c.add(f'A14 publication target exists {rel}',(b/rel).is_file(),category='publication-regression')

    # 5. Negative controls: representative drift must be detected.
    controls=[]
    with tempfile.TemporaryDirectory(prefix='geairm-a14-controls-') as td:
        td=Path(td)
        # NC01: checksum-only tamper of a known positive fixture; JSON remains valid.
        t1=td/'nc01'; copy_project(root,t1)
        f=t1/'static/spec/aips/geairm/0.1/testcases/positive/m16-p01-primary-learned-model-fraud.json'
        f.write_bytes(f.read_bytes()+b'\n')
        r=run([sys.executable,str(t1/'static/spec/aips/geairm/0.1/conformance/geairm-0.1-conformance-runner.py'),'--root',str(t1),'--suite','all','--quiet'],t1)
        controls.append(('A14-NC01',r.returncode,1,(r.stdout+r.stderr)[-1200:]))

        # NC02: evolve A6 beyond the supported frozen profile. Runner must fail closed.
        t2=td/'nc02'; copy_project(root,t2)
        f=t2/'static/spec/aips/geairm/0.1/geairm-0.1.shacl.ttl'
        with f.open('a',encoding='utf-8') as out: out.write('\n[] a <http://www.w3.org/ns/shacl#PropertyShape> .\n')
        r=run([sys.executable,str(t2/'static/spec/aips/geairm/0.1/conformance/geairm-0.1-conformance-runner.py'),'--root',str(t2),'--suite','all','--quiet'],t2)
        controls.append(('A14-NC02',r.returncode,2,(r.stdout+r.stderr)[-1200:]))

        # NC03: drift the canonical A5 geairm namespace. Reconciliation must reject it.
        t3=td/'nc03'; copy_project(root,t3)
        f=t3/'static/spec/aips/geairm/0.1/geairm-0.1.context.jsonld'; d=json.loads(f.read_text())
        d['@context']['geairm']='https://invalid.example/geairm/0.1/'
        f.write_text(json.dumps(d,indent=2)+'\n')
        r=run([sys.executable,str(t3/'static/spec/aips/geairm/0.1/reconciliation/geairm-0.1-reconcile.py'),'--root',str(t3),'--output',str(t3/'a13.json')],t3)
        controls.append(('A14-NC03',r.returncode,1,(r.stdout+r.stderr)[-1200:]))

        # NC04: remove a required publication reference. Reconciliation must reject it.
        t4=td/'nc04'; copy_project(root,t4)
        f=t4/'docs/geairm/0.1/geairm-0.1-specification.md'; s=f.read_text()
        target='/spec/aips/geairm/0.1/reconciliation/geairm-0.1.reconciliation-report.json'
        f.write_text(s.replace(target,'/broken/reconciliation-report.json',1))
        r=run([sys.executable,str(t4/'static/spec/aips/geairm/0.1/reconciliation/geairm-0.1-reconcile.py'),'--root',str(t4),'--output',str(t4/'a13.json')],t4)
        controls.append(('A14-NC04',r.returncode,1,(r.stdout+r.stderr)[-1200:]))

    expected={x['id']:x['expectedExitCode'] for x in manifest['negativeControls']}
    for cid,actual,_default,detail in controls:
        c.equal(f'{cid} expected detection exit code',actual,expected[cid],'negative-controls')
        c.add(f'{cid} drift detected',actual!=0,detail,'negative-controls')

    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-A14 Regression Report','version':'0.1','stage':'GEAIRM-A14',
      'status':'PASS' if c.failed==0 else 'FAIL',
      'semanticClaimBoundary':'A14 verifies regression stability and representative drift detection. A14 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,
        'lockedPredecessorFiles':len(locks),'negativeControlsExecuted':len(controls),
        'semanticAssessmentsExecuted':0,'completeSemanticConformanceClaims':0
      },
      'negativeControls':[{'id':cid,'actualExitCode':actual,'expectedExitCode':expected[cid],'detected':actual==expected[cid]} for cid,actual,_d,_detail in controls],
      'checks':c.items
    }

def derive_default_root(): return Path(__file__).resolve().parents[6]

def main():
    ap=argparse.ArgumentParser(); ap.add_argument('--root',type=Path); ap.add_argument('--manifest',type=Path); ap.add_argument('--output',type=Path); args=ap.parse_args()
    root=(args.root or derive_default_root()).resolve(); manifest=args.manifest or (root/'static/spec/aips/geairm/0.1/regression/geairm-0.1.regression-manifest.json')
    try: report=regression(root,manifest)
    except Exception as exc:
        print(f'GEAIRM-A14 regression ERROR: {exc}',file=sys.stderr); return 2
    out=args.output or (root/'static/spec/aips/geairm/0.1/regression/geairm-0.1.regression-report.json')
    out.parent.mkdir(parents=True,exist_ok=True); out.write_text(json.dumps(report,indent=2)+'\n')
    print(f"GEAIRM-A14 regression {report['status']}: {report['summary']['passed']}/{report['summary']['checks']} checks passed; negative controls={report['summary']['negativeControlsExecuted']}")
    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())
