"""Bounded reviewed-derivative correspondence; original-source validation is a separate local command."""
from pathlib import Path
from engineering_references import validate_fact_content
import json,xml.etree.ElementTree as E,hashlib,re,base64,zlib
R=Path(__file__).resolve().parents[1];P=R/'examples/engineering-reference-extension'
def local(t):return t.rsplit('}',1)[-1]
def attr(e,k):return next((v for n,v in e.attrib.items() if n.startswith('{') and local(n)==k),None)
# Fixed selected identities from the reviewed derivative contract, not raw XML.
EXPECTED_NODE_KINDS={
 '_17_0_2_3_41e01aa_1382548453439_686811_74426':'uml:InitialNode',
 '_17_0_2_3_41e01aa_1382548455558_205728_74434':'uml:ActivityFinalNode',
 '_17_0_2_3_41e01aa_1383810481906_821693_75583':'uml:SendSignalAction',
 '_17_0_2_3_41e01aa_1383810483618_843330_75595':'uml:AcceptEventAction',
 '_18_0_4_baa02e2_1437598234583_903659_170363':'uml:ActivityParameterNode',
 '_18_0_5_baa02e2_1457628566053_846606_159260':'uml:ForkNode',
 '_18_0_5_baa02e2_1457628574540_652543_159280':'uml:JoinNode'}
def check(d=None,g=None,native=None,model=None):
 d=json.loads((P/'source/action-facts.json').read_text()) if d is None else d
 g=json.loads((P/'rendered/05-tmt-exposure.geometry.json').read_text()) if g is None else g
 native=json.loads((P/'validation/tmt-exposure-native-semantics.json').read_text()) if native is None else native
 model=(P/'derived/tmt-exposure.sysml').read_text() if model is None else model
 if not isinstance(d,dict) or not d:raise ValueError('Invalid or empty curated action facts')
 for key,fields in [('nodes',{'id','kind'}),('edges',{'id','kind','source','target'})]:
  rows=d.get(key)
  if not isinstance(rows,list) or not rows or any(not isinstance(row,dict) or not fields<=row.keys() for row in rows):raise ValueError('Invalid or empty curated action '+key)
 for label,rows in [('geometry',g),('saved native inventory',native)]:
  if not isinstance(rows,list) or not rows or any(not isinstance(row,dict) or not isinstance(row.get('kind'),str) for row in rows):raise ValueError('Invalid or empty '+label)
 if not isinstance(model,str) or not model.strip():raise ValueError('Invalid or empty model text')
 receipt=json.loads((P/'validation/native-inventory-inputs.json').read_text())['models']['tmt-exposure']
 if hashlib.sha256(model.encode()).hexdigest()!=receipt['model_sha256']:raise ValueError('Model changed after actual native inventory; regenerate parser/native evidence')
 if hashlib.sha256((P/'validation'/receipt['native_semantic_file']).read_bytes()).hexdigest()!=receipt['native_semantic_sha256']:raise ValueError('Native inventory bytes changed; recheck actual tool evidence')
 validate_fact_content(d)
 if d.get('schema')!='reviewed-action-facts/1':raise ValueError('Wrong derivative action fact schema')
 nodes=d['nodes']
 if len(nodes)!=len(EXPECTED_NODE_KINDS) or len({n['id'] for n in nodes})!=len(nodes) or {n['id']:n['kind'] for n in nodes}!=EXPECTED_NODE_KINDS:
  raise ValueError('Curated Activity node inventory/identity drift')
 ledger_edges={(e['id'],e['kind'],e['source'],e['target']) for e in d['edges']}
 drawn_edges={(e['source_id'],e['flow_type'],e['source'],e['target']) for e in g if e['kind']=='edge'}
 if ledger_edges!=drawn_edges or len(ledger_edges)!=7 or len(d['edges'])!=7:raise ValueError('Curated control/object flow correspondence changed')
 mapping={'uml:InitialNode':'initial','uml:ActivityFinalNode':'final','uml:SendSignalAction':'send','uml:AcceptEventAction':'accept','uml:ActivityParameterNode':'parameter','uml:ForkNode':'fork','uml:JoinNode':'join'}
 kinds={c['source_id']:c['kind'] for c in g}
 for node in d['nodes']:
  if node['kind'] not in mapping or kinds.get(node['id'])!=mapping[node['kind']]:raise ValueError('Lost/changed Activity node notation')
 send=next(n for n in d['nodes'] if n['kind']=='uml:SendSignalAction')
 if send['onPort']!='_17_0_2_3_41e01aa_1382548607674_333485_74722':raise ValueError('Changed curated send port')
 expected={('start','exposureFork'),('exposureFork','sendCommand'),('exposureFork','awaitAck'),('sendCommand','exposureJoin'),('awaitAck','exposureJoin'),('exposureJoin','done')}
 pairs={(x['source'].rsplit('::',1)[-1],x['targets'][0].rsplit('::',1)[-1]) for x in native if x['kind']=='SuccessionAsUsage'}
 if pairs!=expected or sum(x['kind']=='SuccessionAsUsage' for x in native)!=6:raise ValueError('Native fork/join successions changed')
 ns=next(x for x in native if x['kind']=='SendActionUsage')
 if ns['sender']!='TMTExposureDerived::PEASContext::PEAS2SHOut':raise ValueError('Native sender does not resolve source port')
 if 'new SH_Take_exposure_Cmd(dit) via PEAS2SHOut' not in model:raise ValueError('Lost input payload or port')
 # No receive port in the selected source; do not derive one.
 if re.search(r'action awaitAck accept SH_Take_exposure_Ack\s+(?:via|from)',model):raise ValueError('Invented receive endpoint')
 if re.search(r'first\s+sendCommand\s+then\s+awaitAck',model):raise ValueError('Serialized fork branches')
 if {(a,b) for a,b in re.findall(r'first\s+(\w+)\s+then\s+(\w+)\s*;',model)}!=expected:raise ValueError('Derived control graph changed')
 sv=E.parse(P/'rendered/05-tmt-exposure.svg').getroot()
 sg={(e.get('data-source-id'),e.get('data-flow-type'),e.get('data-source'),e.get('data-target')) for e in sv.iter() if local(e.tag)=='polyline'}
 if sg!=ledger_edges:raise ValueError('SVG flow endpoints changed')
 dx=E.parse(P/'rendered/05-tmt-exposure.drawio').getroot()
 dg={(e.get('sourceId'),e.get('flowType'),e.get('source'),e.get('target')) for e in dx.iter('mxCell') if e.get('edge')=='1'}
 if dg!=ledger_edges:raise ValueError('Editable flow endpoints changed')
 final_id=next(n['id'] for n in d['nodes'] if n['kind']=='uml:ActivityFinalNode')
 final_cell=next(e for e in dx.iter('mxCell') if e.get('sourceId')==final_id)
 encoded=re.search(r'shape=stencil\(([^)]+)\)',final_cell.get('style',''))
 if not encoded:raise ValueError('Editable activity-final glyph is not a bullseye')
 glyph=E.fromstring(zlib.decompress(base64.b64decode(encoded[1]),-15))
 if [e.get('color') for e in glyph.iter('fillcolor')]!=['#FFFFFF','#172F45'] or len(list(glyph.iter('ellipse')))!=2:raise ValueError('Editable activity-final glyph lost white ring/filled center')
 evaluation=json.loads((P/'validation/timing-evaluation.json').read_text())
 if [(e['input_seconds'],e['actual_boolean']) for e in evaluation['rows']]!=[(1799,True),(1800,True),(1801,False)]:raise ValueError('Wrong actual native timing boundary result')
 return {'curated_nodes':len(nodes),'curated_edges':len(ledger_edges),'saved_native_successions':len(pairs),'saved_native_resolved_send_port':True,'historical_native_timing_boundaries':len(evaluation['rows']),'claim_scope':'reviewed-derivative-correspondence','original_source_validation':'not_run; raw source inputs excluded','scope':'curated facts versus retained derivative/native/view evidence; no behavior simulation or full graphical conformance'}
if __name__=='__main__':print(json.dumps(check(),indent=2))
