#!/usr/bin/env python3
"""Check additive lights, native/web map parity and all 13 light patterns.
Host dependencies: Matrix Brandy, Node.js, Python unicorn and capstone.
This does not replace visual acceptance on a RISC OS desktop.
"""
from pathlib import Path
import struct,re,random,sys,subprocess,json,runpy,tempfile,argparse
ROOT=Path(__file__).resolve().parent
ap=argparse.ArgumentParser(description=__doc__)
ap.add_argument('--brandy',default='sbrandy')
ap.add_argument('--web-dir',type=Path,required=True,help='Web directory containing room-render.js')
options=ap.parse_args();WEB=options.web_dir.resolve()
from unicorn import Uc,UC_ARCH_ARM,UC_MODE_ARM
from unicorn.arm_const import *
from capstone import Cs,CS_ARCH_ARM,CS_MODE_ARM
source=(ROOT/'LampParty').read_text()
def code(name):
 pairs=re.findall(rf'{name}%!(\d+)=&([A-F0-9]+)',source)
 return b''.join(struct.pack('<I',int(op,16)) for _,op in sorted(pairs,key=lambda p:int(p[0])))
def add(a,b):return sum(min(255,(a>>s&255)+(b>>s&255))<<s for s in (0,8,16))
regs=[UC_ARM_REG_R0,UC_ARM_REG_R1,UC_ARM_REG_R2,UC_ARM_REG_R3,UC_ARM_REG_R4,UC_ARM_REG_R5,UC_ARM_REG_R6,UC_ARM_REG_R7,UC_ARM_REG_R8,UC_ARM_REG_R9,UC_ARM_REG_R10,UC_ARM_REG_R11,UC_ARM_REG_R12,UC_ARM_REG_SP,UC_ARM_REG_LR]
rng=random.Random(2650)
for name in ['partyadd','ledadd']:
 c=code(name);ins=list(Cs(CS_ARCH_ARM,CS_MODE_ARM).disasm(c,0x1000));assert len(ins)*4==len(c)
 for width in [0,1,15,600,694]:
  for tint in [0,0xFFFFFF,0x800001,0x01FF80,0x123456]:
   height=15 if name=='ledadd' else 1;pad=8;stride=width+pad
   pixels=[rng.randrange(0x1000000) for _ in range(stride*height)];src=[tint if j%3 else rng.randrange(0x1000000) for j in range(width*height)]
   if tint==0:src=[0]*len(src)
   data=struct.pack('<'+'I'*(len(pixels)+2),0xDEADBEEF,*pixels,0xCAFEBABE)
   u=Uc(UC_ARCH_ARM,UC_MODE_ARM);u.mem_map(0x1000,0x80000);u.mem_write(0x1000,c);u.mem_write(0x10000,data)
   u.mem_write(0x30000,struct.pack('<'+'I'*len(src),*src))
   if name=='ledadd':args=[0x10004,0x30000,width,height,pad*4]
   else:args=[0x10004,width,tint]
   values=args+[0x12345+i for i in range(13-len(args))]+[0x7F000,0x2000]
   for reg,value in zip(regs,values):u.reg_write(reg,value)
   u.emu_start(0x1000,0x2000,count=max(100,width*height*50))
   assert [u.reg_read(r) for r in regs]==values,(name,'register corruption')
   got=list(struct.unpack('<'+'I'*(len(pixels)+2),u.mem_read(0x10000,len(data))))
   expect=pixels[:]
   for y in range(height):
    for x in range(width):expect[y*stride+x]=add(expect[y*stride+x],src[y*width+x] if name=='ledadd' else tint)
   assert got==[0xDEADBEEF,*expect,0xCAFEBABE],(name,width,tint,'pixels/guards')
 print('PASS',name,'25 ARMv4 cases: zero identity, per-channel monotonicity/saturation, row bounds, all registers')
# Verify the actual BASIC pattern state machine against all 13 web patterns.
lighting=(ROOT/'Lighting').read_text()
brandy=options.brandy
with tempfile.TemporaryDirectory() as tmp:
 out=Path(tmp)/'patterns.bin';p=Path(tmp)/'check.bas'
 p.write_text(f'''ON ERROR PRINT "FAIL: ";REPORT$;" at ";ERL:QUIT
DIM level%(29),lightid%(29)
f%=OPENOUT("{out}"):bulbbase%=0
FOR pattern%=0 TO 12
 FOR sample%=0 TO 600 STEP 25
  ledpattern%=pattern%:ledstart=0:ledend=1000000:ledhue%=7:ledserial%=3:ledlast=-1
  scenetime=sample%/100:PROClighting
  FOR i%=0 TO 29:BPUT #f%,lightid%(i%) MOD 256:BPUT #f%,lightid%(i%) DIV 256:NEXT
 NEXT
NEXT
CLOSE #f%
PRINT "PASS native patterns"
QUIT
'''+lighting)
 r=subprocess.run([str(brandy),'-quit',str(p)],capture_output=True,text=True,timeout=30);assert 'PASS' in r.stdout,(r.stdout,r.stderr)
 js=WEB/'room-render.js';script=f'''import fs from 'node:fs';
let s=fs.readFileSync({json.dumps(str(js))},'utf8').replace(/^import .*$/mg,'');
const {{TreeLights}}=await import('data:text/javascript;base64,'+Buffer.from(s).toString('base64'));
const t=new TreeLights();t.start=0;t.hue=7;t.serial=3;
const all=[];for(let p=0;p<13;p++)for(let j=0;j<=600;j+=25){{t.pattern=p;for(let i=0;i<30;i++){{let f=t.frame(i,j/100);all.push(f%256,Math.floor(f/256));}}}}
fs.writeFileSync({json.dumps(str(Path(tmp)/'web.bin'))},Buffer.from(all));
'''
 r=subprocess.run(['node','--input-type=module','-e',script],capture_output=True,text=True,timeout=30);assert r.returncode==0,(r.stdout,r.stderr)
 native=out.read_bytes();web=(Path(tmp)/'web.bin').read_bytes();assert native==web, next((i,native[i],web[i]) for i in range(len(native)) if native[i]!=web[i])
 print('PASS all 13 native/web lighting patterns agree for 30 lamps at 25 points per six-second cycle')
# Run the actual native map generator in BASIC, then compare all 59,400 texels.
brandy=options.brandy
lighting=(ROOT/'Lighting').read_text();gen=lighting[lighting.index('DEF PROCledmaps'):lighting.index('DEF PROCdrawtreeleds')]
with tempfile.TemporaryDirectory() as tmp:
 out=Path(tmp)/'glow.bin';p=Path(tmp)/'check.bas'
 p.write_text(f'''ON ERROR PRINT "FAIL: ";REPORT$;" at ";ERL:QUIT
PROCledmaps
f%=OPENOUT("{out}")
FOR p%=ledglow% TO ledglow%+237599:BPUT #f%,?p%:NEXT
CLOSE #f%
PRINT "PASS native emission maps"
QUIT
'''+gen)
 r=subprocess.run([str(brandy),'-quit',str(p)],capture_output=True,text=True,timeout=90)
 assert 'PASS' in r.stdout,(r.stdout,r.stderr)
 native=out.read_bytes();assert len(native)==237600
 js=WEB/'room-render.js';script=f'''import fs from 'node:fs';
let s=fs.readFileSync({json.dumps(str(js))},'utf8').replace(/^import .*$/mg,'');
const {{bulbEmission,TreeLights}}=await import('data:text/javascript;base64,'+Buffer.from(s).toString('base64'));
const all=[];for(let h=0;h<33;h++)for(let l=0;l<8;l++){{let b=bulbEmission(h,l);for(let i=3;i<b.length;i+=4)b[i]=0;all.push(Buffer.from(b));}}
fs.writeFileSync({json.dumps(str(Path(tmp)/'web.bin'))},Buffer.concat(all));
const t=new TreeLights();t.pattern=12;t.start=0;
for(let i=0;i<30;i++){{let levels=new Set();for(let j=0;j<=600;j++){{const f=t.frame(i,j/100);if(Math.floor(f/8)!==32||f%8<2)throw Error('white twinkle');levels.add(f%8);}}if(levels.size<5)throw Error('static light');}}
console.log('PASS 30 gently twinkling white lights over complete six-second cycle');
'''
 r=subprocess.run(['node','--input-type=module','-e',script],capture_output=True,text=True,timeout=30);assert r.returncode==0,(r.stdout,r.stderr)
 print(r.stdout.strip());web=(Path(tmp)/'web.bin').read_bytes()
 assert native==web, next((i,native[i],web[i]) for i in range(len(native)) if native[i]!=web[i])
 print('PASS native/web emission maps byte-for-byte identical across 33 hues × 8 levels × 225 pixels')
 for h in range(33):assert set(native[h*7200:h*7200+900])=={0}
 print('PASS every unlit map contains zero emission; no opaque dark rim or background')
