from pathlib import Path
import json,struct,runpy,hashlib,zipfile
import sys
r=Path(__file__).resolve().parent; native=r.parent.parent
if len(sys.argv)<2:raise SystemExit('Usage: python3 CheckFullSongs /path/to/web/xmas26 [previous-native.zip]')
w=Path(sys.argv[1])
read=lambda n:json.loads((r/n).read_text())
lyrics=read('LyricInput')['songs'][22];review=read('TwelveReview');song=read('MusicData')['songs'][22]
# Independently inspect the words the player will actually show, not only source verse metadata.
book=json.loads((w/'score/songbook.json').read_text());lines=book['songs'][22]['lines'];text=' '.join(x[0] for x in lines).lower()
ordinals='first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth'.split()
for word in ordinals: assert text.count('on the '+word+' day')==1,(word,text)
assert 'skip to' not in text and text.count('pear tree.')==12
for gift,count in [('five gold rings',8),('six geese',7),('eight maids',5),('nine ladies',4),('ten lords',3),('twelve drummers',1)]:assert text.count(gift)==count,(gift,text.count(gift))
assert len(review['verses'])==12 and song['duration_cs']>25000
# Every karaoke syllable begins on a melody attack, including ordinal subdivisions.
onsets={a for a,b,n in song['streams'][0] if n>=0}
assert all(t in onsets for t,word in lyrics['cues'])
assert all(len(x[0])<=30 for x in lines)
index=json.loads((w/'music/index.json').read_text())
for mode in ['0','1','2','3','4','dj']:
 assert f'{mode}-23' in index['tracks'] and f'{mode}-43' in index['tracks']
 assert index['tracks'][f'{mode}-23']['duration']>170
 if mode!='0':
  b=(w/f'music/{mode}-23.bin').read_bytes();n=struct.unpack_from('<I',b,8)[0];cs=struct.unpack_from(f'<{n+1}i',b,12+4*(n+1))
  for v in review['verses']:
   at=round(v['start_tick']*review['tempo']/review['division']/10000)
   assert any(abs(p-at)<4 for p in cs),(mode,v['day'])
medley=index['tracks']['5-medley'];assert any(x['title']=='The Twelve Days of Christmas' for x in medley['parts']) and any(x['title']=='Auld Lang Syne' for x in medley['parts'])
medtext=' '.join(x[0] for x in book['medley']['lines']).lower()
for word in ordinals:assert 'on the '+word+' day' in medtext,word
assert 'for auld lang syne' in medtext
assert len(index['titles'])==46 and len(book['songs'])==46
for number in [44,45,46]:
 for mode in ['0','1','2','3','4','dj']:assert f'{mode}-{number}' in index['tracks']
 assert any(x['title']==index['titles'][number-1] for x in medley['parts'])
for i in range(46):
 b=(native/f'!Xmas26/Tracker/Mix/J{i+1:02}').read_bytes();tag,version,id,bpm,pulse,pad,cut,n,orig=struct.unpack_from('<4s8I',b)
 assert tag==b'DJ41' and version==2 and n<6400 and cut+96==n and n*48+36==len(b)
 # One uninterrupted kick every beat through the full verse sequence and tail.
 for row in range(0,n,12):
  a,bb,c,d=b[36+32*row+20:36+32*row+24];assert (a&16)|(c>>4), (i,row)
# Only Twelve Days changes in the individual regular genre modules.
if len(sys.argv)>2:
 with zipfile.ZipFile(sys.argv[2]) as old:
  for folder in ['Chill','Dance','Class','Trance']:
   for i in range(1,44):
    if i==23:continue
    name=f'!Xmas26/Tracker/{folder}/C{i:02}'
    assert old.read(name)==(native/name).read_bytes(),name
print('PASS: twelve ordered verses, cumulative gift counts, every karaoke onset, full-song clocks in all five genres plus DJ, both songs in the medley, uninterrupted DJ kick, and optional baseline MOD comparison.')
