"""Expand the credited source setting into twelve cumulative verses.

TwelveSeed preserves the unmodified imported material and its provenance.
Positions below are source crotchets, not seconds. G major and the changing
4/4, 3/4 and cut-time gift phrases are retained; no recorded audio is used.
"""
from pathlib import Path
from fractions import Fraction as F
import json

def build(root):
    root=Path(root)
    seed=json.loads((root/'TwelveSeed').read_text())
    tempo=seed['track']['tempo'][0][1]; division=384
    def tick(cs): return round(F(cs*10000*division,tempo)/96)*96
    source=[[(tick(a),tick(b),p) for a,b,p in st] for st in seed['song']['streams']]
    cues=[(tick(a),w) for a,w in seed['lyrics']['cues']]
    streams=[[],[],[]]; lyrics=[]; meters=[]; verses=[]; cursor=0
    def meter(n,d,at=None):
        at=cursor if at is None else at
        if not meters or meters[-1][1:]!=[n,d]: meters.append([at,n,d])
    def piece(a,b,words=None):
        nonlocal cursor
        a=round(a*division);b=round(b*division)
        for out,st in zip(streams,source):
            for x,y,p in st:
                if x<b and y>a:out.append([cursor+max(x,a)-a,cursor+min(y,b)-a,p])
        lyrics.extend([cursor+x-a,w] for x,w in (words if words is not None else cues) if a<=x<b)
        cursor+=b-a
    meter(4,4)
    ordinals=['first','second','third','fourth','fifth','sixth','seventh','eighth','ninth','tenth','eleventh','twelfth']
    for day,ordinal in enumerate(ordinals,1):
        start=cursor
        if day==1:
            piece(0,16)
        else:
            meter(4,4,start+division)
            intro=[(x,w) for x,w in cues if 62*division<=x<71*division and x!=63*division]
            syllables={'second':['sec-','ond'],'seventh':['sev-','enth'],'eleventh':['e-','lev-','enth']}.get(ordinal,[ordinal])
            lengths=([192,192] if len(syllables)==2 else [96,96,192] if len(syllables)==3 else [384])
            at=63*division
            for length,word in zip(lengths,syllables):intro.append((at,word));at+=length
            piece(62,71,sorted(intro))
            # Separate lead attacks support the extra ordinal syllables.
            if len(syllables)>1:
                at=start+division; old=next(n for n in streams[0] if n[0]==at)
                idx=streams[0].index(old); notes=[]
                for length in lengths:notes.append([at,at+length,old[2]]);at+=length
                streams[0][idx:idx+1]=notes
            for gift in range(day,5,-1):
                meter(3,4)
                a=71+(12-gift)*3
                piece(a,a+3)
            if day>=5:
                meter(2,2);piece(92,100)
            if day<5:
                # Austin's familiar tune has a different setting before verse 5.
                # All gifts 2-4 use D-A-B-C here, including the repeated gifts.
                # 'French' spans A-B; the later descending phrases begin only
                # when 'five gold rings' first appears, and persist thereafter.
                words={2:[(0,'Two'),(1,'tur-'),(1.5,'tle-'),(2,'doves,')],
                       3:[(0,'Three'),(1,'French'),(2,'hens,')],
                       4:[(0,'Four'),(1,'call-'),(1.5,'ing'),(2,'birds,')]}
                for gift in range(day,1,-1):
                    meter(4 if gift==2 else 3,4)
                    piece(25,28,[(round((25+at)*division),word) for at,word in words[gift]])
                piece(28,36)
            else:
                meter(3,4);piece(100,103)
                meter(3,4);piece(103,106)
                meter(4,4);piece(106,109);piece(109,117)
        verses.append({'day':day,'ordinal':ordinal,'start_tick':start,'end_tick':cursor})
    # Strip the inter-verse breath at the very end, then use the normal 2s tail.
    end=cursor-division//2
    for st in streams:
        st[:]=[[a,min(b,end),p] for a,b,p in st if a<end]
        assert st[0][0]==0 and st[-1][1]==end
        assert all(a[1]==b[0] for a,b in zip(st,st[1:]))
    def cs(t):return round(F(t*tempo,division*10000))
    duration=cs(end)+200
    song={**seed['song'],'streams':[[[cs(a),cs(b),p] for a,b,p in st]+[[cs(end),duration,-1]] for st in streams],
          'duration_cs':duration,'edition':'All twelve cumulative verses, including the early-verse gift melody; expanded in Docs/build/TwelveFull from the credited source phrases.'}
    track={**seed['track'],'meters':meters,'tracks':[{'name':name,'notes':st} for name,st in zip(('melody','bass','harmony'),streams)]}
    lyric={**seed['lyrics'],'cues':sorted([[cs(a),w] for a,w in lyrics if a<end]),
           'line_starts_cs':[cs(v['start_tick']) for v in verses],
           'edition':'All twelve verses. Source editorial directions removed; ordinal syllables and cumulative gift order explicitly aligned.'}
    for name,index,value in [('ScoreInput',21,song),('TrackerInput',22,track),('LyricInput',22,lyric)]:
        data=json.loads((root/name).read_text());data['songs'][index]=value
        (root/name).write_text(json.dumps(data,indent=2)+'\n')
    (root/'TwelveReview').write_text(json.dumps({'division':division,'tempo':tempo,'key':'G major','verses':verses,'end_tick':end,'duration_cs':duration,'meters':meters},indent=2)+'\n')
    print('Twelve Days:',len(verses),'verses,',float(F(end,division)),'quarters,',duration/100,'seconds')

if __name__=='__main__':build(Path(__file__).resolve().parent)
