import csv,hashlib,json,pathlib,re,sys
from datetime import datetime
manifest,out=map(pathlib.Path,sys.argv[1:3]);manifest_bytes=manifest.read_bytes();entries=json.loads(manifest_bytes)
if not isinstance(entries,list) or not 1<=len(entries)<=10:raise ValueError('Select 1–10 recorded profile requests')
ACTION='wechat_mp.v2.fetch_account_profile'
rows,sources,seen,requests=[],[],set(),set()
def valid_id(value):return isinstance(value,str) and len(value)<=80 and re.fullmatch(r'[0-9A-Za-z][-_0-9A-Za-z]{1,63}(@[0-9A-Za-z]{1,16})?',value)
def safe(value):
if value is None:return ''
value=str(value)
return "'"+value if value.startswith(('=','+','-','@','\t','\r','\n')) else value
for i,e in enumerate(entries,1):
params=e.get('params');requested=params.get('username') if isinstance(params,dict) else None
if e.get('action')!=ACTION or not isinstance(params,dict) or set(params)!={'username','raw'} or params['raw'] is not False or not valid_id(requested):raise ValueError('Use explicit simplified profile and valid username')
if type(e.get('http_status')) is not int or e['http_status']!=200:raise ValueError('Resolve failed profiles separately; do not silently omit an account')
collected=e.get('collected_at')
if not isinstance(collected,str) or datetime.fromisoformat(collected.replace('Z','+00:00')).tzinfo is None:raise ValueError('Record collection time with timezone')
raw=(manifest.parent/e['response_file']).read_bytes();body=json.loads(raw);data=body.get('data')
if body.get('action')!=ACTION or body.get('status')!='succeeded' or body.get('error') is not None or not isinstance(data,dict):raise ValueError('Invalid successful profile envelope')
rid=body.get('request_id')
if not isinstance(rid,str) or not rid.strip() or rid in requests:raise ValueError('Missing or duplicate request ID')
requests.add(rid);returned=data.get('user_name')
if not valid_id(returned):raise ValueError('Missing returned account identity')
if requested.startswith('gh_') and returned!=requested:raise ValueError('Canonical identity mismatch; do not normalize @app')
if returned in seen:raise ValueError('Repeated canonical account; select one observation')
seen.add(returned)
unavailable=data.get('unavailable',[])
if not isinstance(unavailable,list) or any(not isinstance(x,str) for x in unavailable):raise ValueError('Invalid unavailable flags')
finder=data.get('finder_username');name=data.get('finder_nickname')
if name is not None and not isinstance(name,str):raise ValueError('Invalid linked display name')
if 'finder_username' in unavailable:state='unavailable' if finder in (None,'') else 'inconsistent_unavailable'
elif 'finder_username' not in data:state='missing'
elif finder is None:state='null'
elif finder=='':state='empty'
elif isinstance(finder,str) and 10<=len(finder)<=256 and re.fullmatch(r'v2_[0-9a-fA-F]+@finder',finder):state='linked_identifier_returned'
else:state='unsupported_identifier'
next_request={'action':'wechat_channels.v2.fetch_user_videos','params':{'username':finder,'raw':False,'last_buffer':''}} if state=='linked_identifier_returned' else None
row={'requested_username':requested,'returned_username':returned,'identity_relation':'exact' if requested==returned else 'alias_returned_by_profile','profile_request_id':rid,'collected_at':collected,'finder_username_raw':json.dumps(finder,ensure_ascii=False),'finder_nickname_raw':json.dumps(name,ensure_ascii=False),'link_state':state,'legal_common_owner_verified':'false','source_index':i}
rows.append(row);sources.append({'row':row,'raw':raw,'next':next_request})
out.mkdir(exist_ok=False)
with (out/'account-links.csv').open('x',encoding='utf-8-sig',newline='') as f:
w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows({k:safe(v) for k,v in r.items()} for r in rows)
evidence=[]
for i,source in enumerate(sources,1):
name='profile-%02d.json'%i;(out/name).write_bytes(source['raw'])
evidence.append({'source_index':i,'filename':name,'sha256':hashlib.sha256(source['raw']).hexdigest(),'request':entries[i-1],'link_state':source['row']['link_state']})
if source['next'] is not None:(out/('unexecuted-videos-%02d.json'%i)).write_text(json.dumps(source['next'],ensure_ascii=False,indent=2),encoding='utf-8')
(out/'manifest.json').write_bytes(manifest_bytes)
(out/'evidence.json').write_text(json.dumps({'sources':evidence,'manifest_sha256':hashlib.sha256(manifest_bytes).hexdigest(),'executed_calls':0,'weekly_monitoring_installed':False,'identity_basis':'recorded profile response; not corporate ownership or independent live verification'},ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps({'accounts':len(rows),'linked_identifiers':sum(r['link_state']=='linked_identifier_returned' for r in rows),'executed_calls':0}))