"""Bind a successful same-package/same-target capability result before import."""
import json,hashlib,sys,os,re
from pathlib import Path
if len(sys.argv)!=3:raise SystemExit('Usage: python3 bind_probe.py private/import.private.json probe-.../result.json')
root=Path(__file__).resolve().parent;cfgpath=Path(sys.argv[1]).resolve();probe_file=Path(sys.argv[2]).resolve();cfg=json.loads(cfgpath.read_text());p=json.loads(probe_file.read_text());m=json.loads((root/'manifest.json').read_text())
valid=cfg['user']=='FOODSAFE2_APP' and cfg['expectedTablespace']=='FOODSAFE2_TBS' and p.get('passed')is True and p.get('target_user')==cfg['user']and p.get('instance')==cfg['expectedInstance']and p.get('build')==cfg['expectedBuild']and str(p.get('port'))==str(cfg['port'])and p.get('tablespace')==cfg['expectedTablespace']
valid=valid and p.get('manifest_sha256')==hashlib.sha256((root/'manifest.json').read_bytes()).hexdigest()and p.get('source_sha256')==m['source_sha256']and p.get('schema_sha256')==m['files']['sql/01_schema.sql']['sha256']and p.get('column_mapping_sha256')==m['files']['column-mapping.json']['sha256']
mapping=json.loads((root/'column-mapping.json').read_text());auto=[c for c in mapping if 'auto_increment' in c['EXTRA']];clones=p.get('clone_tests',[])
valid=valid and len(clones)==len(auto) and len({c.get('table') for c in clones})==len(auto)
valid=valid and all(any(t.get('table')==c['TABLE_NAME'] and t.get('passed') is True and str(t.get('seed'))==str(t.get('generated_next'))==str(c['TARGET_IDENTITY_SEED']) for t in clones) for c in auto)
valid=valid and isinstance(m.get('max_source_field_utf8_bytes'),int) and isinstance(p.get('large_field_bytes'),int) and p['large_field_bytes']>m['max_source_field_utf8_bytes']
expected_probe=cfg.get('isolationProbeTable')
valid=valid and isinstance(expected_probe,str) and re.fullmatch(r'FOODSAFE2_PROBE\.Z_CAP_VALUES',expected_probe) and p.get('isolation_probe_table')==expected_probe and p.get('probe_user')=='FOODSAFE2_PROBE' and p.get('isolation_probe_exists') is True and p.get('host')==cfg['host']
if not valid:raise SystemExit('Capability failed or belongs to another package/target: import remains blocked')
cfg['capabilityEvidenceFile']=str(probe_file);tmp=cfgpath.with_suffix('.tmp')
with tmp.open('x')as f:json.dump(cfg,f,indent=2)
tmp.chmod(0o600);os.replace(tmp,cfgpath);print('Capability result bound; importer will independently verify it again')
