#!/usr/bin/env python3
"""GEAIRM 0.1 A15 release-closure verifier.

Closes the executable release candidate after verifying the A1-A14 artifact
surface and re-running A12/A13/A14. It does not perform semantic assessment or
governed publication/promotion.

Exit codes: 0 PASS, 1 closure mismatch, 2 execution/configuration error.
"""
from __future__ import annotations
from pathlib import Path
import argparse, hashlib, json, 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 run(cmd, cwd):
    return subprocess.run(cmd,cwd=cwd,text=True,capture_output=True)

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

    # 1. Byte-lock the complete A1-A14 predecessor machine-artifact surface.
    locks=m['predecessorArtifactSurface']['files']
    c.equal('A1-A14 locked predecessor artifact count',len(locks),m['predecessorArtifactSurface']['lockedFiles'],'release-lock')
    for item in locks:
        p=root/item['path']; exists=p.is_file()
        c.add(f"locked artifact exists {item['path']}",exists,category='release-lock')
        if exists:
            c.equal(f"locked artifact size {item['path']}",p.stat().st_size,item['sizeBytes'],'release-lock')
            c.equal(f"locked artifact sha256 {item['path']}",sha256(p),item['sha256'],'release-lock')

    # 2. Frozen semantic counts remain unchanged.
    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=m['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, A13 and A14 from the release-candidate tree.
    with tempfile.TemporaryDirectory(prefix='geairm-a15-') as td:
        td=Path(td); a12o=td/'a12.json'; a13o=td/'a13.json'; a14o=td/'a14.json'
        p12=run([sys.executable,str(b/'conformance/geairm-0.1-conformance-runner.py'),'--root',str(root),'--suite','all','--report',str(a12o),'--quiet'],root)
        c.equal('A12 release rerun exit code',p12.returncode,0,'execution-continuity')
        if a12o.is_file():
            d=json.loads(a12o.read_text()); e=m['expectedExecution']['A12']; sm=d['summary']
            c.equal('A12 release rerun status',d['status'],e['status'],'execution-continuity')
            for k in ['testcasesExecuted','testcaseExpectationsMatched','executableLayerChecks','executableLayerExpectationsMatched','semanticAssessmentDeclarations','semanticAssessmentsExecuted','completeSemanticConformanceClaims']:
                c.equal(f'A12 release rerun {k}',sm[k],e[k],'execution-continuity')
        else: c.add('A12 release rerun report produced',False,p12.stderr,'execution-continuity')

        p13=run([sys.executable,str(b/'reconciliation/geairm-0.1-reconcile.py'),'--root',str(root),'--output',str(a13o)],root)
        c.equal('A13 release rerun exit code',p13.returncode,0,'execution-continuity')
        if a13o.is_file():
            d=json.loads(a13o.read_text()); e=m['expectedExecution']['A13']; sm=d['summary']
            c.equal('A13 release rerun status',d['status'],e['status'],'execution-continuity')
            for k in ['checks','passed','failed']: c.equal(f'A13 release rerun {k}',sm[k],e[k],'execution-continuity')
        else: c.add('A13 release rerun report produced',False,p13.stderr,'execution-continuity')

        p14=run([sys.executable,str(b/'regression/geairm-0.1-regression.py'),'--root',str(root),'--output',str(a14o)],root)
        c.equal('A14 release rerun exit code',p14.returncode,0,'execution-continuity')
        if a14o.is_file():
            d=json.loads(a14o.read_text()); e=m['expectedExecution']['A14']; sm=d['summary']
            c.equal('A14 release rerun status',d['status'],e['status'],'execution-continuity')
            for k in ['checks','passed','failed','lockedPredecessorFiles','negativeControlsExecuted','semanticAssessmentsExecuted','completeSemanticConformanceClaims']:
                c.equal(f'A14 release rerun {k}',sm[k],e[k],'execution-continuity')
        else: c.add('A14 release rerun report produced',False,p14.stderr,'execution-continuity')

    # 4. Stored predecessor reports must themselves remain successful.
    stored=[
      ('A12',b/'conformance/geairm-0.1.conformance-report.json'),
      ('A13',b/'reconciliation/geairm-0.1.reconciliation-report.json'),
      ('A14',b/'regression/geairm-0.1.regression-report.json')]
    for stage,p in stored:
        c.add(f'{stage} stored report exists',p.is_file(),category='stored-evidence')
        if p.is_file(): c.equal(f'{stage} stored report PASS',json.loads(p.read_text())['status'],'PASS','stored-evidence')

    # 5. A15 publication references and explicit governance boundary.
    spec=(root/'docs/geairm/0.1/geairm-0.1-specification.md').read_text()
    for path in m['releaseArtifacts']:
        rel=path.split('static/spec/aips/geairm/0.1/',1)[1]
        c.add(f'A15 publication link present {rel}',('/spec/aips/geairm/0.1/'+rel) in spec,category='publication-closure')
        if rel.endswith('geairm-0.1.release-report.json'):
            # The closure report is the output of this verifier and is written after checks complete.
            c.add(f'A15 publication target generated by verifier {rel}',True,category='publication-closure')
        else:
            c.add(f'A15 publication target exists {rel}',(root/path).is_file(),category='publication-closure')
    c.add('A15 status marks executable formalization complete','A15 complete' in spec and 'executable formalization complete' in spec,category='governance-boundary')
    c.add('Working Draft status retained','**Status:** Working Draft' in spec,category='governance-boundary')
    c.add('governed publication explicitly pending','governed publication pending' in spec.lower(),category='governance-boundary')
    c.add('GEAIRA identified as downstream programme','GEAIRA 0.1' in spec,category='governance-boundary')

    # 6. Closure itself must not overclaim semantic/governance proof.
    c.equal('A15 semantic concepts introduced',m['newSemanticConcepts'],0,'semantic-boundary')
    c.equal('A15 semantic relationships introduced',m['newSemanticRelationships'],0,'semantic-boundary')
    c.equal('A15 semantic invariants introduced',m['newSemanticInvariants'],0,'semantic-boundary')
    c.equal('governed publication promotion remains false',m['governanceStatus']['governedPublicationPromoted'],False,'semantic-boundary')
    c.equal('governance approval claim remains false',m['governanceStatus']['governanceApprovalClaimed'],False,'semantic-boundary')
    c.equal('machine semantic assessment remains false',m['executionContract']['semanticAssessmentsMachineExecuted'],False,'semantic-boundary')
    c.equal('machine PASS not complete semantic conformance',m['executionContract']['machinePassEstablishesCompleteSemanticConformance'],False,'semantic-boundary')

    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-A15 Release Closure Report','version':'0.1','stage':'GEAIRM-A15',
      'status':'PASS' if c.failed==0 else 'FAIL',
      'releaseStatus':'CLOSED_EXECUTABLE_RELEASE_CANDIDATE' if c.failed==0 else 'NOT_CLOSED',
      'documentStatus':'Working Draft','governedPublicationPromoted':False,
      'semanticClaimBoundary':'A15 closes the executable GEAIRM 0.1 release candidate. A15 PASS does not establish complete semantic conformance, AIPS Product qualification, governance approval, governed publication, or architecture approval.',
      'summary':{'checks':len(c.items),'passed':c.passed,'failed':c.failed,'categories':bycat,'lockedA1A14Files':len(locks),'semanticAssessmentsExecuted':0,'completeSemanticConformanceClaims':0,'newSemanticConcepts':0,'newSemanticRelationships':0,'newSemanticInvariants':0},
      'nextProgramme':m['nextProgramme'],'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/release/geairm-0.1.release-manifest.json'
    try: report=close_release(root,manifest)
    except Exception as exc:
        print(f'GEAIRM-A15 release closure ERROR: {exc}',file=sys.stderr); return 2
    out=args.output or root/'static/spec/aips/geairm/0.1/release/geairm-0.1.release-report.json'; out.parent.mkdir(parents=True,exist_ok=True); out.write_text(json.dumps(report,indent=2)+'\n')
    print(f"GEAIRM-A15 release closure {report['status']}: {report['summary']['passed']}/{report['summary']['checks']} checks passed; status={report['releaseStatus']}")
    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())
