"""Package only a fully verified, released assembly. No native/resident execution."""
import importlib.util
import json
import mmap
from pathlib import Path
import shutil
import subprocess
import sys
sys.dont_write_bytecode = True
OUT = Path(__file__).resolve().parent
ROOT = OUT.parents[3]
spec = importlib.util.spec_from_file_location('field302producer',OUT/'run.py')
p = importlib.util.module_from_spec(spec)
spec.loader.exec_module(p)
spec = importlib.util.spec_from_file_location('field302symbols',ROOT/'.spt/preserved/302/symbols/prepare_symbols.py')
s = importlib.util.module_from_spec(spec)
spec.loader.exec_module(s)
g = p.g
PHASES = ('pool-claim','build','meet-diag','guards','starve','attach','stack-unit','checks','version','wedge-provisioned','checks-post-fixture','version-post-fixture','pool-release')

def identity(path, parser):
    with path.open('rb') as file, mmap.mmap(file.fileno(),0,access=mmap.ACCESS_READ) as data:
        return parser(data)

def artifact(path):
    return dict(path=str(path),bytes=path.stat().st_size,sha256=g.digest(path))

def main():
    receipts = {name:json.loads((OUT/name/'receipt.json').read_bytes()) for name in PHASES}
    review = json.loads((OUT/'build-artifact-review.json').read_bytes())
    if review['authorization']['message_id']!='6SEWFO43' or review['build_commit']!=p.r.HEAD or review['original_receipt_sha256']!=g.digest(OUT/'build/receipt.json'):
        raise RuntimeError('attributed native-success ruling/provenance mismatch')
    for name,r in receipts.items():
        if r['source_changes'] or r.get('finalization_error'):
            raise RuntimeError('changed source or failed finalization: '+name)
        if name == 'attach':
            log = (OUT/'attach/tests.stderr').read_text(encoding='utf-8')
            if [c['native_exit'] for c in r['commands']] != [0,100] or r['driver_exit']!=1 or 'required test fixture `mock-session` is missing' not in log or '17 tests run: 16 passed, 1 failed, 0 skipped' not in log:
                raise RuntimeError('unexpected original attach failure')
        elif any(c['native_exit']!=0 for c in r['commands']):
            raise RuntimeError('failed native command: '+name)
        if name == 'build':
            if r['driver_exit']!=1 or r['error']!='RuntimeError("builder/pool user refused: [(54960, \'cargo.exe\')]")':
                raise RuntimeError('unexpected build wrapper outcome')
        elif name != 'attach' and (r['status']!='passed' or r['driver_exit']!=0):
            raise RuntimeError('incomplete/failed phase: '+name)
        if r['source_before']['head']!=p.r.HEAD or r['source_after']['head']!=p.r.HEAD:
            raise RuntimeError('wrong assembly identity: '+name)
    wedge = receipts['wedge-provisioned']
    if wedge['authorization_message']!='P3TDCW7C' or wedge['artifact_invariance_authorization']!='OEUO574A' or wedge['original_attach_receipt_sha256']!=g.digest(OUT/'attach/receipt.json'):
        raise RuntimeError('fixture-provisioned wedge authorization/provenance mismatch')
    if not wedge['spt_before_fixture'] or wedge['spt_before_fixture']!=wedge['spt_after_fixture'] or wedge['spt_before_fixture']!=wedge['spt_after_wedge']:
        raise RuntimeError('SPT executable/PDB changed across fixture leg')
    owner = json.loads((g.TARGET/'POOL-OWNER.json').read_bytes())
    if set(owner)!={'owner_tree','written_by'} or Path(owner['owner_tree']).resolve()!=g.TREE.resolve():
        raise RuntimeError('owned pool is not released')
    version = (OUT/'version-post-fixture/version.stdout').read_text(encoding='utf-8').strip()
    if version != 'spt 0.70.0':
        raise RuntimeError('unexpected actual CLI version: '+version)
    expected = review['built_subjects']['spt.exe']
    exe,pdb = OUT/'built-subjects/spt.exe',OUT/'built-subjects/spt.pdb'
    if g.digest(exe)!=expected['exe_sha256'] or g.digest(pdb)!=expected['pdb_sha256']:
        raise RuntimeError('built application bytes changed')
    pe,pi = identity(exe,s.pe_identity),identity(pdb,s.pdb_identity)
    if pe['codeview']['guid']!=pi['guid'] or pe['codeview']['age']!=pi['dbi_age'] or pe['codeview']['name'].lower()!='spt.pdb':
        raise RuntimeError('application PE/PDB mismatch')
    original = ROOT/'.spt/preserved/302/enlyzeam-symbols'
    manifest = json.loads((original/'manifest.json').read_bytes())
    if len(manifest['modules'])!=15 or g.digest(original/'manifest.json')!='6431f18c6e54db4c4834d13a8b66c1c8a43d5c40c4e0fa7797b0960f73221978':
        raise RuntimeError('historical OS provenance changed')
    capsule = ROOT/'.spt/preserved/302/artifacts-release-0f80fef8'
    if (capsule/'manifest.json').exists():
        raise RuntimeError('capsule already finalized; never overwrite')
    symbols = capsule/'symbols'
    if g.digest(capsule/'spt.exe')!=expected['exe_sha256'] or g.digest(capsule/'spt.pdb')!=expected['pdb_sha256']:
        raise RuntimeError('immutable application copy mismatch')
    bundle = []
    for module in manifest['modules']:
        source = Path(module['flat_path'])
        dest = symbols/source.name
        if g.digest(source)!=module['pdb_sha256'] or not module['identity_match']:
            raise RuntimeError('OS symbol provenance mismatch: '+source.name)
        actual = identity(dest,s.pdb_identity)
        cv = module['pe']['codeview']
        if actual!=module['pdb_identity'] or actual['guid']!=cv['guid'] or actual['dbi_age']!=cv['age'] or g.digest(dest)!=module['pdb_sha256']:
            raise RuntimeError('OS symbol copy or identity mismatch: '+source.name)
        bundle.append(dict(module=module['module'],**artifact(dest),pdb_identity=actual,codeview=cv))
    app_symbol = artifact(symbols/'spt.pdb')
    if app_symbol['sha256']!=expected['pdb_sha256'] or identity(symbols/'spt.pdb',s.pdb_identity)!=pi:
        raise RuntimeError('bundle application PDB mismatch')
    bundle.append(dict(module='spt.exe',**app_symbol,pdb_identity=pi,codeview=pe['codeview']))
    if len(bundle)!=16 or len({Path(x['path']).name.lower() for x in bundle})!=16:
        raise RuntimeError('exactly sixteen distinct PDBs required')
    if g.digest(symbols/'manifest.os-only.json')!=manifest['os_only_manifest']['sha256']:
        raise RuntimeError('OS-only manifest copy mismatch')
    g.save(symbols/'manifest.json',dict(scope='ENLYZEAM Windows 19045.6466 OS symbols plus new assembly application; not HFENDULEAM OS symbols',build_commit=p.r.HEAD,modules=bundle,historical_manifest=artifact(original/'manifest.json'),immutable_os_manifest=artifact(symbols/'manifest.os-only.json')))
    stat = subprocess.run(['git','diff','--stat','a593ece06d5b67afa7fcdd23824b585675d7cc04',p.r.HEAD],cwd=g.TREE,capture_output=True,text=True,check=True).stdout
    result = dict(build_commit=p.r.HEAD,build_profile='release+line-tables',profile=p.r.PROFILE,cli_version=version,broker_version='0.70.0',producer_host=g.os.environ.get('COMPUTERNAME'),path_scope='Producer-local capsule; ENLYZEAM transfer and installed/resident verification are operator-owned and not performed',fix_commit='a593ece06d5b67afa7fcdd23824b585675d7cc04',fix_branch='fix/302-meet-offload',assembly_branch=p.r.BRANCH,pr='https://github.com/BigscreenVR/spt-bs-core/pull/231',exe=artifact(capsule/'spt.exe'),pdb=artifact(capsule/'spt.pdb'),symbol_pairing_reviewed=True,release_pair_identity=dict(pe=pe,pdb=pi,guid_match=True,dbi_age_match=True),symbol_bundle=artifact(symbols/'manifest.json'),symbol_count=len(bundle),diagnostic_delta_from_fix=stat,proofs={name:artifact(OUT/name/'receipt.json') for name in PHASES},local_boundary_proof=receipts['meet-diag']['local_boundary_proof'],released_pool=str(g.TARGET),packager=artifact(Path(__file__)),field_acceptance='PENDING operator restage, field capture and local/remote rc checks')
    result['build_review'] = artifact(OUT/'build-artifact-review.json')
    result['build_outcome'] = 'Native build 0; wrapper 1 on attributed PR231 post-build CPU contention. Doyle 6SEWFO43 accepts the build without rebuild. Subsequent cohorts require independent quiet admission.'
    result['attach_outcome'] = 'Original cohort: 16 passed, wedge precondition exit100 because release mock-session was absent. Doyle P3TDCW7C authorized fixture provisioning and only that cell; wedge-provisioned must pass with source and SPT executable/PDB unchanged. Original rig red preserved.'
    result['fixture_invariance'] = wedge['spt_before_fixture']
    result['resumption'] = artifact(OUT/'resumption.json')
    g.save(capsule/'manifest.json',result)
    g.save(OUT/'capsule-identity.json',artifact(capsule/'manifest.json'))
    print(json.dumps(artifact(capsule/'manifest.json'),indent=2))
    return 0

if __name__=='__main__':
    sys.exit(main())
