"""Authored supplier-key contract. No ERP, database or identity verification."""
import json,hashlib,sys
from pathlib import Path
from datetime import datetime,timezone
ROOT=Path(__file__).resolve().parent
FIELDS=('instance','company','local_id')
def text(value):
    if not isinstance(value,str) or not value or value.strip()!=value:raise ValueError('invalid_identifier')
    return value
def key(row):
    if not isinstance(row,dict):raise ValueError('invalid_record')
    return tuple(text(row.get(x)) for x in FIELDS)
def resolve(requests,associations):
    keys=[key(row) for row in requests]
    if len(set(keys))!=len(keys):raise ValueError('duplicate_request_key')
    index={}
    for row in associations:index.setdefault(key(row),[]).append(text(row.get('group_id')))
    result=[];counts=dict(assigned=0,unmapped=0,ambiguous=0)
    for k in keys:
        targets=index.get(k,[])
        state='unmapped' if not targets else 'assigned' if len(targets)==1 else 'ambiguous'
        counts[state]+=1
        result.append(dict(key=list(k),status=state,group_id=targets[0] if state=='assigned' else None,association_rows=len(targets),observed_targets=sorted(set(targets))))
    return dict(counts=counts,records=result)
def boundaries():
    count=0;r=dict(instance='erp-a',company='north',local_id='00042');m=dict(r,group_id='g1')
    def check(test):
        nonlocal count
        assert test;count+=1
    def reject(fn):
        nonlocal count
        try:fn()
        except ValueError:count+=1
        else:raise AssertionError('invalid input accepted')
    for row in [dict(r,local_id=42),dict(company='north',local_id='00042'),dict(r,company=''),dict(r,local_id=' 00042')]:reject(lambda row=row:key(row))
    reject(lambda:resolve([r,r],[m]))
    check(resolve([r],[m,m])['records'][0]['status']=='ambiguous')
    a=dict(instance='a|b',company='c',local_id='d');b=dict(instance='a',company='b|c',local_id='d')
    check('|'.join(key(a))=='|'.join(key(b)) and key(a)!=key(b))
    check(resolve([r,dict(r,instance='ERP-A')],[m])['records'][1]['status']=='unmapped')
    check(key(r)!=key(dict(r,local_id='42')))
    reject(lambda:resolve([r],[dict(m,group_id='')]))
    return count
if __name__=='__main__':
    f=json.loads((ROOT/'fixture.json').read_text());outputs=[]
    for scenario in f['scenarios']:
        result=resolve(f['requests'],scenario['associations'])
        assert result['counts']==scenario['expected_counts']
        assert [r['group_id'] for r in result['records']]==scenario['expected_targets']
        reversed_result=resolve(list(reversed(f['requests'])),scenario['associations'])
        assert sorted(result['records'],key=lambda x:x['key'])==sorted(reversed_result['records'],key=lambda x:x['key'])
        outputs.append(dict(name=scenario['name'],**result))
    checks=boundaries()+len(outputs)
    print(json.dumps(dict(author='Anant Mishra',status='executed_synthetic_supplier_key_contract',executed_at_utc=datetime.now(timezone.utc).isoformat(),python_version=sys.version,command='python3 reproduce.py',hashes={n:hashlib.sha256((ROOT/n).read_bytes()).hexdigest() for n in ['fixture.json','reproduce.py']},boundary_checks=checks,results=outputs,limitations='Authored keys and association labels. No supplier identity, ERP integration, persistence, matching service, payments or financial outcome verified.'),indent=2))
