#!/usr/bin/env python3
"""Guard the reviewed v2.28 source payload against accidental restoration.

Fingerprints are an audit of this release, not a legal opinion. If changing
music, review its rights before intentionally updating RightsData.
"""
from pathlib import Path
import hashlib,json

def check(root):
 root=Path(root);dist=root.parent.parent
 record=json.loads((root/'RightsData').read_text())
 for rel,want in record['approved_files'].items():
  path=dist/rel
  assert path.is_file(),f'Missing rights input: {rel}'
  assert hashlib.sha256(path.read_bytes()).hexdigest()==want,f'Review changed rights input: {rel}'
 for rel,want in record['generated_music_sha256'].items():
  assert hashlib.sha256((dist/rel).read_bytes()).hexdigest()==want,f'Review/rebuild changed music output: {rel}'
 assert not (root/'QTM-API').exists(),'Optional QTM API manual must not be redistributed'
 assert not list(dist.rglob('RhythmScores')),'Removed score archive has returned'
 assert not list(dist.rglob('*.midi')) and not list(dist.rglob('*.mid')),'Unreviewed raw MIDI in package'
 for name in ['ScoreInput','TrackerInput','LyricInput','MusicKeys']:
  songs=json.loads((root/name).read_text())['songs']
  assert len(songs)==(45 if name=='ScoreInput' else 46),(name,len(songs))
  bell=next(s for s in songs if s['title']=='Carol of the Bells')
  if name=='LyricInput':
   assert 'Original festive English words' in bell['source']
  else:
   assert bell['source_sha256']==record['bells_arrangement_sha256'],name
 for path in dist.rglob('*'):
  if path.is_file() and path.suffix not in ('.pyc',) and not any(x.startswith('.') for x in path.relative_to(dist).parts):
   assert hashlib.sha256(path.read_bytes()).hexdigest() not in record['excluded_source_sha256'],f'Removed source restored: {path}'
 print(f'Rights guard: {len(record["approved_files"])} approved inputs, {len(record["generated_music_sha256"])} music outputs; independent Bells; removed sources absent')

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