"""Finite fictional session allocations, not measured productivity costs."""
from itertools import permutations, product
import json

TASKS={'A':60,'B':30}


def evaluate(blocks,setup=10,switch=5):
    if any(isinstance(v,bool) or not isinstance(v,int) or v<0 for v in [setup,switch]):
        raise ValueError('Overhead must be nonnegative integer minutes')
    completed={key:0 for key in TASKS};details=[]
    for block in blocks:
        capacity=block['capacity']
        if not isinstance(capacity,int) or capacity<=0:raise ValueError('Invalid block capacity')
        seen=set();cursor=0;segments=[]
        for task,minutes in block['visits']:
            if task not in TASKS:raise ValueError('Unknown task')
            if task in seen:raise ValueError('One visit per task in a block is the declared model')
            if not isinstance(minutes,int) or minutes<=0:raise ValueError('Invalid work amount')
            if task=='A' and minutes%15:raise ValueError('A uses declared 15-minute work chunks')
            if task=='B' and minutes!=30:raise ValueError('B is indivisible in this model')
            if seen and switch:
                segments.append({'kind':'switch','task':task,'start':cursor,'end':cursor+switch});cursor+=switch
            if setup:
                segments.append({'kind':'setup','task':task,'start':cursor,'end':cursor+setup});cursor+=setup
            segments.append({'kind':'work','task':task,'start':cursor,'end':cursor+minutes});cursor+=minutes
            seen.add(task);completed[task]+=minutes
        if cursor>capacity:raise ValueError('Block over capacity including overhead')
        details.append({'id':block['id'],'capacity':capacity,'spent':cursor,'unused':capacity-cursor,'segments':segments})
    if any(completed[k]>TASKS[k] for k in TASKS):raise ValueError('Work counted beyond the defined task')
    totals={kind:sum(s['end']-s['start'] for b in details for s in b['segments'] if s['kind']==kind) for kind in ['work','setup','switch']}
    capacity=sum(b['capacity'] for b in details);spent=sum(b['spent'] for b in details)
    assert spent==sum(totals.values())
    return {'blocks':details,'overhead_policy':{'setup_per_visit':setup,'switch_within_block':switch},'capacity':capacity,'core_work':totals['work'],'setup':totals['setup'],'switch':totals['switch'],'spent':spent,'unused':capacity-spent,
            'completed_work':completed,'remaining_work':{k:TASKS[k]-completed[k] for k in TASKS},'all_tasks_complete':completed==TASKS}


def options(capacity):
    result=[]
    for a,b in product([0,15,30,45,60],[0,30]):
        visits=([('A',a)] if a else [])+([('B',b)] if b else [])
        for order in permutations(visits):
            block={'id':'slot','capacity':capacity,'visits':list(order)}
            try:evaluate([block])
            except ValueError:continue
            result.append(block)
    return result


def exhaustive(capacities):
    tested=valid=complete=0
    for candidate in product(*(options(capacity) for capacity in capacities)):
        tested+=1
        try:r=evaluate(candidate)
        except ValueError:continue
        valid+=1;complete+=r['all_tasks_complete']
    return {'capacities':capacities,'candidate_allocations':tested,'valid_allocations':valid,'full_completion_allocations':complete,
            'scope':'Declared 15-minute A chunks, B indivisible, once per task per block, setup10 per visit and switch5 inside a block only.'}


def block(identity,capacity,*visits):return {'id':identity,'capacity':capacity,'visits':list(visits)}


def run():
    long=evaluate([block('one_120',120,('A',60),('B',30))])
    draft_only=evaluate([block('first_60',60,('A',30)),block('second_60',60,('A',30))])
    reduced=evaluate([block('first_60',60,('A',30)),block('second_60',60,('B',30))])
    counterfactual=evaluate([block('first_60',60,('A',60)),block('second_60',60,('B',30))],setup=0,switch=0)
    assert (long['core_work'],long['setup'],long['switch'],long['spent'],long['unused'])==(90,20,5,115,5)
    assert long['all_tasks_complete']
    assert (draft_only['spent'],draft_only['unused'],draft_only['remaining_work'])==(80,40,{'A':0,'B':30})
    assert (reduced['spent'],reduced['unused'],reduced['remaining_work'])==(80,40,{'A':30,'B':0})
    assert counterfactual['all_tasks_complete'] and counterfactual['spent']==90
    searches=[exhaustive([120]),exhaustive([60,60])]
    assert searches[0]['full_completion_allocations']==2
    assert searches[1]['candidate_allocations']==25 and searches[1]['full_completion_allocations']==0
    # Independent analytical lower bound: A needs >=2 visits in 60-minute
    # blocks, B needs 1; >=3 visits across 2 blocks force >=1 within-block switch.
    lower_bound=90+3*10+5
    assert lower_bound==125>120
    rejected=[]
    tests=[('over_capacity',[block('bad',60,('A',60))]),('over_completed',[block('bad',120,('A',75))]),
           ('invalid_chunk',[block('bad',60,('A',10))]),('split_indivisible_B',[block('bad',60,('B',15))]),
           ('unknown_task',[block('bad',60,('C',15))]),('negative_work',[block('bad',60,('A',-15))]),
           ('repeat_context_in_block',[block('bad',120,('A',15),('A',15))])]
    for name,blocks in tests:
        try:evaluate(blocks)
        except ValueError as error:rejected.append({'case':name,'result':'rejected_as_expected','reason':str(error)})
        else:raise AssertionError('Invalid plan accepted: '+name)
    return {'scope':'Generated independent A/B tasks, no external deadlines. Core requirements A60/B30; A divisible in 15-minute chunks, B30 indivisible. Setup10 per task visit; switch5 between different tasks inside a block. None are observed or recommended universal durations.',
            'cases':{'one_long_block':long,'two_blocks_draft_only':draft_only,'two_blocks_smaller_A_action_and_B':reduced,'counterfactual_zero_overhead':counterfactual},
            'searches':searches,'two_short_blocks_completion_lower_bound':lower_bound,
            'lower_bound_limit':'125 is a necessary lower bound for full completion under these rules, not a feasible 125-minute schedule or general scheduling theorem.',
            'invalid_plans':rejected}


if __name__=='__main__':print(json.dumps(run(),ensure_ascii=False,indent=2))
