"""Online FIFO batching with an unknown horizon of two to five consecutive arrivals."""
from functools import lru_cache
from itertools import product
import json
from glouton23 import compare
from dispersion21 import scan,primes_to

def game(delay,known=None):
    alphabet=(1,2,6);cap=known or 5;minimum=known or 2
    oracle={s:compare(s,delay)['opt'] for n in range(minimum,cap+1) for s in product(alphabet,repeat=n)}
    policy={}
    def finish(prefix,i):
        return max(prefix[i:],default=0)-oracle[prefix]
    @lru_cache(None)
    def value(prefix,i):
        if len(prefix)==cap:return finish(prefix,i)
        if len(prefix)<i+delay+1:
            outcomes=[value(prefix+(z,),i) for z in alphabet]
            if len(prefix)>=minimum:outcomes.append(finish(prefix,i))
            return max(outcomes)
        cost,k=min((max(prefix[i:j])+value(prefix,j),j) for j in range(i+1,len(prefix)+1))
        policy[prefix,i]=k
        return cost
    worst=value((),0);by_length=[];first=None
    for n in range(minimum,cap+1):
        regrets=[]
        for seq in product(alphabet,repeat=n):
            i=total=0;cuts=[]
            while i<n:
                count=i+delay+1
                if n<count or count>=cap:j=n
                else:j=policy[seq[:count],i]
                total+=max(seq[i:j]);cuts.append(j);i=j
            gap=total-oracle[seq];regrets.append(gap)
            if gap==worst and first is None:first=dict(stream=seq,cuts=cuts,cost=total,offline=oracle[seq])
        by_length.append(dict(n=n,worst=max(regrets),positive=sum(v>0 for v in regrets),total=len(regrets)))
    assert max(r['worst'] for r in by_length)==worst
    if known is None:
        for row in by_length:row['announced']=game(delay,row['n'])['worst']
        offsets={cost:next(k for k in range(1,70) if scan([k])['blocks']==cost) for cost in alphabet}
        ids=[offsets[z] for z in first['stream']];sieve=primes_to(39000)
        first['offsets']=ids;first['primes']=[sieve[3999+k] for k in ids]
        for i,j in zip([0]+first['cuts'],first['cuts']):
            req=sorted(set(ids[i:j]));got=scan(req)
            assert got['blocks']==max(first['stream'][i:j]) and got['primes']==[sieve[3999+k] for k in req]
    return dict(delay=delay,worst=worst,by_length=by_length,first=first)
if __name__=='__main__':print(json.dumps([game(1),game(2)]))
