#!/usr/bin/env python3
"""Exercise real BASIC shuffle, Christmas clock/state, and native table icons.
Only unavailable Wimp/OS boundaries are replaced. Checks both source and
Acorn-tokenised BASIC in Matrix Brandy; not an emulator integration test.
"""
from pathlib import Path
import argparse,json,re,runpy,subprocess,tempfile
ROOT=Path(__file__).resolve().parent

def proc(file,name):
    s=(ROOT/file).read_text();m=re.search(r'^DEF (?:PROC|FN)'+name+r'(?=\W|$)',s,re.M);assert m,name
    end=re.search(r'^DEF ',s[m.end():],re.M)
    return s[m.start():m.end()+end.start() if end else len(s)].rstrip(':\n')+'\n'

def main():
    ap=argparse.ArgumentParser();ap.add_argument('--brandy',default='brandy');a=ap.parse_args()
    playlist=(ROOT/'Playlist').read_text()
    playlist=re.sub(r'DEF PROCcurrentnotes\n.*?\nENDPROC','DEF PROCcurrentnotes\nENDPROC',playlist,flags=re.S)
    head='''ON ERROR PRINT "FAIL: ";REPORT$;" at ";ERL:QUIT
djlive%=FALSE:djmix%=FALSE:trackerrunning%=FALSE:musicmode%=0
trackermode%=FALSE:paused%=FALSE:animationsstopped%=FALSE:gameactive%=FALSE:karaokemode%=FALSE:openmain%=TRUE
evevisible%=FALSE:evepending%=FALSE:cupactive%=FALSE
songcount%=43:DIM songlength%(42),seen%(42)
FOR i%=0 TO 42:songlength%(i%)=100+i%:NEXT
PROCplaylistinit
PROCassert(random% AND loopall% AND listcount%=42 AND song%<>42,"shuffle on, seasonal defaults")
last%=-1
FOR cycle%=1 TO 30
 seen%()=0
 PROCassert(song%<>last%,"no cycle-boundary repeat")
 FOR n%=1 TO 42
  PROCassert(song%>=0 AND song%<42,"eligible random song")
  seen%(song%)+=1:PROCassert(seen%(song%)=1,"no repeated carol in a cycle")
  last%=song%:PROCplaylistnext
 NEXT
 FOR i%=0 TO 41:PROCassert(seen%(i%)=1,"complete cycle coverage"):NEXT
NEXT
REM Replay and changing playback style do not reset the shuffle history.
played%()=FALSE:PROCsetsong(7):PROCrestartdummy
seen%()=0:seen%(7)=1
FOR n%=1 TO 41
 PROCplaylistnext:seen%(song%)+=1:PROCassert(seen%(song%)=1,"replay preserves unused pool")
NEXT
REM Loop off stops after all eligible songs, including the initial one.
played%()=FALSE:PROCsetsong(3):loopall%=FALSE
FOR n%=1 TO 41:PROCplaylistnext:PROCassert(playlistended%=FALSE,"loop-off plays every song"):NEXT
PROCplaylistnext:PROCassert(playlistended%,"loop-off ends after one cycle")
PROCplaylistloop:PROCassert(playlistended%=FALSE,"loop-on restarts ended shuffle")
REM Seasonal inclusion and removal, queue edits, one-song and empty cases.
PROCplaylistnone:PROCplaylisttoggle(5):PROCplaylisttoggle(8):PROCplaylisttoggle(12)
PROCassert(song%=5 AND listcount%=3,"first added song starts")
PROCplaylisttoggle(5):PROCassert(song%=8 OR song%=12,"remove current selects unused")
PROCplaylisttoggle(8):PROCplaylisttoggle(12)
PROCassert(song%=-1 AND playlistended%,"remove final song")
PROCplaylisttoggle(42):PROCassert(listcount%=0,"seasonal song unavailable before Dec 26")
PROCplaylistall:PROCseasondate("20261226")
PROCassert(included%(42) AND listcount%=43,"seasonal addition")
PROCseasondate("20270102"):PROCassert(included%(42)=FALSE AND listcount%=42,"seasonal removal")
PROCplaylistnone:PROCplaylisttoggle(9):PROCplaylistnext
PROCassert(song%=9 AND playlistended%=FALSE,"one-song shuffle loop")
PROCplaylistloop:PROCplaylistnext:PROCassert(playlistended%,"one-song loop-off")
PROCplaylistnone:PROCplaylistnext:PROCassert(playlistended%,"empty queue is safe")
REM Ordered mode still uses insertion order; switching preserves the song.
PROCplaylisttoggle(9):PROCplaylisttoggle(2):PROCplaylisttoggle(6)
old%=song%:PROCplaylistrandom:PROCassert(random%=FALSE AND song%=old%,"shuffle toggle does not restart")
PROCplaylistnext:PROCassert(song%=2,"ordered next")
PROCplaylistnext:PROCassert(song%=6,"ordered next again")
PROCplaylistrandom:PROCassert(random%,"shuffle can be reenabled")
REM The real Traditional elapsed-time path marks each automatic selection.
PROCplaylistnone:PROCplaylistall:loopall%=FALSE:seen%()=0
FOR n%=1 TO 42
 seen%(song%)+=1:PROCassert(seen%(song%)=1,"traditional automatic shuffle unique")
 PROCplaylistadvance(songlength%(song%))
NEXT
PROCassert(playlistended%,"traditional loop-off completes")

REM Repeat overrides automatic progression, preserving the shuffle pool.
PROCplaylistnone:PROCplaylistall:loopall%=FALSE
PROCassert(repeatsong%=FALSE,"repeat off at launch")
held%=song%:oldpos%=musicpos%:PROCplaylistrepeat
PROCassert(repeatsong% AND musicpos%=oldpos%,"enabling repeat preserves position")
FOR n%=1 TO 10
 PROCplaylistadvance(songlength%(song%)*1000+7)
 PROCassert(song%=held% AND musicpos%=(n%*7) MOD songlength%(held%) AND playlistended%=FALSE,"traditional repeat, bounded long interval")
NEXT
FOR n%=1 TO 5
 PROCplaylistfinish
 PROCassert(song%=held% AND musicpos%=0,"tracker automatic completion repeats current")
NEXT
FOR i%=0 TO 41:PROCassert(played%(i%)=(i%=held%),"repeat preserves shuffle history"):NEXT
PROCplaylistnext:PROCassert(song%<>held%,"manual next escapes repeated song")
nextheld%=song%:PROCplaylistfinish:PROCassert(song%=nextheld%,"new song now repeats")
PROCplaylistrepeat:PROCassert(repeatsong%=FALSE,"repeat disabled")
seen%()=0:seen%(held%)=1:seen%(nextheld%)=1
FOR n%=1 TO 40
 PROCplaylistfinish:seen%(song%)+=1
 PROCassert(seen%(song%)=1,"resume unused shuffle pool")
NEXT
PROCplaylistfinish:PROCassert(playlistended%,"loop off ends after repeat disabled")
PROCplaylistrepeat:PROCassert(playlistended%=FALSE AND repeatsong%,"repeat restarts ended current song")
PROCplaylistnone:PROCplaylistfinish:PROCassert(song%=-1 AND playlistended%,"empty repeated playlist safe")
PROCplaylistall:held%=song%:PROCplaylisttoggle(held%)
PROCassert(song%<>held%,"removing repeated song chooses another")
PROCplaylistrepeat:loopall%=TRUE

PROCnightinit
wallstamp$="20261223210000":PROCnightclock(""):PROCassert(nightpending%=FALSE,"not December 23")
wallstamp$="20261224205959":PROCnightclock(""):PROCassert(nightpending%=FALSE,"not before 9pm")
wallstamp$="20261224210000":PROCnightclock("20261224205959")
PROCassert(nightpending% AND nightseen$="20261224","Christmas Eve 9pm queues visit")
openmain%=TRUE:paused%=TRUE:PROCnighttry:PROCassert(nightactive%=FALSE AND nightpending%,"pause holds visit")
paused%=FALSE:animationsstopped%=TRUE:PROCnighttry:PROCassert(nightpending%,"stopped animations hold visit")
animationsstopped%=FALSE:karaokemode%=TRUE:PROCnighttry:PROCassert(nightpending%,"karaoke holds visit")
karaokemode%=FALSE:cupactive%=TRUE:PROCnighttry:PROCassert(nightpending%,"cupboard conflict waits")
cupactive%=FALSE:scenetime=50:PROCnighttry:PROCassert(nightactive% AND nightpending%=FALSE,"room starts queued visit")
PROCnightclock("20261224210000"):PROCassert(nightpending%=FALSE,"same date cannot retrigger")
FOR wide%=0 TO 1
 roomwide%=wide%<>0:width%=1200:IF roomwide% THEN width%=1388
 nightactive%=TRUE:nightstart=50:nightgifts%=0:lastx=10000
 FOR step%=0 TO 1700
  scenetime=50+step%/100:PROCnightstate
  PROCassert(nightgifts%>=0 AND nightgifts%<=3,"gift count bounded")
  IF step%<600 THEN PROCassert(nightx<=lastx,"Santa enters smoothly from right")
  lastx=nightx
  IF nightid%>=0 THEN PROCassert(nightid%>=nightwalkbase% AND nightid%<nightmagicbase%,"valid full-size Santa frame")
  IF nightmagic%>=0 THEN PROCassert(nightmagic%>=nightmagicbase% AND nightmagic%<nightmagicbase%+20,"valid sparkle frame")
  IF step%=1200 THEN PROCassert(nightid%>=nightwinkbase% AND nightid%<nighttouchbase%,"cheeky wink after gifts")
  IF step%=1350 THEN PROCassert(nightid%>=nighttouchbase% AND nightid%<nightmagicbase%,"touch nose before magic")
  IF step%=1500 THEN PROCassert(nightid%=-1 AND nightmagic%>=0,"Santa vanishes into sparkles")
 NEXT
 PROCassert(nightactive%=FALSE AND nightgifts%=3,"finite visit leaves three presents")
NEXT
PROCnightinit:wallstamp$="20261224210115":PROCnightclock("20261224205959")
PROCassert(nightpending%,"clock polling delay crossing 9pm")
wallstamp$="20261225000000":PROCnightclock("20261224235959"):PROCassert(nightpending%=FALSE,"pending visit does not spill into Christmas Day")
PROCnightinit:wallstamp$="20261224211000":PROCnightclock(""):PROCassert(nightpending%=FALSE,"late launch does not fake 9pm")
PROCnightinit:wallstamp$="20261225210000":PROCnightclock(""):PROCassert(nightpending%=FALSE,"no Christmas Day 9pm visit")

REM Capture real native icon descriptors and check each label fits its cell.
DIM block% 255,icon% 35,inset% 7,action% 7,poll% 255
$inset%="R2":$action%="R5,3":screenw%=1280:screenh%=1024
icons%=0:poll%!8=4:PROClicensewindow
PROCassert(icons%=144,"native table has all headers, controls and cells")
PROCassert(licextent%!8=1760 AND licextent%!4=-1980,"scrollable table extent")
PROCassert((windowflags% AND &FF000000)=&FF000000,"standard resize and scroll furniture")
PROCassert(licused%<=24576,"permanent table buffers bounded")
poll%!16=licmusic%:PROClicenseclick:PROCassert(source%=0,"music source action")
poll%!16=licapp%:PROClicenseclick:PROCassert(source%=1,"app source action")
poll%!16=licnotes%:PROClicenseclick:PROCassert(source%=3,"licence notes action")
DIM menu% 223,options% 247,ibmenu% 127,sourcesroot% 31
DIM musiclabel% 31,optionlabels% 159,karaokelabel% 31,state% 255
menu%!220=&12345678:options%!244=&12345678:ibmenu%!124=&12345678
info%=10:modesmenu%=20:main%=30:bar%=4:carols%=40:helpicon%=0:sourcesicon%=1
djmix%=FALSE:djlive%=FALSE
fullscreen%=FALSE:lowpower%=FALSE:music%=TRUE
karaokestopped%=FALSE:countdownhidden%=FALSE:roomwide%=FALSE
PROCmenu
PROCassert(menu%!220=&12345678 AND options%!244=&12345678 AND ibmenu%!124=&12345678,"menu buffers bounded")
PROCassert($(ibmenu%!88)="Sources and Licences" AND ibmenu%!80=-1,"direct iconbar sources command, no submenu")
PROCassert($(ibmenu%+40)="Info" AND $(ibmenu%+64)="Help" AND $(ibmenu%+112)="Quit","iconbar administrative items")
PROCassert($(menu%+40)="Carols..." AND $(menu%+160)="Music Genre" AND $(menu%+208)="Pause","room use menu")
PROCassert(menu%!196=&80 AND ibmenu%!100=&80,"both menus have bounded item counts")
PROCassert($(options%+184)="Shuffle off" AND options%!172=0,"shuffle retained before repeat")
PROCassert($(options%!208)="Repeat this song" AND options%!196=0,"repeat starts off")
PROCassert($(options%!232)="Dance/Trance DJ mix" AND options%!220=&80,"ninth menu item and end flag")
poll%!16=licprogram%:PROClicenseclick:PROCassert(source%=2,"read program button retained")
poll%!16=licfolder%:PROClicenseclick:PROCassert(folderopened%,"folder button available")
poll%!8=4:poll%!12=info%:poll%!16=sourcesicon%:PROCclick
PROCassert(source%=4,"Info sources button opens table")
REM Actual click dispatcher selects the appropriate root menu only.
poll%!8=2:poll%!12=-2:poll%!16=bar%:PROCclick
PROCassert(shownmenu%=ibmenu% AND iconbarmenu%,"iconbar menu click")
PROCassert(menuy%=296,"iconbar bottom at 96 OS units, including separator")
!poll%=2:poll%!4=-1:PROCselection:PROCassert(source%=4,"iconbar sources opens table directly")
!poll%=0:PROCselection:PROCassert(opened%=info%,"iconbar info action")
!poll%=1:PROCselection:PROCassert(helpopened%,"iconbar help action")
!poll%=3:PROCselection:PROCassert(quit%,"iconbar quit action"):quit%=FALSE
poll%!8=2:poll%!12=main%:PROCclick
PROCassert(shownmenu%=menu% AND iconbarmenu%=FALSE,"room menu click")
!poll%=0:PROCselection:PROCassert(opened%=carols%,"room carol action")
!poll%=4:poll%!4=7:state%!8=1:PROCselection
PROCassert(repeatsong% AND (options%!196 AND 1)<>0 AND shownmenu%=menu%,"repeat toggles and Adjust keeps correct root")
PROCselection:PROCassert(repeatsong%=FALSE,"repeat can be disabled")
!poll%=4:poll%!4=8:PROCselection
PROCassert(djmix% AND options%!220=&81,"Options enables DJ and ticks item")
!poll%=4:poll%!4=8:PROCselection
PROCassert(djmix%=FALSE AND options%!220=&80,"Options disables DJ and removes tick")
!poll%=5:poll%!4=3:PROCselection:PROCassert(chosenmode%=3,"genre submenu index")
!poll%=6:PROCselection:PROCassert(nextrequested%,"room next action")
!poll%=7:PROCselection:PROCassert(paused%,"room pause action")
shownmenu%=-99:poll%!8=2:poll%!12=licences%:PROCclick
PROCassert(shownmenu%=-99,"table does not acquire room menu")
poll%!12=-2:poll%!16=bar%+1:PROCclick
PROCassert(shownmenu%=-99,"other iconbar icons ignored")
stylepopup%=TRUE:!poll%=2:PROCselection
PROCassert(chosenmode%=2 AND shownmenu%=modesmenu%,"karaoke style popup still separate")
PRINT "PASS: 30 shuffle cycles, replay/edit/seasonal cases, ordered mode, local 9pm schedule, Santa phases, native licence table, separate menus and repeat"
QUIT
DEF PROCassert(ok%,s$)
IF ok%=FALSE THEN PRINT "FAIL: ";s$:QUIT
ENDPROC
DEF PROCfxnight(clip%)
ENDPROC
DEF PROCforgetnotes
ENDPROC
DEF PROCrestartdummy
PROCplaylistrestart:PROCsetsong(song%)
ENDPROC
DEF FNwindow(w%,h%,f%,t$,bg%)
windowflags%=f%
=100
DEF FNcaptureicon
LOCAL s$,chars%
s$=$(icon%!24):chars%=(icon%!12-icon%!4) DIV 16
PROCassert(LEN(s$)<=chars%,"clipped table label: "+s$)
id%=icons%:icons%+=1
=id%
DEF PROCsourceopen(which%)
source%=which%
ENDPROC
DEF PROClicensefolder
folderopened%=TRUE
ENDPROC
DEF FNsecretclick(w%,buttons%,ic%)
=FALSE
DEF PROCopen(h%)
opened%=h%
ENDPROC
DEF PROChelp
helpopened%=TRUE
ENDPROC
DEF PROCplaylistui
ENDPROC
DEF PROCmode(id%)
chosenmode%=id%
ENDPROC
DEF PROCnextsong
nextrequested%=TRUE
ENDPROC
DEF PROCpause
paused%=NOT paused%
ENDPROC
'''
    g=json.loads((ROOT/'Geometry').read_text())['groups']
    head=head.replace('PROCnightinit\nwallstamp$', '\n'.join(f'{k}base%={v}' for k,v in g.items() if k.startswith('night'))+'\nPROCnightinit\nwallstamp$',1)
    ui=(ROOT/'LicenseUI').read_text().split('DEF PROClicensefolder')[0].replace('SYS "Wimp_SetExtent",licences%,licextent%','REM captured extent').replace('SYS "Wimp_CreateIcon",,icon% TO id%','id%=FNcaptureicon')
    events=proc('Main','selection')+'\n'+proc('Main','click')
    events=events.replace('SYS "Wimp_GetPointerInfo",,state%:', '')
    events=events.replace('SYS "OS_ReadMonotonicTime" TO now%', 'now%=42')
    for menu in ('modesmenu%', 'ibmenu%', 'menu%'):
        events=events.replace('SYS "Wimp_CreateMenu",,'+menu+',menux%,menuy%', 'shownmenu%='+menu)
    program=head+'\n'+proc('DJMix','djoption')+'\n'+playlist+'\n'+(ROOT/'NightSanta').read_text()+'\n'+ui+'\n'+proc('Main','menu')+'\n'+proc('Main','menuheight')+'\n'+events+'\nDEF PROCmodemenu\nENDPROC\n'
    builder=runpy.run_path(str(ROOT/'Build'))
    with tempfile.TemporaryDirectory(prefix='xmas26-beta-check-') as temp:
        for tokenised in (False,True):
            p=Path(temp)/('test,ffb' if tokenised else 'test.bas')
            if tokenised:
                out=bytearray()
                for n,line in enumerate(program.splitlines(),1):
                    code=builder['tokenise_line'](line);assert len(code)<=251,line
                    out+=bytes((13,n>>8,n&255,len(code)+4))+code
                p.write_bytes(out+b'\r\xff')
            else:p.write_text(program)
            r=subprocess.run([a.brandy,'-size','16M','-quit',str(p)],capture_output=True,text=True,timeout=60)
            if r.returncode or 'PASS: 30 shuffle' not in r.stdout:
                Path('/tmp/xmas26-beta-failed.bas').write_text(program)
                raise AssertionError((tokenised,r.returncode,r.stdout[-3000:],r.stderr))
            print(('Tokenised' if tokenised else 'Source')+': '+r.stdout.strip())

if __name__=='__main__':main()
