import subprocess,json,time,hashlib,shutil,os,sys
B='/downloads/anan2090/impossible/';BK='/downloads/anan2090/sky-site-backup/impossible/'
ALL="bigint,modinv,factor,fraction,isqrt,toposort,illposed,unitfrac,weekday,missing"
def sha(p):return hashlib.sha256(open(p,'rb').read()).hexdigest()
def log(r):open(B+'ops_log.jsonl','a').write(json.dumps(r,ensure_ascii=False)+'\n')
def runc(path,c,n):
    t=time.time();o=subprocess.run(['python3',path,str(n),str(c),ALL],capture_output=True,text=True,timeout=110);j=json.loads(o.stdout)
    F=j['families'];ok=sum(v['after_ok']+v['after_abstain_ok'] for v in F.values());bad=sum(v['after_bad'] for v in F.values());un=sum(v['after_unsolved'] for v in F.values())
    return {'cycle':c,'n':n,'set_sha256':j['set_sha256'],'ok_or_abstain_ok':ok,'bad':bad,'unsolved':un,'sec':round(time.time()-t,2),'unsolved_by_family':{k:v['after_unsolved'] for k,v in F.items() if v['after_unsolved']}}
prev=B+'factory.py';ref_hash=None
for c,n in ((1,10000),(2,2000)):
    r=runc(prev,c,n);r['factory_sha']=sha(prev);r['ts']=time.strftime('%Y-%m-%dT%H:%M:%S%z')
    # verify new vs previous: same inputs must give same set hash and same counts
    ok_gate=r['bad']==0
    r['decision']='ACCEPT' if ok_gate else 'ROLLBACK'
    if ok_gate:
        os.makedirs(B+'primary',exist_ok=True);os.makedirs(BK,exist_ok=True)
        shutil.copy(prev,B+'primary/factory.py');shutil.copy(prev,BK+'factory.py')
        r['primary_sha']=sha(B+'primary/factory.py');r['backup_sha']=sha(BK+'factory.py')
    log(r);print(json.dumps(r,ensure_ascii=False))
# restore test: destroy primary copy, restore from backup, re-run cycle 1, compare to logged cycle 1
t0=time.time();os.remove(B+'primary/factory.py');shutil.copy(BK+'factory.py',B+'primary/factory.py')
rs=runc(B+'primary/factory.py',1,10000);first=[json.loads(l) for l in open(B+'ops_log.jsonl')][0]
same=(rs['set_sha256']==first['set_sha256'] and rs['ok_or_abstain_ok']==first['ok_or_abstain_ok'] and rs['bad']==first['bad'] and rs['unsolved']==first['unsolved'] and sha(B+'primary/factory.py')==first['backup_sha'])
rr={'event':'restore_test','restore_and_rerun_sec':round(time.time()-t0,2),'identical_to_cycle1':same,'ts':time.strftime('%Y-%m-%dT%H:%M:%S%z')}
log(rr);print(json.dumps(rr))
