"""Native Maestro type-2 exporter and score-timed karaoke bank; no runtime Python.
Maestro layout checked against the supplied !RunImage's own load/save routines.
In particular: instrument channel IDs are 0..7, tempo payload is ONE byte,
and time-signature beats are encoded as beats-1 (older PRM tables differ).
"""
from pathlib import Path
import json,struct,math,re,collections
ROOT=Path(__file__).resolve().parent
def pages(cues,end,line_starts=()):
 # A MIDI syllable marked '-' joins the next syllable to form one displayed word.
 words=[];word='';syl=[]
 for at,text in cues:
  text=text.strip().strip('"')
  if not text:continue
  join=text.endswith('-');part=text[:-1] if join else text
  syl.append((at,len(word),len(word)+len(part)));word+=part
  if not join:words.append((word,syl));word='';syl=[]
 if word:words.append((word,syl))
 # Roll by ONE line at its first syllable. The singing line is always on top,
 # with the next complete line below; score onsets and durations are unchanged.
 lines=[];line='';syllables=[];out=[]
 for word,syl in words:
  if line and (syl[0][0] in line_starts or len(line)+1+len(word)>30):
   lines.append((line,syllables));line='';syllables=[]
  offset=len(line)+(1 if line else 0)
  line+=(' ' if line else '')+word
  for at,lo,hi in syl:syllables.append((at,offset+lo,offset+hi))
  # Phrase punctuation is a sung line boundary, including in the medley.
  # Flush only after a complete assembled word: its syllables never wrap.
  if word.rstrip('\"\'').endswith((',', ';')):
   lines.append((line,syllables));line='';syllables=[]
 if line:lines.append((line,syllables))
 for i,(line,syllables) in enumerate(lines):
  following=lines[i+1][0] if i+1<len(lines) else ''
  for at,lo,hi in syllables:out.append([at,0,lo,hi,line,following])
 out.sort(key=lambda c:c[0]);out=[c for c in out if c[0]<end]
 for i,c in enumerate(out):c[1]=out[i+1][0] if i+1<len(out) else end
 return out

def build(root=ROOT):
 songs=json.loads((root/'MusicData').read_text())['songs'];lyrics=json.loads((root/'LyricInput').read_text())['songs']
 import runpy
 runpy.run_path(str(root/'Engrave'))['build'](root)
 styles=[]
 for s in songs:
  tm=s.get('source_tempo_map',[[0,800000]]);division=s.get('source_ticks_per_quarter',384);tempo_cs=[];elapsed=0
  for j,(tick,tempo) in enumerate(tm):
   if j:elapsed+=(tick-tm[j-1][0])*tm[j-1][1]/division/10000
   tempo_cs.append((round(elapsed),tempo/10000))
  for stream in s['streams']:
   for a,b,n in stream:
    quarter=next(q for t,q in reversed(tempo_cs) if t<=a);beats=(b-a)/quarter
    kind,dots=min(((k,d) for k in range(8) for d in range(2)),key=lambda kd:abs(beats-8/2**kd[0]*(1.5 if kd[1] else 1)))
    styles.append((1 if kind<=2 else 0)|(2 if kind<=1 else 0)|(max(0,kind-3)<<2)|(dots<<5))
 (root.parent.parent/'!Xmas26/NoteView').write_bytes(b'X26N'+struct.pack('<I',len(styles))+bytes(styles))
 tables=[]
 for s,l in zip(songs,lyrics):
  tables.append(pages(l['cues'],s['duration_cs']-(240 if s['title']=='Silent Night' else 200),l.get('line_starts_cs',())))
 # Tracker lyrics are retimed to actual lead row positions, not wall-clock guesses.
 arr=json.loads((root/'TrackerData').read_text());med=[];titles=[]
 for sec in arr['sections']:
  name=sec['title'];row=sec['row'];length=sec['rows'];titles.append([row,name])
  match=next((i for i,s in enumerate(songs) if name==s['title'] or name.startswith(s['title']+' -')),None)
  if match is None or name.startswith('Frostlight'):continue
  cues=lyrics[match]['cues'];quarter=songs[match].get('source_tempo_map',[[0,800000]])[0][1]/10000
  if name.startswith('Jingle Bells'):
   jingle=runpy.run_path(str(root/'JingleMake'))
   chorus=jingle['read'](root)['chorus']
   words=[w if w!='~' else 'Hey!' for bar in chorus for _,_,w in jingle['bar_notes'](bar)]
   rr=arr['jingle_lead_rows'];assert len(words)==len(rr),(len(words),len(rr));cues=[[r,w] for r,w in zip(rr,words)];quarter=4
  for t,w in cues:
   r=round(t/quarter*4)
   if r<length:med.append([round((row+r)*11.71875),w])
 # Rolling lyric lines cannot straddle song/bridge boundaries.
 medtable=[]
 for j,(row,name) in enumerate(titles):
  a=round(row*11.71875);b=round((titles[j+1][0] if j+1<len(titles) else arr['rows'])*11.71875)
  medtable+=pages([[t,w] for t,w in med if a<=t<b],b)
 tables.append(medtable)
 records=[];headers=[]
 for table in tables:headers.append((len(records),len(table)));records+=table
 data=b'X26L'+struct.pack('<II',1,len(tables))+b''.join(struct.pack('<II',*h) for h in headers)
 for a,b,lo,hi,l1,l2 in records:
  assert 0<=lo<hi<=len(l1)<=30 and len(l2)<=30,(a,lo,hi,l1,l2)
  data+=struct.pack('<4I',a,b,lo,hi)+(l1+'\r').encode().ljust(32,b'\0')+(l2+'\r').encode().ljust(32,b'\0')
 (root.parent.parent/'!Xmas26/Lyrics').write_bytes(data)
 (root/'LyricTiming').write_text(json.dumps({'record_size':80,'tables':tables},indent=2)+'\n')
 return len(records)
if __name__=='__main__':print(build(),'lyric syllable cues; 92 Maestro scores in two sets')
