#!/usr/bin/env python3
"""Replacement Bells data, independently entered from Leontovych's score.

No former Wilhousky/Bloomfield Bells note, harmony or lyric data is read.
The melody below was checked against A1's public-domain engraving, pages
1-2, measures 1-37. Repeat: 1, 2..33, 2..32, 34..37. The tenor's closing
motif is carried by the instrumental melody in bars 34-36. Accompaniment
and English festive words are new project work. See Licences/Shchedryk.
"""
from pathlib import Path
import hashlib,json

TITLE='Carol of the Bells'
SOURCE='https://commons.wikimedia.org/wiki/File:%D0%A9%D0%B5%D0%B4%D1%80%D0%B8%D0%BA.pdf'
TEMPO=352941
DIVISION=384
# (MIDI pitch, eighth-note units); each printed measure contains six units.
MOTIF=[(70,2),(69,1),(70,1),(67,2)]
UPPER=[(74,2),(72,1),(74,1),(70,2)]
MEASURES={i:list(MOTIF) for i in range(1,38)}
MEASURES.update({i:list(UPPER) for i in range(17,21)})
MEASURES.update({
 21:[(79,2),(79,1),(79,1),(77,1),(75,1)],
 22:[(74,2),(74,1),(74,1),(72,1),(70,1)],
 23:[(72,2),(72,1),(72,1),(74,1),(72,1)],
 24:[(67,2),(67,1),(67,1),(67,2)],
 25:[(62,1),(64,1),(66,1),(67,1),(69,1),(70,1)],
 26:[(72,1),(74,1),(72,2),(70,2)],
 27:[(62,1),(64,1),(66,1),(67,1),(69,1),(70,1)],
 28:[(72,1),(74,1),(72,2),(70,2)],
})
ORDER=[1]+list(range(2,34))+list(range(2,33))+[34,35,36,37]
# New broken-chord accompaniment, deliberately not a reduction of the
# removed SATB source. Cadences and register follow this instrumental form.
CHORDS={
 'g':(43,58,62),'eb':(39,55,58),'bb':(46,62,65),
 'c':(48,63,67),'d':(38,54,57),'f':(41,57,60),
}
CYCLE=['g','eb','bb','d','g','c','eb','d']
VERSE=['Snow is a- glow,','Lights in a row,','Soft on the street,',
       'Hear win- ter feet.','Stars in the sky,','Clouds sail- ing by,',
       'Warm in- side here,','Christ- mas is near.']
SPECIAL={21:'Hear all the bells ring,',22:'High in the still air,',
 23:'Come share a warm fire,',24:'Peace for us all.',
 25:'May all our win- ter nights',26:'glow soft and bright.',
 27:'Let ev- ery heart come home',28:'safe here to- night.',
 34:'Peace, warmth, joy, home.',35:'Warm in- side here,',
 36:'Christ- mas is near.',37:'Love to you all.'}

def build(root):
 root=Path(root)
 assert len(ORDER)==68 and all(sum(d for n,d in bar)==6 for bar in MEASURES.values())
 parts=[[],[],[]];cues=[];line_starts=[];measure_map=[]
 for position,printed in enumerate(ORDER):
  bar=MEASURES[printed];start=position*6;at=start
  words=SPECIAL.get(printed,VERSE[(printed-1)%8]).split()
  assert len(words)==len(bar),(printed,words,bar)
  line_starts.append(round(start*TEMPO/20000))
  for (pitch,units),word in zip(bar,words):
   parts[0].append((at,at+units,pitch))
   cues.append([round(at*TEMPO/20000),word]);at+=units
  label=CYCLE[position%8]
  if printed in (25,27):label='d'
  if printed in (26,28):label='g'
  if printed>=34:label='g'
  bass,third,fifth=CHORDS[label]
  parts[1].append((start,start+6,bass))
  for offset,pitch in enumerate((third,fifth,third+12)):
   parts[2].append((start+offset*2,start+offset*2+2,pitch))
  measure_map.append(dict(printed_measure=printed,start_cs=line_starts[-1],
                          start_tick=start*192,accompaniment=label))
 end=round(len(ORDER)*6*TEMPO/20000);duration=end+200
 streams=[[[round(a*TEMPO/20000),round(b*TEMPO/20000),n] for a,b,n in part]+[[end,duration,-1]] for part in parts]
 canonical=dict(title=TITLE,melody_source=SOURCE,printed_measure_order=ORDER,
                eighth_units_per_bar=6,tempo_us_per_quarter=TEMPO,parts=parts,
                cues=cues,description='Leontovych melody; new project accompaniment and English words')
 digest=hashlib.sha256(json.dumps(canonical,sort_keys=True,separators=(',',':')).encode()).hexdigest()
 score=dict(title=TITLE,duration_cs=duration,streams=streams,source_url=SOURCE,
            source_sha256=digest,source_hash_kind='SHA-256 of canonical project arrangement data',
            source_tempo_map=[[0,TEMPO]],source_ticks_per_quarter=DIVISION)
 tracker=dict(title=TITLE,source_sha256=digest,division=DIVISION,
              tempo=[[0,TEMPO]],meters=[[0,3,4]],
              tracks=[dict(name=name,notes=[[a*192,b*192,n] for a,b,n in part])
                      for name,part in zip(('Melody','Original bass','Original broken chords'),parts)])
 lyric=dict(title=TITLE,cues=cues,line_starts_cs=line_starts,
            source='Original festive English words by OakAcorn Software, revised for the independently entered Leontovych melody in v2.28',
            timing_note='Every syllable starts on its explicitly mapped melody note; printed repeat unfolded in full.')
 key=dict(title=TITLE,source_url=SOURCE,metadata_url=SOURCE,source_sha256=digest,
          division=DIVISION,keys=[[0,-2,1]])
 for filename,new in [('ScoreInput',score),('TrackerInput',tracker),('LyricInput',lyric),('MusicKeys',key)]:
  p=root/filename;data=json.loads(p.read_text());i=next(i for i,s in enumerate(data['songs']) if s['title']==TITLE)
  data['songs'][i]=new;p.write_text(json.dumps(data,indent=2)+'\n')
 p=root/'RhythmSources';data=json.loads(p.read_text());i=next(i for i,s in enumerate(data['songs']) if s['title']==TITLE)
 data['songs'][i]=dict(title=TITLE,pickup_beats=0,source_url=SOURCE,
                      source_sha256=digest,partial='none; independently entered 3/4 score')
 p.write_text(json.dumps(data,indent=2)+'\n')
 (root/'BellsPhrases').write_text(json.dumps(dict(source=SOURCE,arrangement_sha256=digest,
                    measures=measure_map,syllables=len(cues),duration_cs=duration),indent=2)+'\n')
 return score

if __name__=='__main__':
 s=build(Path(__file__).resolve().parent)
 print(s['title'],s['duration_cs']/100,'seconds; independent Leontovych arrangement')
