"""Bind local probe experiments and an explicit-ID import to the target user."""
import json,re,hashlib,sys,collections,os
from pathlib import Path
if not __debug__:raise SystemExit('Python optimization is forbidden for migration acceptance gates')
root=Path(__file__).resolve().parent
if len(sys.argv)!=4:raise SystemExit('Usage: python3 finalize_identity.py private/import.private.json probe-.../result.json run-.../result.json')
cfgpath=Path(sys.argv[1]).resolve();cfg=json.loads(cfgpath.read_text());probe=json.loads(Path(sys.argv[2]).read_text());run=json.loads(Path(sys.argv[3]).read_text());m=json.loads((root/'manifest.json').read_text());mapping=json.loads((root/'column-mapping.json').read_text())
assert probe['passed']and len(probe['clone_tests'])==len([c for c in mapping if 'auto_increment' in c['EXTRA']]) and run['phase']=='imported_requires_independent_verification'
assert probe['target_user']==cfg['user']==run['target']['user']
assert cfg['expectedInstance']==probe['instance']==run['target']['instance']and cfg['expectedBuild']==probe['build']==run['target']['build']
assert probe['source_sha256']==m['source_sha256']and probe['schema_sha256']==m['files']['sql/01_schema.sql']['sha256']and probe['column_mapping_sha256']==m['files']['column-mapping.json']['sha256']
fp={'manifest_sha256':hashlib.sha256((root/'manifest.json').read_bytes()).hexdigest(),'source_sha256':m['source_sha256'],'schema_sha256':m['files']['sql/01_schema.sql']['sha256'],'column_mapping_sha256':m['files']['column-mapping.json']['sha256']}
assert all(probe.get(k)==v and run.get('payload',{}).get(k)==v for k,v in fp.items())
assert str(probe['port'])==str(cfg['port'])==str(run['target']['port'])and probe['tablespace']==cfg['expectedTablespace']==run['target']['tablespace']
assert probe['client']==run['client']and run['capability_sha256']==hashlib.sha256(Path(sys.argv[2]).read_bytes()).hexdigest()
assert {t['table']:int(t['rows'])for t in run['tables']}=={t['table']:t['rows']for t in m['tables']}and len({t['table']for t in run['tables']})==len(run['tables'])
auto_cols=[c for c in mapping if'auto_increment'in c['EXTRA']]
assert len(probe['clone_tests'])==len(auto_cols)and len({c['table']for c in probe['clone_tests']})==len(auto_cols)
for c in auto_cols:
 z=next(t for t in probe['clone_tests']if t['table']==c['TABLE_NAME']);assert z['passed']and str(z['seed'])==str(z['generated_next'])==str(c['TARGET_IDENTITY_SEED'])
auto={c['TABLE_NAME']:c for c in mapping if'auto_increment'in c['EXTRA']};counts=collections.Counter();alln=0
for t in m['tables']:
 for rel in t['data_files']:
  p=root/rel;h=hashlib.sha256()
  with p.open('rb')as f:
   for line in f:
    h.update(line)
    if line.startswith((b'INSERT ',b'@insert ')):
     z=re.match(rb'(?:INSERT|@insert) INTO "([A-Z0-9_]+)"\(([^)]*)\) VALUES\(',line)
     assert z and z[1].decode().lower()==t['table'];alln+=1
     if t['table']in auto:
      assert ('"'+auto[t['table']]['COLUMN_NAME'].upper()+'"').encode()in z[2].split(b',');counts[t['table']]+=1
  assert h.hexdigest()==m['files'][rel]['sha256']
 assert t['table']not in auto or counts[t['table']]==t['rows']
assert alln==m['total_rows']==run['total_rows']and len(run['tables'])==m['target_tables']
e={'instance':cfg['expectedInstance'],'user':cfg['user'],'build':cfg['expectedBuild'],'source_sha256':m['source_sha256'],'schema_sha256':probe['schema_sha256'],'column_mapping_sha256':probe['column_mapping_sha256'],'all_auto_inserts_explicit':True,'no_implicit_target_writes':True,'clone_tests':probe['clone_tests'],'all_insert_statements':alln,'passed':True,'execution_condition':'Exclusive new target: application and manual writes must remain stopped until acceptance'}
p=cfgpath.parent/'identity-evidence.json'
with p.open('x')as f:json.dump(e,f,indent=2)
p.chmod(0o600);cfg['identityEvidenceFile']=str(p)
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(json.dumps({'explicit_identity_statements_verified':alln,'clone_tests':len(auto_cols),'evidence_written':str(p)}))
