"""Build the native plain-text lyric sheets from this edition's words and credits."""
from pathlib import Path
import json, re, textwrap, unicodedata
ROOT=Path(__file__).resolve().parent
COLLECTION='https://acollectionofchristmascarols.com/'
BOOK=COLLECTION+'pdfs/ccc-playbook.pdf'
YOUNG='https://www.hymnsandcarolsofchristmas.com/Hymns_and_Carols/silent_night_holy_night-1.htm'
# Printed pages of the source edition, not PDF indices. Alternate settings
# are matched to the actual MIDI used, e.g. Kirkpatrick, Stainer and Holst.
PAGES=(0,42,0,18,13,14,112,32,52,16,28,39,46,55,22,77,20,106,113,41,96,65,24,182,80,110,73,62,98,56,47,68,48,175,194,173,171,23,114,76,2,67,0,40,158,49)

def letters(s):
    plain=unicodedata.normalize('NFKD',s).casefold()
    return ''.join(c for c in plain if c.isalnum())

def twelve_days():
    ordinals='first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth'.split()
    gifts=['a partridge in a pear tree','two turtledoves','three French hens','four calling birds',
           'five gold rings','six geese a-laying','seven swans a-swimming','eight maids a-milking',
           'nine ladies dancing','ten lords a-leaping','eleven pipers piping','twelve drummers drumming']
    verses=[]
    for day,number in enumerate(ordinals):
        verse=[f'On the {number} day of Christmas','My true love sent to me']
        for i in range(day,-1,-1):
            gift=('and '+gifts[i]) if i==0 and day else gifts[i]
            verse.append(gift[:1].upper()+gift[1:]+('.' if i==0 else ','))
        verses.append(verse)
    return verses

def build(root=ROOT):
    read=lambda name:json.loads((root/name).read_text())
    sheets=read('SheetText'); cues=read('LyricInput')['songs']; music=read('MusicData')['songs'];auld=read('AuldSource')
    assert len(sheets)==len(cues)==len(music)==len(PAGES)==46
    dest=root.parent.parent/'!Xmas26/Words';dest.mkdir(exist_ok=True)
    for n,(sheet,lyric,song,page) in enumerate(zip(sheets,cues,music,PAGES),1):
        assert sheet['title']==lyric['title']==song['title']
        body=sheet['stanzas'] if n!=23 else twelve_days()
        assert all(verse and all(line.strip() for line in verse) for verse in body)
        if n!=23 and not sheet.get('instrumental'):
            source_words=letters(''.join(w for _,w in lyric['cues']))
            sung_words=letters(''.join(line for verse in body for line in verse))
            assert source_words==sung_words,(n,sheet['title'])
        lines=[sheet['title'],'='*len(sheet['title']),'']
        for label,key in [('Words','words'),('Music','music')]:
            lines+=textwrap.wrap(label+': '+sheet[key],width=76,subsequent_indent='  ')
        if n==1:
            lines+=['Source: !Xmas26 project score, first arranged for Christmas 1.1.',
                    'Words: Young translation, aligned in Docs/build/LyricInput.',
                    'Historical text reference:',YOUNG]
        elif n==3:
            lines+=['Source: Shchedryk, independently transcribed from A1\'s engraving.',
                    song['source_url'],'Words source: original !Xmas26 English text in Docs/build/Shchedryk',
                    'and Docs/build/LyricInput.']
        elif n==39:
            tune=read('JingleTune')
            lines+=['Tune: familiar later version of Jingle Bells; historical score:',tune['source'],
                    'Words source: A Collection of Christmas Carols, Benjamin Bloomfield.',
                    tune['lyrics_source'],'App score: OakAcorn Software, Docs/build/JingleTune.']
        elif n==46:
            lines+=['Source: Old Songs for Young Voices (1898), collected by Agnes L. Money.',
                    'Transcribed by cipoo.net; hosted by Breizh Partitions / CelticScores.',
                    auld['score_url'],auld['url']]
        else:
            lines+=['Source: A Collection of Christmas Carols, edited by Benjamin Bloomfield.',
                    song['source_url'],'Source edition and credits:',f'{BOOK}#page={page+4}']
            if n in (26,32):
                lines+=['Words source: original !Xmas26 verse in Docs/build/LyricInput.']
        lines+=['!Xmas26 arrangement: OakAcorn Software.','']
        if n==23:
            lines+=['All twelve cumulative verses, performed in full in the app.','']
        lines+=['Lyrics','-----','']
        if sheet.get('instrumental'):
            lines+=['Instrumental presentation. Lyric text is not bundled.', 'Words and original score are available from the credited source:', f'{BOOK}#page={page+4}', '']
        for verse in body:lines+=verse+['']
        (dest/f'C{n:02}').write_bytes(('\n'.join(lines).rstrip()+'\n').encode('latin-1'))
    print('Generated 46 lyric sheets, with credits, source links and verse lines.')
if __name__=='__main__':build()
