#!/usr/bin/env python3
"""Exercise real native licence icons, links and failures at mocked OS boundaries."""
from pathlib import Path
import argparse,json,re,runpy,subprocess,tempfile
ROOT=Path(__file__).resolve().parent

def main():
 ap=argparse.ArgumentParser();ap.add_argument('--brandy',default='brandy');ap.add_argument('--icons',type=Path);a=ap.parse_args()
 rows=json.loads((ROOT/'LicenseData').read_text())['rows']
 for row in rows:
  for target in row[6:9]:
   base=ROOT.parent.parent if target.startswith('!Xmas26.') else ROOT.parent
   assert (base/target.replace('.','/')).is_file(),target
 for path in ('Docs/Warranty','Docs/VersionChanges','!Xmas26/License'):assert (ROOT.parent.parent/path).is_file()
 header='''ON ERROR PRINT "FAIL: ";REPORT$;" at ";ERL:QUIT
DIM icon% 35,poll% 255,errorblock% 255,inset% 7,action% 7
$inset%="R2":$action%="R5,3"
screenw%=1920:screenh%=1080:icons%=0:blue%=0:errors%=0
fileflags%=0:taskflags%=0:uriflags%=0:uristatus%=0:testkind%=1
textcalls%=0:uricalls%=0:poll%!8=4
PROClicensewindow
PROCassert(icons%=144 AND blue%=3,"all rows and three pale blue headings")
PROCassert(liclinks%=47 AND licused%=18432,"bounded persistent icons and link mapping")
PROCassert(licextent%!4=-1980 AND licextent%!8=1760,"scrollable extent covers all fourteen rows")
REM The actual click dispatcher must resolve every registered target correctly.
FOR link%=0 TO liclinks%-1
 poll%!16=liclinkid%(link%):oldtext%=textcalls%:oldurl%=uricalls%
 PROClicenseclick
 IF liclinkkind%(link%)=1 THEN
  PROCassert(uricalls%=oldurl%+1 AND textcalls%=oldtext%,"web target uses URI, never a shell")
  PROCassert(lasturl$=liclinktarget$(link%),"exact registered URL")
 ELSE
  PROCassert(textcalls%=oldtext%+1 AND uricalls%=oldurl%,"file target uses editor")
  expected$="<Xmas26$Dir>.Docs."+liclinktarget$(link%)
  IF LEFT$(liclinktarget$(link%),8)="!Xmas26." THEN expected$="<Xmas26$Dir>."+MID$(liclinktarget$(link%),9)
  PROCassert(lastpath$=expected$,"correct document path")
  PROCassert(lastcommand$="@RunType_FFF "+CHR$34+expected$+CHR$34,"quoted path with explicit text handler")
 ENDIF
NEXT
poll%!16=licwarranty%:PROClicenseclick
PROCassert(lastpath$="<Xmas26$Dir>.Docs.Warranty","warranty button")
poll%!16=licchanges%:PROClicenseclick
PROCassert(lastpath$="<Xmas26$Dir>.Docs.VersionChanges","version notes button")
oldtext%=textcalls%:oldurl%=uricalls%
poll%!8=1:PROClicenseclick:poll%!8=2:PROClicenseclick
poll%!8=4:poll%!16=-1:PROClicenseclick
PROCassert(textcalls%=oldtext% AND uricalls%=oldurl%,"Adjust, Menu and unknown icons do nothing")
PROClictext("!Xmas26.!RunImage")
PROCassert(LEFT$(lastcommand$,13)="@RunType_FFF ","executable file is still opened as text")
oldtext%=textcalls%
PROClictext("file"+CHR$34+"bad"):PROClictext("file"+CHR$10+"bad")
PROClictext("^.outside"):PROClictext("<Injected$Dir>.File"):PROClictext("")
PROCassert(textcalls%=oldtext%,"unsafe local paths rejected")
oldurl%=uricalls%
PROClicurl("javascript:alert(1)"):PROClicurl("https://example.invalid/")
PROClicurl("https://www.pi-star.co.uk/qtm"+CHR$10+"bad")
PROCassert(uricalls%=oldurl%,"only exact published HTTPS links accepted")
REM Error returns must keep the app running and give a useful native notice.
testkind%=0:before%=errors%:PROClictext("!Xmas26.License")
PROCassert(errors%=before%+1 AND textcalls%=oldtext%,"missing file does not launch editor")
testkind%=1:fileflags%=1:PROClictext("!Xmas26.License")
PROCassert(errors%=before%+2 AND textcalls%=oldtext%,"OS file error handled")
fileflags%=0:taskflags%=1:PROClictext("!Xmas26.License")
PROCassert(errors%=before%+3,"text handler failure reported")
taskflags%=0:uriflags%=1:PROClicurl("https://www.pi-star.co.uk/qtm")
PROCassert(errors%=before%+4,"missing URI handler reported")
uriflags%=0:uristatus%=1:PROClicurl("https://www.pi-star.co.uk/qtm")
PROCassert(errors%=before%+5,"unclaimed URL reported")
uristatus%=0:PROClicurl("https://www.pi-star.co.uk/qtm")
PROCassert(errors%=before%+5,"successful URI dispatch has no error")
PRINT "PASS: 144 icons, 47 links, blue headers, local text/URI separation and failure handling"
QUIT
DEF PROCassert(ok%,why$)
IF ok%=FALSE THEN ERROR 1,why$
ENDPROC
DEF FNwindow(w%,h%,flags%,title$,bg%)
PROCassert((flags% AND &FF000000)=&FF000000,"resize and both scroll bars")
=100
DEF FNcaptureicon
LOCAL s$,validation$,id%,f%
s$=$(icon%!24):validation$="":IF icon%!28<>-1 THEN validation$=$(icon%!28)
PROCassert(LEN(s$)*16<=icon%!12-icon%!4,"clipped table text: "+s$)
PROCassert(icon%!4>=0 AND icon%!12<=1760 AND icon%!8>=-1980,"icon outside extent")
f%=icon%!20
IF validation$="C453321/F4EADC" THEN
 blue%+=1:PROCassert((f% AND &20)<>0,"blue heading is filled")
 PROCassert((f% AND &F000)=0,"heading is not a click target")
ENDIF
PRINT "ICON|";icon%!4;"|";icon%!8;"|";icon%!12;"|";icon%!16;"|";f%;"|";validation$;"|";s$
id%=icons%:icons%+=1
=id%
DEF PROCsourceopen(which%)
ENDPROC
DEF PROClicensefolder
ENDPROC
'''
 ui=(ROOT/'LicenseUI').read_text().split('DEF PROClicensefolder')[0]
 replacements={
  'SYS "Wimp_SetExtent",licences%,licextent%':'REM captured extent',
  'SYS "Wimp_CreateIcon",,icon% TO id%':'id%=FNcaptureicon',
  'SYS "XOS_File",5,path$ TO kind%;flags%':'kind%=testkind%:flags%=fileflags%:lastpath$=path$',
  'SYS "XWimp_StartTask","@RunType_FFF "+CHR$34+path$+CHR$34 TO err%;flags%':'lastcommand$="@RunType_FFF "+CHR$34+path$+CHR$34:flags%=taskflags%:textcalls%+=1',
  'SYS &6E381,0,licurlbuf%,0 TO result%;flags%':'result%=uristatus%:flags%=uriflags%:lasturl$=LEFT$($licurlbuf%,LEN($licurlbuf%)-1):uricalls%+=1',
  'SYS "XWimp_ReportError",errorblock%,1,"Xmas26"':'errors%+=1:lasterror$=$(errorblock%+4)',
 }
 for old,new in replacements.items():assert old in ui,old;ui=ui.replace(old,new)
 program=header+ui
 build=runpy.run_path(str(ROOT/'Build'))
 with tempfile.TemporaryDirectory(prefix='xmas26-licences-') 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=build['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)
   result=subprocess.run([a.brandy,'-size','16M','-quit',str(p)],capture_output=True,text=True,timeout=60)
   if result.returncode or 'PASS: 144 icons' not in result.stdout:
    Path('/tmp/xmas26-licences-failed.bas').write_text(program)
    raise AssertionError((tokenised,result.returncode,result.stdout[-3000:],result.stderr))
   print(('Tokenised' if tokenised else 'Source')+': '+result.stdout.splitlines()[-1])
   if not tokenised and a.icons:
    icons=[]
    for line in result.stdout.splitlines():
     if line.startswith('ICON|'):
      _,x0,y0,x1,y1,flags,validation,label=line.split('|',7)
      icons.append(dict(x0=int(x0),y0=int(y0),x1=int(x1),y1=int(y1),flags=int(flags),validation=validation,label=label))
    a.icons.write_text(json.dumps(icons,indent=2)+'\n')
if __name__=='__main__':main()
