"""A certified five-item online batching game via best responses on the observation tree."""
from fractions import Fraction as F
from itertools import product
from scipy.optimize import linprog
from hasard27 import schedules
from glouton23 import compare
import json
def game(prefix,horizon=5):
    streams=[(*prefix,*z) for z in product((1,2,6),repeat=horizon-len(prefix))]
    opt=[compare(s,1)['opt'] for s in streams]
    assert opt==[min(c for _,c in schedules(s)) for s in streams]
    def best(q):
        def visit(ids,i):
            n=horizon-i
            if n<=2:return {k:max(streams[k][i:]) for k in ids},{}
            options=[]
            for action in (1,2):
                children={};j=i+action
                for k in ids:children.setdefault(streams[k][:min(horizon,j+2)],[]).append(k)
                cost={};rule={(i,streams[ids[0]][:i+2]):action}
                for group in children.values():
                    tail,sub=visit(group,j);rule.update(sub)
                    cost.update({k:max(streams[k][i:j])+v for k,v in tail.items()})
                options.append((sum(q[k]*v for k,v in cost.items()),action,cost,rule))
            return min(options,key=lambda z:z[:2])[2:]
        costs,rule=visit(range(len(streams)),0)
        for k,seq in enumerate(streams):
            i=cost=0
            while i<horizon:
                a=rule[i,seq[:i+2]] if i<horizon-2 else horizon-i
                cost+=max(seq[i:i+a]);i+=a
            assert cost==costs[k]
        return tuple(costs[i]-opt[i] for i in range(len(streams))),[[i,p,a] for (i,p),a in sorted(rule.items())]
    first,rule=best([1]*len(streams));rows=[first];rules=[rule]
    def mix(mat):
        n=len(mat);c=[0]*n+[1]
        lp=linprog(c,A_ub=[[ *col,-1] for col in zip(*mat)],b_ub=[0]*len(mat[0]),A_eq=[[1]*n+[0]],b_eq=[1],bounds=[(0,None)]*n+[(None,None)],method='highs')
        assert lp.success
        return [F(float(x)).limit_denominator(100000) for x in lp.x]
    while True:
        *p,v=mix(rows);*q,nv=mix([[-z for z in col] for col in zip(*rows)])
        assert sum(p)==sum(q)==1 and min(p+q)>=0 and v==-nv
        fresh,rule=best(q);lower=sum(x*y for x,y in zip(q,fresh))
        if lower==v:break
        assert lower<v and fresh not in rows;rows.append(fresh);rules.append(rule)
    scores=[sum(x*y for x,y in zip(p,col)) for col in zip(*rows)]
    assert max(scores)==v
    return dict(prefix=prefix,value=v,rounds=len(rows),streams=streams,weights=q,upper=scores,
                support=[dict(weight=w,payoffs=row,rule=rule) for w,row,rule in zip(p,rows,rules) if w],best_response=fresh)
def study():
    games=[game(p) for p in product((1,2,6),repeat=2)]
    return dict(value=max(g['value'] for g in games),games=games)
if __name__=='__main__':print(json.dumps(study(),default=str))
