"""Public-domain Silent Night melody, transposed to C; original simple accompaniment.
Durations below are eighth-note units in a 3/4 respelling (24 bars).
One unit is 40 centiseconds: quarter note = 75 BPM.
The complete verse is 144 units / 57.6 seconds, followed by a 2.4 second rest.
Pitch reference: MIDI 60 (middle C) -> RISC OS enhanced pitch &4000.
"""
import json, math
from pathlib import Path
MELODY=[
 [(67,3),(69,1),(67,2),(64,6)],
 [(67,3),(69,1),(67,2),(64,6)],
 [(74,4),(74,2),(71,6)],
 [(72,4),(72,2),(67,6)],
 [(69,4),(69,2),(72,3),(71,1),(69,2)],
 [(67,3),(69,1),(67,2),(64,6)],
 [(69,4),(69,2),(72,3),(71,1),(69,2)],
 [(67,3),(69,1),(67,2),(64,6)],
 [(74,4),(74,2),(77,3),(74,1),(71,2)],
 [(72,6),(76,6)],
 [(72,2),(67,2),(64,2),(67,3),(65,1),(62,2)],
 [(60,12)]
]
# Each row above spans two bars in the chosen 3/4 notation.
CHORDS=['C','C','G','C','F','C','F','C','G','C','CG','C']
TRIADS={'C':(48,52,55),'G':(43,47,50),'F':(41,45,48)}
def score():
    assert all(sum(d for p,d in row)==12 for row in MELODY)
    melody=[pair for row in MELODY for pair in row]+[(-1,6)]
    bass=[];arp=[]
    for label in CHORDS:
        for half in range(2):
            chord=label[half] if label=='CG' else label;r,t,f=TRIADS[chord]
            bass.append((r,6))
            arp.extend([(t+12,2),(f+12,2),(t+12,2)])
    bass.append((-1,6));arp.append((-1,6))
    streams=[]
    for stream in (melody,bass,arp):
        events=[];start=0
        for midi,units in stream:
            end=start+units*40;pitch=-1 if midi<0 else round(16384+(midi-60)*4096/12)
            events.append((start,end,pitch,midi));start=end
        assert start==6000
        streams.append(events)
    return streams

def build_score(root):
    streams=score();Path(root,'MusicData').write_text(json.dumps({'unit_centiseconds':40,'quarter_bpm':75,'verse_centiseconds':5760,'cycle_centiseconds':6000,'streams':streams},indent=2)+'\n')
    return streams
