#!/usr/bin/env python3
"""Build the tokenised BASIC application, native sprite and RISC OS ZIP.
Python 3 standard library only. Run this script from any directory.
The lexer deliberately supports this source's uppercase keywords and lowercase
identifiers; it is not a general-purpose BBC BASIC tokeniser.
"""
from pathlib import Path
import datetime
import math
import re
import struct
import zipfile

ROOT = Path(__file__).resolve().parent
APP = ROOT / '!PengBowl'
# BBC BASIC V token bytes (BBC BASIC Reference Manual, Appendix B).
# ELSE is contextual: 8B in a single-line IF, CC on its own line.
TOKENS = {
 'SQR':'b6','SGN':'b4','EXP':'a1','ATN':'99','GET$':'be','STOP':'fa','OTHERWISE':'7f','ABS':'94','ASC':'97','RND':'b3','OPENIN':'8e','CLOSE':'d9','READ':'f3','DATA':'dc','AND':'80','DIV':'81','EOR':'82','MOD':'83','OR':'84','ERROR':'85',
 'STEP':'88','THEN':'8c','COS':'9b','ERL':'9e','ERR':'9f','FALSE':'a3',
 'FN':'a4','INT':'a8','LEN':'a9','NOT':'ac','PI':'af','SIN':'b5',
 'TO':'b8','TRUE':'b9','VAL':'bb','CHR$':'bd','LEFT$(':'c0',
 'MID$(':'c1','RIGHT$(':'c2','STR$':'c3','CASE':'c88e',
 'CIRCLE':'c88f','FILL':'c890','RECTANGLE':'c893','WHILE':'c895',
 'QUIT':'c898','SYS':'c899','WHEN':'c9','OF':'ca','ENDCASE':'cb',
 'ENDIF':'cd','ENDWHILE':'ce','DEF':'dd','DIM':'de','DRAW':'df',
 'END':'e0','ENDPROC':'e1','FOR':'e3','IF':'e7','LOCAL':'ea',
 'MOVE':'ec','NEXT':'ed','ON':'ee','VDU':'ef','PLOT':'f0',
 'PRINT':'f1','PROC':'f2','REM':'f4','REPEAT':'f5','REPORT$':'f624',
 'REPORT':'f6','RETURN':'f8','UNTIL':'fd','OFF':'87'
}
TOKENS = {k:bytes.fromhex(v) for k,v in TOKENS.items()}
KEYWORDS = sorted(TOKENS, key=len, reverse=True)


def tokenise_line(line):
    result = bytearray()
    i = 0
    while i < len(line):
        if line[i] == '"':
            # Preserve quoted text, including doubled quote sequences.
            j = i + 1
            while j < len(line):
                if line[j] == '"':
                    if j+1 < len(line) and line[j+1] == '"':
                        j += 2
                        continue
                    j += 1
                    break
                j += 1
            else:
                raise ValueError('Unterminated string: '+line)
            result.extend(line[i:j].encode('ascii'))
            i = j
        elif line[i] == '&':
            m = re.match(r'&[0-9A-Fa-f]+',line[i:])
            if not m:
                raise ValueError('Bad hexadecimal literal: '+line)
            result.extend(m[0].encode('ascii'))
            i += len(m[0])
        elif line.startswith('ELSE',i):
            result.append(0xcc if line.strip()=='ELSE' else 0x8b)
            i += 4
        elif line[i].isupper():
            for k in KEYWORDS:
                if line.startswith(k,i):
                    result.extend(TOKENS[k])
                    i += len(k)
                    if k in ('REM','DATA'):
                        result.extend(line[i:].encode('ascii'))
                        i = len(line)
                    break
            else:
                raise ValueError('Unknown uppercase keyword: '+line[i:])
        else:
            result.append(ord(line[i]))
            i += 1
    return bytes(result)


def build_basic():
    out = bytearray()
    lines = (APP/'Source').read_text(encoding='ascii').splitlines()
    for number,line in enumerate(lines,1):
        tokenised = tokenise_line(line)
        length = 4+len(tokenised)
        if length > 255:
            raise ValueError(f'BASIC line {number*10} too long')
        out.extend(bytes((13, (number*10)>>8, (number*10)&255, length)))
        out.extend(tokenised)
    out.extend(b'\r\xff')
    (APP/'!RunImage').write_bytes(out)
    return len(lines)



import array
import random
import sys
import json

def soundcode():
    # ARM-state ARMv4-compatible, position independent, 32-bit return.
    # Context: start,end,position,fraction,loop,step at offsets 0..20.
    # SharedSound's helper routines handle mixing, volume and resampling.
    ops=[];labels={};fix=[];listing=[]
    def label(s): labels[s]=len(ops)*4; listing.append(s+':')
    def emit(op,s): ops.append(op);listing.append('    '+s)
    def branch(cond,target):
        fix.append((len(ops),target));emit((cond<<28)|0x0a000000,'B'+{14:'',3:'LO',0:'EQ',2:'HS'}[cond]+' '+target)
    emit(0xe92d5ff7,'STMFD sp!, {r0-r2,r4-r12,lr}')
    emit(0xe1a0c000,'MOV r12,r0')
    emit(0xe59c4008,'LDR r4,[r12,#8]')
    emit(0xe59c5004,'LDR r5,[r12,#4]')
    emit(0xe59c900c,'LDR r9,[r12,#12]')
    emit(0xe59c6014,'LDR r6,[r12,#20]')
    label('loop')
    emit(0xe1540005,'CMP r4,r5');branch(3,'data')
    emit(0xe59ca010,'LDR r10,[r12,#16]')
    emit(0xe35a0000,'CMP r10,#0');branch(0,'silence')
    emit(0xe59c4000,'LDR r4,[r12,#0]')
    emit(0xe3a09000,'MOV r9,#0')
    emit(0xe1540005,'CMP r4,r5');branch(2,'silence')
    label('data')
    emit(0xe1a0e00f,'MOV lr,pc')
    emit(0xe598f008,'LDR pc,[r8,#8]')
    emit(0xe1510002,'CMP r1,r2');branch(3,'loop');branch(14,'finish')
    label('silence')
    emit(0xe1a0e00f,'MOV lr,pc')
    emit(0xe598f004,'LDR pc,[r8,#4]')
    emit(0xe59c4004,'LDR r4,[r12,#4]')
    label('finish')
    emit(0xe58c4008,'STR r4,[r12,#8]')
    emit(0xe58c900c,'STR r9,[r12,#12]')
    emit(0xe1a03000,'MOV r3,r0')
    emit(0xe8bd9ff7,'LDMFD sp!, {r0-r2,r4-r12,pc}')
    for i,target in fix:
        ops[i]|=((labels[target]-(i*4+8))//4)&0xffffff
    (APP/'SoundCode').write_bytes(struct.pack('<'+'I'*len(ops),*ops))
    (ROOT/'SoundARM').write_text('; SharedSound fill callback, assembled by Build\n'+'\n'.join(listing)+'\n')

# Appended to Build by the development step; the delivered Build is standalone.
class Canvas:
    def __init__(self,w,h):self.w=w;self.h=h;self.p=[[None]*w for _ in range(h)]
    def dot(self,x,y,c):
        if 0<=x<self.w and 0<=y<self.h:self.p[y][x]=c
    def rect(self,x0,y0,x1,y1,c):
        for y in range(y0,y1):
            for x in range(x0,x1):self.dot(x,y,c)
    def line(self,x0,y0,x1,y1,c):
        n=max(abs(x1-x0),abs(y1-y0),1)
        for i in range(n+1):self.dot(round(x0+(x1-x0)*i/n),round(y0+(y1-y0)*i/n),c)
    def ellipse(self,x0,y0,x1,y1,c):
        for y in range(y0,y1):
            for x in range(x0,x1):
                if ((x+.5-(x0+x1)/2)/((x1-x0)/2))**2+((y+.5-(y0+y1)/2)/((y1-y0)/2))**2<=1:self.dot(x,y,c)
    def poly(self,points,c):
        for y in range(min(p[1] for p in points),max(p[1] for p in points)+1):
            for x in range(min(p[0] for p in points),max(p[0] for p in points)+1):
                inside=False;j=len(points)-1
                for i in range(len(points)):
                    a,b=points[i],points[j]
                    if (a[1]>y+.5)!=(b[1]>y+.5) and x+.5<(b[0]-a[0])*(y+.5-a[1])/(b[1]-a[1])+a[0]:inside=not inside
                    j=i
                if inside:self.dot(x,y,c)
    def flip(self):
        o=Canvas(self.w,self.h);o.p=[row[::-1] for row in self.p];return o

def sprite_bytes(name,c):
    stride=((c.w*4+31)//32)*4
    image=bytearray(stride*c.h);mask=bytearray(stride*c.h)
    for y,row in enumerate(c.p):
        for x,col in enumerate(row):
            if col is not None:
                off=y*stride+x//2;shift=x%2*4
                image[off]|=col<<shift;mask[off]|=15<<shift
    pal=b''.join(struct.pack('<II',r<<8|g<<16|b<<24,r<<8|g<<16|b<<24) for r,g,b in PALETTE)
    img=44+len(pal);msk=img+len(image);size=msk+len(mask)
    header=struct.pack('<I12s7I',size,name.encode(),stride//4-1,c.h-1,0,(c.w*4-1)%32,img,msk,27)
    return header+pal+image+mask

def area(path,items):
    raw=b''.join(sprite_bytes(name,c) for name,c in items)
    path.write_bytes(struct.pack('<III',len(items),16,16+len(raw))+raw)

PALETTE=[(14,31,48),(26,57,78),(45,83,104),(76,127,147),
         (126,181,198),(177,216,229),(216,237,245),(246,251,251),
         (38,99,153),(55,145,202),(90,201,223),(242,188,74),
         (225,125,54),(206,73,80),(119,74,136),(51,144,123)]

def penguin():
    c=Canvas(32,48)
    c.ellipse(1,40,31,48,3)
    c.ellipse(5,40,15,47,12);c.ellipse(18,40,28,47,12)
    c.ellipse(3,8,29,44,0);c.ellipse(6,0,27,25,0)
    c.ellipse(9,15,25,43,7);c.ellipse(8,7,17,22,7);c.ellipse(17,7,25,22,7)
    c.poly([(4,19),(0,32),(4,35),(9,25)],1)
    c.poly([(27,19),(32,30),(29,34),(24,25)],1)
    c.rect(12,10,14,14,0);c.rect(20,10,22,14,0)
    c.dot(12,10,7);c.dot(20,10,7)
    c.poly([(13,17),(23,17),(18,23)],12)
    c.rect(6,25,27,29,13);c.rect(23,27,27,36,13)
    c.rect(8,25,24,26,11);c.rect(24,35,27,37,11)
    c.rect(12,33,14,35,5);c.rect(12,37,14,39,5)
    return c

def tumble(left=False):
    p=penguin();c=Canvas(48,32)
    for y,row in enumerate(p.p):
        for x,v in enumerate(row):c.dot(47-y,x,v)
    return c.flip() if left else c

def ball(frame):
    c=Canvas(32,32)
    c.ellipse(0,1,32,32,0);c.ellipse(1,0,31,29,8)
    c.ellipse(3,2,27,24,9);c.ellipse(4,3,19,15,10)
    c.ellipse(7,4,13,8,7)
    angle=frame*math.pi/2
    for xx,yy in [(5,1),(0,6),(-3,0)]:
        x=16+round(xx*math.cos(angle)-yy*math.sin(angle))
        y=16+round(xx*math.sin(angle)+yy*math.cos(angle))
        c.ellipse(x-2,y-2,x+2,y+2,0)
    return c

def backdrop():
    c=Canvas(536,236);c.rect(0,0,536,236,2)
    # Ice shelves and a pale polar horizon.
    c.rect(0,0,536,34,3)
    c.poly([(0,33),(36,10),(60,28),(89,3),(133,36),(174,21),(214,45),(0,45)],5)
    c.poly([(310,42),(348,16),(373,34),(409,2),(448,27),(473,12),(536,38),(536,55)],5)
    c.poly([(36,10),(60,28),(48,24),(40,24)],7)
    c.poly([(409,2),(429,17),(414,14),(406,17)],7)
    def project(x,y):return round((560+x*(1.45-y/1000)*2-24)/2),round((650-y*.39-196)/2)
    def quad(x0,x1,col):c.poly([project(x0,0),project(x1,0),project(x1,1000),project(x0,1000)],col)
    quad(-149,149,4);quad(-145,-120,1);quad(120,145,1);quad(-120,120,6)
    for xx in (-118,118):c.line(*project(xx,0),*project(xx,1000),7)
    for xx in (-80,-40,0,40,80):c.line(*project(xx,0),*project(xx,1000),5)
    c.line(*project(-118,105),*project(118,105),9)
    for xx in (-68,-34,0,34,68):
        x,y=project(xx,440);c.poly([(x,y-3),(x-2,y+2),(x+2,y+2)],8)
    # Small frost accents, outside the playing lane.
    rng=random.Random(128)
    for _ in range(40):
        x=rng.randrange(536);y=rng.randrange(70,235)
        if x<75 or x>466:c.rect(x,y,x+2,y+1,3)
    return c

def artwork():
    items=[('arena',backdrop()),('penguin',penguin()),('tumbler',tumble()),('tumblel',tumble(True))]
    items += [(f'ball{n}',ball(n)) for n in range(4)]
    area(APP/'Sprites',items)
    icon=Canvas(34,34);p=penguin()
    for y in range(32):
        for x in range(22):icon.dot(x+2,y,p.p[min(47,y*48//32)][min(31,x*32//22)])
    b=ball(0)
    for y in range(16):
        for x in range(16):
            v=b.p[y*2][x*2]
            if v is not None:icon.dot(x+18,y+18,v)
    area(APP/'!Sprites',[('!pengbowl',icon)])
    return items

def audio():
    sr=11025;bank=bytearray();index=[]
    durations=[1.2,.18,.38,1.3,.85,.65,1.8,.07]
    for name,duration in zip(['Roll','Bowl','Hit','Strike','Spare','Gutter','Finish','Click'],durations):
        rng=random.Random(name);pcm=array.array('h');low=0
        for i in range(int(sr*duration)):
            t=i/sr;white=rng.uniform(-1,1);low=.88*low+.12*white
            envelope=min(1,t/.012)*min(1,(duration-t)/.035)
            if name=='Roll':
                s=.12*low+.055*white*(.6+.4*math.sin(2*math.pi*10*t))
            elif name=='Bowl':s=.28*white*math.exp(-t*17)+.13*math.sin(2*math.pi*(170*t-220*t*t))*math.exp(-t*15)
            elif name=='Hit':
                s=.24*white*math.exp(-t*24)+.16*math.sin(2*math.pi*(620*t-520*t*t))*math.exp(-t*7)
                for at in (.09,.17):
                    if t>at:s+=.15*white*math.exp(-(t-at)*38)
            elif name=='Gutter':s=.17*math.sin(2*math.pi*(330*t-180*t*t))
            elif name=='Click':s=.12*math.sin(2*math.pi*900*t)*math.exp(-t*45)
            else:
                notes={'Strike':[523.25,659.25,783.99,1046.50],
                       'Spare':[523.25,659.25,783.99],
                       'Finish':[523.25,659.25,783.99,659.25,1046.50]}[name]
                n=min(len(notes)-1,int(t/duration*len(notes)));f=notes[n]
                nt=t%(duration/len(notes));gate=min(1,nt/.01)*math.exp(-nt*2)
                s=(.14*math.sin(2*math.pi*f*t)+.035*math.sin(2*math.pi*2*f*t))*gate
            v=int(max(-.9,min(.9,s*envelope))*27000)
            pcm.extend((v,v))
        if sys.byteorder!='little':pcm.byteswap()
        raw=pcm.tobytes();index.append((name,len(bank),len(raw)));bank.extend(raw)
    (APP/'Sounds').write_bytes(bank)
    (ROOT/'SoundIndex').write_text(json.dumps(index,indent=2)+'\n')
    return index

def sources(items,index):
    tail=['REM Generated asset table.','DEF PROCassets','LOCAL i%,name$',
          'DIM sprite%(7),spritew%(7),soundoff%(7),soundlen%(7)',
          'FOR i%=0 TO 7','  READ name$,spritew%(i%)',
          '  SYS "OS_SpriteOp",&118,sprites%,name$ TO ,,sprite%(i%)','NEXT',
          'FOR i%=0 TO 7','  READ soundoff%(i%),soundlen%(i%)','NEXT','ENDPROC',':']
    tail += [f'DATA "{name}",{c.w}' for name,c in items]
    tail += [f'DATA {off},{size}' for name,off,size in index]
    (APP/'Source').write_text((ROOT/'Main').read_text()+'\n'+(ROOT/'Game').read_text()+'\n'+'\n'.join(tail)+'\n')

def make_zip():
    target=ROOT.parent/'PenguinBowl-riscos5.zip,a91'
    stamp=int((datetime.datetime.now(datetime.timezone.utc)-datetime.datetime(1900,1,1,tzinfo=datetime.timezone.utc)).total_seconds()*100)
    types={'OakLogo':0xff9,'!Run':0xfeb,'!Boot':0xfeb,'!RunImage':0xffb,'!Sprites':0xff9,'Sprites':0xff9,'Sounds':0xffd,'SoundCode':0xffd}
    with zipfile.ZipFile(target,'w',zipfile.ZIP_DEFLATED) as z:
        for p in sorted(ROOT.rglob('*')):
            if not p.is_file() or '__pycache__' in p.parts:continue
            zi=zipfile.ZipInfo(p.relative_to(ROOT).as_posix(),datetime.datetime.now().timetuple()[:6])
            zi.create_system=13;zi.compress_type=zipfile.ZIP_DEFLATED
            load=0xfff00000|(types.get(p.name,0xfff)<<8)|((stamp>>32)&255)
            data=struct.pack('<4sIIII',b'ARC0',load,stamp&0xffffffff,0x33,0)
            zi.extra=struct.pack('<HH',0x4341,len(data))+data
            z.writestr(zi,p.read_bytes())
    return target

if __name__=='__main__':
    items=artwork();index=audio();soundcode();sources(items,index);lines=build_basic()
    print(f'{make_zip()}: {lines} BASIC lines; native sprite art and generated sound')

