"""Build 46 instrumental carols into native little-endian timed note records.
Times are absolute centiseconds, retaining the source MIDI tempo map.
Each record is (start_cs, end_cs, enhanced_BBC_pitch), 3 signed 32-bit words.
"""
from pathlib import Path
import json,runpy,struct

def build_score(root):
 root=Path(root);original=runpy.run_path(str(root/'SilentNight'))['score']()
 songs=[dict(title='Silent Night',duration_cs=6000,streams=[[[a,b,m] for a,b,p,m in stream] for stream in original],source_url='Original arrangement supplied with Christmas 1.1')]
 songs+=json.loads((root/'ScoreInput').read_text())['songs']
 assert len(songs)==46 and len({s['title'] for s in songs})==46
 records=[]
 for song in songs:
  song['bases']=[];song['counts']=[]
  for stream in song['streams']:
   song['bases'].append(len(records));song['counts'].append(len(stream));at=0
   for a,b,midi in stream:
    assert a==at and b>a and (midi==-1 or 21<=midi<=108)
    pitch=-1 if midi<0 else round(16384+(midi-60)*4096/12)
    records.append((a,b,pitch));at=b
   assert at==song['duration_cs']
 raw=b'X26M'+struct.pack('<III',1,len(songs),len(records))
 raw+=b''.join(struct.pack('<iii',*record) for record in records)
 (root.parent.parent/'!Xmas26'/'Carols').write_bytes(raw)
 (root/'MusicData').write_text(json.dumps({'format':'X26M/1','record_count':len(records),'songs':songs},indent=2)+'\n')
 return songs
