#!/usr/bin/env python3
"""Generate the plain-text song rights register from the shipped metadata.

This records source claims and the MIT grant for original contributions.
It does not relicense third-party inputs. Run after the music builders when changing music.
"""
from pathlib import Path
import hashlib
import json
import textwrap

CATALOGUE = 'https://acollectionofchristmascarols.com/'
CAT_LICENCE = 'https://github.com/bbloomf/christmas-carols/blob/master/LICENSE.md'
CC0 = 'https://creativecommons.org/publicdomain/zero/1.0/'
YOUNG = 'https://www.hymnsandcarolsofchristmas.com/Hymns_and_Carols/silent_night_holy_night-1.htm'
SHCHEDRYK = 'https://commons.wikimedia.org/wiki/File:%D0%A9%D0%B5%D0%B4%D1%80%D0%B8%D0%BA.pdf'
MEDLEY_TITLES = ['Carol of the Bells', 'God Rest You Merry, Gentlemen',
    'Good King Wenceslas', 'Deck the Halls', 'Hark! the Herald Angels Sing',
    'Jingle Bells', 'Silent Night', 'Joy to the World',
    'We Wish You a Merry Christmas']

HEADER = '''XMAS26 2.49 BETA - SONG SOURCES, ASSETS AND LICENCE REGISTER
Prepared 10 November 2026. Plain text; native RISC OS file type &FFF.

SCOPE AND HOW TO READ THIS FILE
All 46 songs are listed individually, followed by the original Xmas Trackies
/ Neon Noel medley. Each entry identifies the score and displayed words,
source links, recorded-source fingerprint where retained, licence basis,
tracker sample assets and the two Maestro exports. Relative paths start at
the package directory containing !Xmas26, Licences, build and Maestros.
URLs are the actual recorded inputs or licence references unless expressly
labelled as historical verification only. Links can change; source hashes
and the preserved grants identify the release inputs. This inventory is
generated from the shipped metadata, not inferred from song titles.

The source tune, its particular arrangement, translated words, recording
and sample are different rights layers. A traditional tune does not make a
modern recording or translation public domain. This register records the
basis used for this release; it is not a worldwide legal clearance. Keep
the accompanying grants and Docs/Licences/RightsReview when distributing it.

LICENCE BASES USED BELOW
[C] Benjamin Bloomfield, A Collection of Christmas Carols.
    Forty retained imported scores come from this collection. Its repository
    states that its contents were found in the public domain and are intended
    to remain so, and expressly invites reuse. This is the publisher's own
    public-domain/reuse declaration, not a Creative Commons CC0 licence and
    not an independent guarantee about every historical contributor.
    Preserve the exact declaration in Docs/Licences/CarolScores/License.
    Catalogue: https://acollectionofchristmascarols.com/
    Repository: https://github.com/bbloomf/christmas-carols
    Grant: https://github.com/bbloomf/christmas-carols/blob/master/LICENSE.md

[S] Shchedryk, Mykola Leontovych (1877-1921), traditional Ukrainian source.
    A1's 2016 engraving identifies the composition as public domain and
    dedicates the engraving to the public domain worldwide, with an
    unrestricted-use fallback where dedication is not legally possible.
    The source PDF and grant record are in Docs/Licences/Shchedryk.
    No Peter J. Wilhousky English words or arrangement are used.

[A] Auld Lang Syne: the selected 1898 score, not a modern arrangement.
    CelticScores/Breizh Partitions lists this transcription as Public Domain;
    the source carries permission to copy and distribute. See its entry
    below, Docs/Licences/AuldLangSyne/ReadMe and Docs/build/AuldSource.

[V] VSCO 2 Community Edition recorded instrument samples, CC0 1.0.
    Versilian Studios; Sam Gossner and Simon Dalzell. Upstream credits
    Elan Hickler / Soundemote for editing and sample cutting.
    CC0 permits copying, modification and redistribution, including
    commercial use, without an attribution condition; these credits are
    retained for provenance. The grant includes its warranty disclaimers.
    Licence copy: Docs/Licences/VSCO2CE/License; credits: VSCO2CE/Upstream.
    https://creativecommons.org/publicdomain/zero/1.0/
    https://versilian-studios.com/vsco-community/
    https://github.com/sgossner/VSCO-2-CE/tree/440300901dfe9275fd84e0b7763af1f8443ae62e

[P] Work created for this project under the user's direction with AI help:
    new arrangements, synthesis, tracker programming, replacement verses,
    conversion and synchronisation code. Project credit: OakAcorn Software.
    These original project contributions are licensed under MIT, to the
    extent of the contributors' rights. See Docs/Licences/Project/License and
    Scope. The grant includes new arrangements and original replacement
    verses, and does not change the rights in underlying traditional material.
    Source is supplied under build; original synthesis uses no sample pack.

WORK SHARED BY EVERY SONG
Traditional playback: the note streams in Docs/build/MusicData feed the native
RISC OS sound system through Docs/build/Music. OS-provided voices are used;
no recorded commercial performance or OS voice module is bundled here.
The imported score data was decoded, repeats/timing retained or corrected,
and reduced to the application's three playable voices.

Chillout and 90s PC-Pop: Docs/build/ClubArrange creates the backing,
introductions, fills and phrase contrasts. Each song retains its own sound
palette. Melody and accompaniment share the source metre and tempo map.
Docs/build/ClubSamples synthesises the electronic samples mathematically from
oscillators/noise, envelopes and short effects. No external audio or loops
are used in these two versions. Sample provenance is Docs/build/ClubSources.
Dance/Trance: original sample synthesis in Docs/build/TranceBank, pattern parts
in Docs/build/TranceParts, individual sample hashes in Docs/build/TranceSrc. All
Dance/Trance PCM is original project work [P], released under MIT.

Classical: Docs/build/BuildTrackers arranges the source voices using the actual
embedded samples listed under each entry. Recorded samples were converted
to mono, trimmed, tuned, resampled, looped where appropriate, normalised
and encoded as signed 8-bit PCM by Docs/build/BuildSamples. The synthetic Soft
Timpani is project work [P]; VSCO recordings remain CC0 [V].

Karaoke and notation: syllables were aligned to score events, whole-word
and punctuation breaks added, repeats checked, and tracker row/time maps
generated. Docs/build/LyricInput holds the current words/cues; Docs/build/BuildMedia,
BuildKara and AlignLyrics record the conversion work. Notes/lyrics are
rendered by the app, not copied as song-specific artwork or album covers.

Maestro: both exports for each song contain generated MusicFile score data,
including key signatures. MaestrosPluck uses Pluck for the lead and Soft for channels 2-8, all at ff. Neither folder
contains Maestro program code or recorded instrument audio. Maestro is not
used for application playback. See Docs/Licences/Maestro/ReadMe for references.

The following sample lists describe what is embedded in each module,
including any retained sample that is not triggered. They are read from
Docs/build/TrackerModes and checked against each module's SHA-256. Pinned source
URLs under each Classical entry identify the exact WAVs that were processed.
The raw WAV files are not included in this distribution.

CURRENT RIGHTS CORRECTIONS
Since v2.28, Bells uses the independently transcribed Shchedryk melody and
new backing/English words. O Christmas Tree and Pat-a-Pan also use original
project English verses in place of uncertain translated text. Noel Nouvelet
uses French and Still, Still, Still uses German. Removed raw MIDI/LilyPond
archives and unused translated words are not redistributed. Older change
logs are historical; this register describes the current supplied assets.

CONTENTS
'''


def build(root):
    root = Path(root)
    dist = root.parent.parent
    def read(name):
        return json.loads((root/name).read_text())
    def digest(path):
        return hashlib.sha256(path.read_bytes()).hexdigest()
    songs = read('MusicData')['songs']
    lyrics = read('LyricInput')['songs']
    tracks = read('TrackerModes')['tracks']
    bank = read('SampleSources')
    club = read('ClubSources')
    medley = read('TrackerData')
    auld = read('AuldSource')
    recordings = {'VSCO '+s['name']: s for s in bank['recorded_sources']['samples']}
    originals = {s['name'] for s in club['samples']}
    originals.update(s['name'] for s in bank['samples'] if s['name'] not in recordings)
    originals.update(s['name'] for s in read('TranceSrc')['samples'])
    assert len(songs) == len(lyrics) == 46 and len(tracks) == 184
    assert len(recordings) == 9
    lookup = {(t['song'], t['style']): t for t in tracks}
    assert len(lookup) == 184
    out = [HEADER.rstrip()]
    def para(text):
        out.append(textwrap.fill(text, width=76, break_long_words=False,
                                 break_on_hyphens=False))
    for i, song in enumerate(songs, 1):
        out.append(f'{i:02d}. {song["title"]}')
    out += ['M. Original Xmas Trackies / Neon Noel medley', '']

    for index, (song, lyric) in enumerate(zip(songs, lyrics)):
        number = index+1
        title = song['title']
        assert title == lyric['title']
        out += ['='*76, f'SONG {number:02d} OF 46: {title}', '='*76]
        if index == 0:
            para('Score: Franz Xaver Gruber (1818); the arrangement entered for '
                 'Christmas 1.1 is retained in Docs/build/SilentNight. No external '
                 'MIDI or performance was downloaded for this version. The '
                 'old tune and Young translation are public-domain material; '
                 'new sequencing/accompaniment is project work [P].')
            out += ['Project score SHA-256: '+digest(root/'SilentNight')]
            para('Words: Joseph Mohr, English translation by John Freeman '
                 'Young; hand-aligned to the project score. Young first '
                 'published it in 1859; 1863 in the older build metadata is '
                 'a later reprint date. The link below supplies historical '
                 'verification, not an imported arrangement or recording. '
                 'Later William C. Egan translations on that page are not used.')
            out += ['Historical words/tune reference: '+YOUNG,
                    'Local score/cues: Docs/build/SilentNight; Docs/build/LyricInput.']
        elif index == 2:
            para('Score: Leontovych Shchedryk; independently transcribed from '
                 'A1\'s public-domain engraving [S]. Printed repeats were '
                 'unfolded; the two backing voices were written for the '
                 'project [P]. The popular catalogue title is retained, '
                 'but this is not the Wilhousky version.')
            out += ['Score and grant: '+SHCHEDRYK,
                    'Permanent grant reference: https://commons.wikimedia.org/w/index.php?title=File:%D0%A9%D0%B5%D0%B4%D1%80%D0%B8%D0%BA.pdf&oldid=1087201469',
                    'Source PDF SHA-256: '+digest(dist/'Docs/Licences/Shchedryk/SourcePDF'),
                    'Project note/lyric arrangement SHA-256: '+song['source_sha256']]
            para('Words: original festive English project words [P], '
                 'syllable-aligned to the new transcription. Source files: '
                 'Docs/build/Shchedryk and Docs/build/LyricInput. No external lyric '
                 'translation was imported for this replacement.')
            out += ['Licence records: Docs/Licences/Shchedryk/Grant and ReadMe.']
        elif index == 38:
            tune=read('JingleTune')
            para('Music: James Lord Pierpont. Familiar later verse and chorus, independently '
                 'sequenced with new OakAcorn backing [P]. The two identical opening '
                 'three-note groups in each chorus and the two endings are explicit.')
            out += ['Historical tune reference: '+tune['source'],
                    'Additional historical edition: '+tune['corroboration'],
                    'Tune-form reference: '+tune['reference'],
                    'Project source: Docs/build/JingleTune; SHA-256: '+song['source_sha256']]
            para('Words: retained first verse and chorus from the collection lyric '
                 'events [C], realigned to the corrected melody. Timing and onset '
                 'generation: Docs/build/JingleMake. Lyrics-only source follows.')
            out += ['Words source: '+tune['lyrics_source']]
        elif index == 42:
            para('Score/words: traditional Scottish melody; Robert Burns; '
                 'Old Songs for Young Voices, collected by Agnes L. Money '
                 '(1898), transcribed by cipoo.net and hosted by Breizh '
                 'Partitions / CelticScores. Publisher status: Public Domain '
                 '[A]; source permission allows copying and distribution. '
                 'This is the selected historical score, not the separately '
                 'listed modern arrangement.')
            out += ['Catalogue / rights: '+auld['catalogue'],
                    'Printed score / lyric reference: '+auld['score_url'],
                    'Imported MIDI: '+auld['url'],
                    'Imported MIDI SHA-256: '+auld['sha256'],
                    'Preserved provenance: Docs/build/AuldSource; Docs/Licences/AuldLangSyne/ReadMe.']
            para('Work: decoded voices, aligned printed syllables to the '
                 'vocal line, and held words through slurs. Available in the '
                 'application throughout the year; exports are always supplied.')
        else:
            para('Score asset: Benjamin Bloomfield, A Collection of Christmas '
                 'Carols. Imported note/timing data from the following MIDI. '
                 'Score licence basis [C]: publisher public-domain/reuse '
                 'declaration, preserved in Docs/Licences/CarolScores/License.')
            out += ['Score input: '+song['source_url'],
                    'Imported MIDI SHA-256: '+song['source_sha256'],
                    'Collection: '+CATALOGUE, 'Licence declaration: '+CAT_LICENCE]
            if lyric.get('instrumental'):
                extra=next(s for s in read('AdditionalSources')['songs'] if s['title']==title)
                para('Music credit: '+extra['music'])
                para('Words source credit (text not bundled): '+extra['words'])
                out += ['Printed source data: '+extra['score_source_url'], 'Decoded provenance: Docs/build/AdditionalSources.']
                para('Instrumental presentation. Lyric text is not bundled. The credited upstream score provides the words; see the source link in the supplied text sheet.')
            elif index in (25, 31):
                para('Words: original festive English project verse [P], '
                     'written 2 November 2026 to replace an unidentified '
                     'later translation. Source: Docs/build/LyricInput. The new '
                     'syllables retain the established melody cue timings; '
                     'the former English translation is not redistributed.')
            else:
                language = {33:'French',34:'Latin',36:'German'}.get(index)
                para('Words: '+(language+' lyric material; ' if language else '')+
                     'extracted from the collection MIDI lyric events and '
                     'aligned to the selected vocal line. Licence basis [C], '
                     'under the same publisher declaration linked above. '
                     'Current retained words/cues: Docs/build/LyricInput.')
                out += ['Lyric input: '+lyric['source']]
                if 'lyric_track' in lyric:
                    out += ['Lyric track index recorded by importer: '+str(lyric['lyric_track'])]
                if index == 33:
                    para('The unused P.S.B. English translation formerly '
                         'present in the raw score archive is not included.')
        for key in ('timing_note', 'word_join_note'):
            if lyric.get(key):
                para('Retained conversion note: '+lyric[key])

        out += ['', 'SUPPLIED VERSIONS AND THEIR SAMPLE ASSETS']
        para('Traditional: project sequencing [P], source rights as above; '
             'native OS voices, no downloaded performance. Notes are in '
             '!Xmas26/Carols with karaoke/notation in Lyrics/NoteView/KaraScore.')
        for style, folder in [(1,'Chill'), (2,'Dance'), (3,'Class'), (4,'Trance')]:
            track = lookup[(index, style)]
            assert track['title'] == title
            module = f'!Xmas26/Tracker/{folder}/C{number:02d}'
            assert digest(dist/module) == track['sha256'], module
            assert set(track['samples']) <= originals | recordings.keys(), title
            out += ['', track['label']+': '+module,
                    'Module SHA-256: '+track['sha256']]
            if style==4:
                asset=f'!Xmas26/Tracker/Mix/J{number:02}'
                out+=['DJ playback file: '+asset, 'DJ file SHA-256: '+digest(dist/asset),
                      'Original mix/beat-grid code [P]: Docs/build/BuildDJ and Docs/build/DJMix.']
            if track.get('arrangement'):
                out += ['Arrangement style: '+track['arrangement']]
            para('Embedded sample names: '+', '.join(track['samples'])+'.')
            original = [n for n in track['samples'] if n not in recordings]
            if original:
                para('Original synthetic samples [P]: '+', '.join(original)+
                     '. Source: '+('Docs/build/ClubSamples; Docs/build/ClubSources.' if style<3
                                  else 'Docs/build/TranceBank; Docs/build/TranceSrc.' if style==4 else 'Docs/build/BuildSamples; Docs/build/SampleSources.'))
            recorded = [n for n in track['samples'] if n in recordings]
            if recorded:
                out += ['Recorded samples: VSCO 2 CE [V], CC0 1.0: '+CC0,
                        'Exact processed-source WAV URLs:']
                for name in recorded:
                    out += ['  '+name+': '+recordings[name]['url']]
            else:
                para('No external recorded sample source for this version. '
                     'Score/word rights above and project-work status [P] '
                     'continue to apply to the resulting arrangement.')
        out += ['', 'Maestro exports (score data; no bundled audio):']
        for folder in ('Maestros', 'MaestrosPluck'):
            files = list((dist/folder).glob(f'{number:02d}-*'))
            assert len(files) == 1, (folder, number)
            out += ['  '+files[0].relative_to(dist).as_posix()]
        para('Export rights: source score rights above; project conversion '
             'and new arrangement work [P]. These files do not license or '
             'include the !Maestro application.')
        if title in MEDLEY_TITLES:
            para('Also used as a theme in the original Xmas Trackies medley; '
                 'see entry M for that version\'s sources and sample assets.')
        out += ['']

    out += ['='*76, 'ENTRY M: ORIGINAL XMAS TRACKIES / NEON NOEL MEDLEY', '='*76]
    para('The retained original alternative mix is an eight-channel '
         'sample-based arrangement with nine carol themes, new transitions '
         'and accompaniment [P]. It is separate from the 172 per-song '
         'Chillout, PC-Pop, Classical and Dance/Trance modules. Build source: Docs/build/Medley; '
         'arrangement metadata: Docs/build/TrackerData.')
    out += ['Theme sources and licence bases:']
    for title in MEDLEY_TITLES:
        index = next(i for i,s in enumerate(songs) if s['title']==title)
        song = songs[index]
        basis = '[S] plus project transcription [P]' if index==2 else '[P] original sequencing of public-domain tune' if index in (0,38) else '[C]'
        out += [f'  {title}: {basis}. See song {index+1:02d}.']
        if index in (0,38):
            para('    Independently sequenced in Docs/build/Medley. '+('The medley uses '
                 'the same written chorus as the full song, transposed to C.'
                 if index==38 else 'This passage uses a full Silent Night verse.'))
    out += ['Collection grant for [C]: '+CAT_LICENCE,
            'Shchedryk source/grant for [S]: '+SHCHEDRYK]
    para('All 18 embedded samples are original mathematical synthesis [P] '
         'in Docs/build/Medley; there are no external sample recordings or loops '
         'in this medley. Sample names: '+', '.join(s['name'] for s in medley['samples'])+'.')
    for file in ('NeonMOD','NeonDTT'):
        path=dist/'!Xmas26/Tracker'/file
        out += [path.relative_to(dist).as_posix()+' SHA-256: '+digest(path)]

    out += ['', '='*76, 'RECORDED SAMPLE CHECKSUMS (FOR ALL [V] LINKS ABOVE)', '='*76]
    for name, sample in recordings.items():
        out += [name, '  Source WAV SHA-256: '+sample['sha256']]
    out += ['', 'PLAYER AND OTHER SHARED COMPONENTS']
    para('Tracker playback uses the excellent QTM player. QTM has its own '
         'licence, not CC0: read Docs/Licences/QTM/License and ReadMe for the '
         'commercial distribution condition and other terms. This app is '
         'not supported or endorsed by QTM\'s authors or owners. The player '
         'licence does not replace any song or sample licence. Speech, '
         'system-font and build-tool records are separately indexed in '
         'Docs/Licences/ReadMe; they are not song recordings.')
    out += ['', 'END OF REGISTER: 46 songs, 184 per-song tracker modules,',
            '86 Maestro exports, one original nine-theme medley.', '']
    result='\n'.join(out)
    result.encode('ascii')
    (dist/'Docs/Licences/Songs').write_text(result, encoding='ascii')
    print(f'Song register: 46 songs, 184 verified module hashes, 92 exports; {len(result)} bytes')


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