"""Derive the three added instrumental scores from the retained source evidence.
The evidence contains decoded notes and attribution, not upstream lyric bodies.
Run before Score. All score voices are contiguous and retain source attacks.
"""
from pathlib import Path
from fractions import Fraction as F
import json
ROOT=Path(__file__).resolve().parent

def build(root=ROOT):
 root=Path(root);evidence=json.loads((root/'AdditionalSources').read_text())
 data={name:json.loads((root/name).read_text()) for name in ['ScoreInput','TrackerInput','MusicKeys','RhythmSources','LyricInput','SheetText']}
 notes=(root/'ScoreNotes').read_text().splitlines()[:43]
 for name,d in data.items():
  if name=='SheetText':d[:]=d[:43]
  else:d['songs']=d['songs'][:42 if name=='ScoreInput' else 43]
 for s in evidence['songs']:
  title=s['title'];
  for key in ['music','words']:s[key]=s[key].translate(str.maketrans({'’':"'",'‘':"'",'–':'-','—':'-','“':'"','”':'"'}))
  m=s['midi'];div=m['division'];tempo=m['tempos'][0][1]
  end=round(s['score_duration_beats']*div)
  cs=lambda t:round(F(t*tempo,div*10000))
  tracks=m['tracks'];women=tracks[0]['notes'];men=tracks[1]['notes']
  if s['source_title']=='Hymn for Christmas Day':
   men=men+tracks[3]['notes']
   inner=tracks[1]['notes']+tracks[2]['notes']
  else:inner=tracks[1]['notes']
  def envelope(src,high=True):
   bounds=sorted({0,end}|{t for a,b,p in src for t in (a,b) if 0<=t<=end})
   out=[];previous=None
   for a,b in zip(bounds,bounds[1:]):
    active=[(p,x,y) for x,y,p in src if x<=a<y and p>=0]
    picked=(max(active) if high else min(active)) if active else None
    pitch=picked[0] if picked else -1
    if out and picked==previous:out[-1][1]=b
    else:out.append([a,b,pitch])
    previous=picked
   assert out[0][0]==0 and out[-1][1]==end
   return out
  streams=[envelope(women),envelope(men,False),envelope(inner)]
  duration=cs(end)+200
  song=dict(title=title,source_url=s['source_url'],source_sha256=s['source_sha256'],source_ticks_per_quarter=div,source_tempo_map=m['tempos'],duration_cs=duration,
    streams=[[[cs(a),cs(b),p]for a,b,p in st]+[[cs(end),duration,-1]]for st in streams],
    edition='Instrumental reading of credited source. Lyrics are available through the source link; no lyric text is bundled.')
  track=dict(title=title,source_sha256=s['source_sha256'],division=div,tempo=m['tempos'],meters=[[round(at*div),n,d]for at,n,d in s['notation_meters_beats']],
    tracks=[dict(name=name,notes=st)for name,st in zip(['melody','bass','harmony'],streams)])
  keys=[list(k) for k in m['keys']]
  if s['key_mode']=='minor':keys[0][2]=1
  key=dict(title=title,source_url=s['source_url'],metadata_url=s['download_url_used'],source_sha256=s['source_sha256'],division=div,keys=keys)
  rhythm=dict(title=title,pickup_beats=s['pickup_beats'],source_url=s['score_source_url'],source_sha256=s['score_source_sha256'],notation_note='Retained source bar lengths; compound 9/8 and 12/8 reheading for Gabriel preserves every original duration.' if s['key_mode']=='minor' else 'Source metre retained.')
  lyric=dict(title=title,cues=[],source=s['source_url'],instrumental=True,credit=s['words'],timing_note='Instrumental presentation. Lyric text is not bundled; the credited source supplies the words.')
  sheet=dict(title=title,words=s['words'],music=s['music'],stanzas=[],source_url=s['score_source_url'],instrumental=True)
  for name,item in [('ScoreInput',song),('TrackerInput',track),('MusicKeys',key),('RhythmSources',rhythm),('LyricInput',lyric)]:data[name]['songs'].append(item)
  data['SheetText'].append(sheet)
  notes.append('\t'.join([s['key_name'],s['key_mode'],rhythm['notation_note']+' '+s['lead_selection']]))
 for name,d in data.items():(root/name).write_text(json.dumps(d,indent=2,ensure_ascii=True)+'\n')
 (root/'ScoreNotes').write_text('\n'.join(notes)+'\n')
 print('Three instrumental carols added; 46 total; existing 43 titles retained.')
if __name__=='__main__':build()
