"""Exact finite enumeration of assignments + unary-resource orders for M1–M6.
No external sources or libraries. Every feasible schedule induces one such order.
For a fixed order, earliest calendar-feasible topological placement dominates any
later placement, since all links are minimum finish-to-start and durations fixed.
"""
from itertools import product, permutations
from pathlib import Path
import json, time
ROOT=Path(__file__).parent
DUR={'A':3,'B':4,'C':3,'D':5,'E':4,'F':3,'G':4,'H':3,'I':2,'J':4,'K':3,'L':2,'M':2,'N':3,'O':1,'P':2,'Q':2,'R':1}
PRED={'A':[],'B':['A'],'C':['A'],'D':['A'],'E':['B'],'F':['C'],'G':['D'],'H':['E'],'I':['F'],'J':['G'],'K':['E','F'],'L':['G'],'M':['H','I','J','K','L'],'N':['E','F'],'O':['N','H','I','J'],'P':['M','O'],'Q':['P'],'R':['Q']}
NAMES={'A':'Common service isolation/renewal','B':'North preparation','C':'South preparation','D':'East preparation','E':'North specialist fit-out','F':'South specialist fit-out','G':'East specialist fit-out','H':'North objects/cases','I':'South objects/cases','J':'East objects/cases','K':'AV/control configuration','L':'Climate commissioning','M':'Integrated case/alarm tests','N':'Interpretation/signage','O':'Accessibility/visitor-route walkthrough','P':'Full integrated operating run','Q':'External acceptance','R':'Staff rehearsal'}
BASE_RES={'A':['Services'],'B':['North preparation'],'C':['South preparation'],'D':['East preparation'],'E':['S0'],'F':['S0'],'G':['S0'],'H':['C0'],'I':['C0'],'J':['C0'],'K':['T'],'L':['T'],'M':['C0','T'],'N':['Interpretation'],'O':['Operations'],'P':['C0','T'],'Q':['Acceptance'],'R':['Operations']}
OFFERS={'X':7,'S':18,'C':12,'T':6,'V':4}
SLOTS=[27,34,41]
PERMS3=list(permutations('EFG'));PERMSC=list(permutations('HIJ'));PERMST=list(permutations('KL'))
def avail(r,t,offers):
 if r=='S0': return 0<=t<=47 and t not in (12,13)
 if r=='S1': return 'S' in offers and 8<=t<=16
 if r=='C0': return 0<=t<=47 and t not in (15,24)
 if r=='C1': return 'C' in offers and 14<=t<=21
 if r=='T': return 0<=t<=47 and ('T' in offers or t not in (17,18))
 return t>=0

def solve(offers):
 dur=DUR.copy();dur['G']=3 if 'X' in offers else 4;dur['K']=2 if 'V' in offers else 3
 best=None; best_key=None; n=0; feasible=0
 sas=list(product(['S0','S1'] if 'S' in offers else ['S0'],repeat=3))
 cas=list(product(['C0','C1'] if 'C' in offers else ['C0'],repeat=3))
 # Unique local orders rather than duplicate interleavings.
 def orders(assignments, jobs, perms):
  seen=set();res=[]
  for perm in perms:
   seqs=tuple(tuple(j for j in perm if assignments[j]==r) for r in sorted(set(assignments.values())))
   if seqs not in seen: seen.add(seqs);res.append(seqs)
  return res
 for sa,ca in product(sas,cas):
  assigned={**dict(zip('EFG',sa)),**dict(zip('HIJ',ca))}
  res={k:v[:] for k,v in BASE_RES.items()}
  for j,r in assigned.items():res[j]=[r]
  for so,co,to in product(orders(dict(zip('EFG',sa)),'EFG',PERMS3),orders(dict(zip('HIJ',ca)),'HIJ',PERMSC),PERMST):
   n+=1; pred={k:v[:] for k,v in PRED.items()}
   for seq in [*so,*co,to]:
    for a,b in zip(seq,seq[1:]):
     if a not in pred[b]:pred[b].append(a)
   starts={};fin={};pending=list(DUR);ok=True
   while pending and ok:
    ready=[j for j in pending if all(p in fin for p in pred[j])]
    assert ready,'cycle'
    for j in ready:
     release=max((fin[p] for p in pred[j]),default=0)
     if j=='Q':
      slots=[s for s in SLOTS if s>=release]
      if not slots:ok=False;break
      start=slots[0]
     else:
      start=release
      while start<=48 and not all(avail(r,t,offers) for r in res[j] for t in range(start,start+dur[j])):start+=1
      if start>48:ok=False;break
     starts[j]=start;fin[j]=start+dur[j];pending.remove(j)
   if not ok:continue
   feasible+=1
   key=(fin['P'],fin['R'],sum(starts.values()),tuple(starts[j] for j in DUR),tuple(assigned.values()))
   if best_key is None or key<best_key:
    best_key=key;best={'starts':starts,'finishes':fin,'resources':res,'durations':dur,'resource_orders':[list(x) for x in [*so,*co,to]],'P_finish':fin['P'],'Q_start':starts['Q'],'opening':fin['R'],'margin':starts['Q']-fin['P']}
 result={'codes':''.join(offers),'cost':sum(OFFERS[x] for x in offers),'orders_examined':n,'feasible_orders':feasible,'schedule':best}
 if best:result.update({'holding_cost':max(0,best['opening']-30)*2,'total_cost':sum(OFFERS[x] for x in offers)+max(0,best['opening']-30)*2})
 return result

def validate(option):
 sc=option['schedule']; offers=option['codes']; errs=[]
 if not sc:return ['No feasible slot']
 s=sc['starts']; f=sc['finishes']; r=sc['resources'];d=sc['durations']
 if s['A']!=0:errs.append('A start')
 for j in DUR:
  if f[j]!=s[j]+d[j]:errs.append(j+' duration')
  if any(s[j]<f[p] for p in PRED[j]):errs.append(j+' predecessor')
  if not all(avail(x,t,offers) for x in r[j] for t in range(s[j],f[j])):errs.append(j+' calendar')
  for k in DUR:
   if j<k and set(r[j])&set(r[k]) and max(s[j],s[k])<min(f[j],f[k]):errs.append(j+'/'+k+' overlap')
 if s['Q']not in SLOTS:errs.append('Q slot')
 return errs

if __name__=='__main__':
 t=time.monotonic();options=[]
 for bits in product([False,True],repeat=5):
  codes=[c for c,b in zip(OFFERS,bits) if b];o=solve(codes);err=validate(o)
  assert not err,(codes,err)
  options.append(o);print(o['codes'] or 'None',o['cost'],o['schedule']['P_finish'],o['schedule']['Q_start'],o['schedule']['opening'],flush=True)
 data={'activity_names':NAMES,'predecessors':PRED,'base_durations':DUR,'offers':OFFERS,'options':options,'method':'Exhaustive assignments and resource orders; earliest calendar-feasible placement for each order; minimize P finish, then total start boundaries.','elapsed_seconds':time.monotonic()-t,'validation':'All 32 retained schedules independently checked for calendars, durations, precedence, fixed Q slots and resource non-overlap.'}
 (ROOT/'schedules.json').write_text(json.dumps(data,indent=2)+'\n')
 print('elapsed',data['elapsed_seconds'])
