"""Bind a successful same-package/same-target capability result before import."""
import json,hashlib,sys,os,re
from target_contract import validate_target,validate_probe_binding,fingerprint,verify_files
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())
validate_target(cfg,m);verify_files(root,m)
valid=p.get('passed') is True 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'] and validate_probe_binding(cfg,p)
valid=valid and all(p.get(k)==v for k,v in fingerprint(root,m).items())
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(mapping)==4187 and len(auto)==281 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']
binary=p.get('case_sensitive_unique',{})
valid=valid and 'case_sensitive_unique_hex_rtrim' in p.get('checks',[]) and binary.get('passed') is True and binary.get('rows')==7 and binary.get('index_expression')=='CAST(HEX(RTRIM(V)) AS VARCHAR(512 CHAR))' and binary.get('duplicate_error_codes')==[-6602,-6602,-6602]
client=p.get('client',{})
valid=valid and all(k in client for k in ['node_version','driver_entry','driver_version','driver_entry_sha256','driver_package_sha256','disql_realpath','disql_sha256','dpi_realpath','dpi_sha256'])
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')
