#!/usr/bin/env python3
"""Regression for BASIC V's zero-to-fractional-power startup error.

Matrix Brandy accepts 0^.9, while the reported RISC OS BASIC V build does
not. Instrument ONLY that expression with a strict positive-base domain
check. Exercise the real map generator in both source and tokenised form;
the unguarded previous expression must fail, and the fixed one must pass.
This compatibility test does not claim a full RISC OS desktop run.
"""
from pathlib import Path
import argparse,runpy,subprocess,tempfile
ROOT=Path(__file__).resolve().parent
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--brandy',default='sbrandy');args=ap.parse_args()
source=(ROOT/'Lighting').read_text();a=source.index('DEF PROCledmaps');b=source.index('DEF PROCdrawtreeleds')
gen=source[a:b]
assert gen.count('(lev%/7)^.9')==1
strict=gen.replace('(lev%/7)^.9','FNpositivepower(lev%/7,.9)')
old=strict.replace('IF lev%>0 THEN bright=','bright=')
assert strict!=old,'Missing explicit positive-level guard'
build=runpy.run_path(str(ROOT/'Build'))
def tokenised(text):
 out=bytearray()
 for i,line in enumerate(text.splitlines(),1):
  row=build['tokenise_line'](line);assert len(row)+4<=255
  out+=bytes((13,(i*5)>>8,(i*5)&255,len(row)+4))+row
 return out+b'\r\xff'
with tempfile.TemporaryDirectory() as temp:
 temp=Path(temp)
 for fixed,body in [(False,old),(True,strict)]:
  program=f'''ON ERROR PRINT "FAIL ";ERR;" ";REPORT$:QUIT
calls%=0
PROCledmaps
IF calls%<>231 THEN ERROR 1,"Wrong positive power call count"
PRINT "PASS 33 hues, zero plus seven positive levels"
QUIT
'''+body+'''
DEF FNpositivepower(base,power)
IF base<=0 THEN ERROR 22,"Logarithm range"
calls%+=1
=base^power
'''
  for binary in [False,True]:
   path=temp/('probe.bin' if binary else 'probe.bas')
   path.write_bytes(tokenised(program) if binary else program.encode())
   result=subprocess.run([args.brandy,'-quit',str(path)],capture_output=True,text=True,timeout=45)
   assert ('PASS' in result.stdout if fixed else 'FAIL 22 Logarithm range' in result.stdout),(fixed,binary,result.stdout,result.stderr)
   print(('Fixed' if fixed else 'Previous unguarded expression'),('tokenised' if binary else 'source'),': expected result confirmed')
print('PASS BASIC V domain regression: old expression fails; guarded startup completes in source and tokenised form')
