"""Editorial reduction of the retained D-flat O Holy Night source into 6/8.

One original MIDI quarter pulse becomes one written dotted crotchet.
The sung pitch sequence is taken from OakAcorn's existing vocal reduction.
The two piano lines come from the two retained keyboard tracks.
Score positions in HolySix are semiquavers (twelve per bar).
"""
from pathlib import Path
from fractions import Fraction
from bisect import bisect_right
from collections import defaultdict
import json

START=14                  # first vocal note at source beat 16: one full bar of introduction
END=165                   # end of the retained final chord
BAR_END=166               # allow the final release to breathe for one dotted beat
def build(root):
    root=Path(root)
    def song(name):
        entries=json.loads((root/name).read_text())['songs']
        return next(s for s in entries if s['title']=='O Holy Night')
    t= song('TrackerInput'); app=song('MusicData'); keys=song('MusicKeys'); lyrics=song('LyricInput')
    div=t['division'];usec=t['tempo'][0][1]
    assert div==384 and t['tempo']==[[0,833333]] and all(k[1:]==[-5,0] for k in keys['keys'])
    tracks=t['tracks']; assert len(tracks)==4 and tracks[0]['name'].startswith('women:') and tracks[3]['name'].startswith('men:')
    # The earlier app edit cut 12 quarters and stored rounded centiseconds.
    # At a coalesced note-off take the nominal boundary (not an adjacent
    # grace-note release one source tick before a downbeat).
    lookup=defaultdict(set)
    for track in tracks:
        for a,b,n in track['notes']:
            for tick in (a,b):
                cs=round(Fraction(tick*usec,div*10000))-1000
                lookup[cs].add(tick)
    def original_tick(cs):
        return min(lookup[cs],key=lambda v:(v%(div//16)!=0,abs(Fraction(v*usec,div*10000)-1000-cs)))
    lead=[]
    for a,b,p in app['streams'][0]:
        if a>=app['duration_cs']-200:break
        left=max(START*div,original_tick(a) if a else 12*div)
        right=min(END*div,original_tick(b))
        if right>left:lead.append((left,right,p))
    def reduce(notes,choose):
        bounds=sorted({START*div,END*div}|{t for a,b,n in notes for t in (a,b) if START*div<t<END*div})
        out=[]
        for a,b in zip(bounds,bounds[1:]):
            pitch=choose((n for x,y,n in notes if x<=a<y),default=-1)
            attacked=any(x==a and n==pitch for x,y,n in notes)
            if out and out[-1][2]==pitch and not attacked:out[-1][1]=b
            else:out.append([a,b,pitch])
        return out
    def compound(line):
        phases=defaultdict(set)
        for a,b,_ in line:
            for v in (a,b):phases[v//div].add(v%div)
        def coord(v):
            beat,rem=divmod(v,div)
            # Master uses semiquavers. 0,2,4 are the three written quavers.
            if rem==0:slot=0
            elif rem==128:slot=2
            elif rem==256:slot=4
            elif rem==288:slot=4
            elif rem==192:slot=2 if 288 in phases[beat] else 4
            elif rem==340:slot=5     # measured upper ornament before D-flat
            else:raise ValueError(('unreviewed attack',v,rem))
            return (beat-START)*6+slot
        out=[[coord(a),coord(b),p] for a,b,p in line]
        assert all(a<b for a,b,p in out) and all(a[1]==b[0] for a,b in zip(out,out[1:]))
        assert out[0][0]==0 and out[-1][1]==(END-START)*6
        out.append([(END-START)*6,(BAR_END-START)*6,-1])
        return out,coord
    voice,place=compound(lead)
    right,_=compound(reduce(tracks[1]['notes'],max))
    left,_=compound(reduce(tracks[2]['notes'],min))
    syllables=[];open_word=False
    for cs,word in lyrics['cues']:
        at=place(original_tick(cs))
        assert any(a==at and p>=0 for a,b,p in voice)
        continues=word.endswith('-');text=word.removesuffix('-')
        kind=('middle' if continues else 'end') if open_word else ('begin' if continues else 'single')
        syllables.append([at,kind,text]);open_word=continues
    score=dict(title='O Holy Night',key='D-flat major',fifths=-5,metre=[6,8],subdivisions_per_bar=12,
               dotted_quarter_bpm=72,staves=['Voice','Piano RH','Piano LH'],clefs=['treble','treble','bass'],
               voice=voice,right=right,left=left,lyrics=syllables,source_url=app['source_url'],source_sha256=app['source_sha256'],
               scope='OakAcorn 6/8 score edition based on the retained vocal and piano data. Original app playback is a separate performance.')
    (root/'HolySix').write_text(json.dumps(score,separators=(',',':'),ensure_ascii=True)+'\n')
    return score
if __name__=='__main__': build(Path(__file__).resolve().parent)
