#!/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 / '!Answers'
# 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 = {
 '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)


# The bundle contains generated audio; --speech regenerates it using FFmpeg's
# Flite synthesizer. Normal builds use only the Python 3 standard library.
import array
import json
import random
import subprocess
import sys
import tempfile
from concurrent.futures import ThreadPoolExecutor

GROUPS = {
 'phrases':['','O','Thy','Beneath the','My','Behold the','And file it in triplicate.'],
 'adjectives':['moist','wobbly','bureaucratic','gelatinous','lukewarm','crusty','indignant','mouldering','soggy','verbose','pickled','squamous','dribbling','unnecessary'],
 'nouns':['sludge','paperwork','mucus','custard','armpit','teapot','bureaucrat','spleen','doormat','fungus','trumpet','galosh','bladder','pudding'],
 'verbs':['gurgles','oozes','wobbles','squats','ferments','quivers','squelches','dribbles'],
 'adverbs':['dismally','sideways','forever','politely','bureaucratically','damply','inconveniently']
}
WORDS = sum(GROUPS.values(), [])

def speech():
    def clip(item):
        i,word=item
        if i==0:
            return b'\0'*(int(11025*.32)*4)
        with tempfile.TemporaryDirectory() as tmp:
            text=Path(tmp)/'text'; out=Path(tmp)/'audio'
            text.write_text('Oh' if word=='O' else word)
            subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-f','lavfi','-i',f'flite=textfile={text}:voice=kal',
                            '-ar','11025','-ac','2','-f','s16le','-y',str(out)],check=True)
            data=out.read_bytes()
        # Remove lengthy per-word silence, keeping a small articulation margin.
        pcm=array.array('h');pcm.frombytes(data)
        if sys.byteorder!='little':pcm.byteswap()
        frames=len(pcm)//2
        active=[j for j in range(frames) if abs(pcm[2*j])>100]
        if active:
            lo=max(0,active[0]-160);hi=min(frames,active[-1]+220)
            data=data[lo*4:hi*4]
        return data+b'\0'*440
    with ThreadPoolExecutor(max_workers=4) as pool:
        clips=list(pool.map(clip,enumerate(WORDS)))
    bank=bytearray(); idx=[]
    for text,clipdata in zip(WORDS,clips):
        idx.append([text,len(bank),len(clipdata)]);bank.extend(clipdata)
    (APP/'Voice').write_bytes(bank)
    (ROOT/'VoiceIndex').write_text(json.dumps(idx,indent=2)+'\n')
    print(f'Speech bank: {len(idx)} fragments, {len(bank)} bytes')

def dictionary_source():
    idx=json.loads((ROOT/'VoiceIndex').read_text())
    adj=len(GROUPS['phrases']); noun=adj+len(GROUPS['adjectives'])
    verb=noun+len(GROUPS['nouns']); adv=verb+len(GROUPS['verbs'])
    base=(APP/'Source').read_text().split('REM Generated speech dictionary')[0]
    tail=['REM Generated speech dictionary - offsets into Voice (11025 Hz stereo PCM).',
          'DEF PROCwords',f'DIM word$({len(idx)-1}),offset%({len(idx)-1}),length%({len(idx)-1})',
          'oh%=1:thy%=2:beneath%=3:my%=4:behold%=5:final%=6',
          f'adj%={adj}:nadj%={len(GROUPS["adjectives"])}:noun%={noun}:nnoun%={len(GROUPS["nouns"])}',
          f'verb%={verb}:nverb%={len(GROUPS["verbs"])}:adv%={adv}:nadv%={len(GROUPS["adverbs"])}',
          f'FOR i%=0 TO {len(idx)-1}', '  READ word$(i%),offset%(i%),length%(i%)','NEXT','ENDPROC',':']
    tail.extend(f'DATA "{text}",{offset},{length}' for text,offset,length in idx)
    (APP/'Source').write_text(base+'\n'.join(tail)+'\n')

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')

def rain():
    # Procedural filtered noise with soft droplets, then a seamless crossfade.
    rng=random.Random(424242);sr=11025;n=sr*8;overlap=1102
    tracks=[]
    for channel in range(2):
        low=0.;drop=0.;wave=[]
        for i in range(n+overlap):
            white=rng.uniform(-1,1)
            low=.90*low+.10*white
            if rng.random()<.0009:drop=rng.uniform(.15,.55)
            drop*=.965
            gust=.7+.18*math.sin(i/sr*.8+channel*.5)
            sample=(.45*white+.95*low)*gust+drop*white
            wave.append(int(max(-16000,min(16000,sample*10500))))
        blended=[int(wave[n+j]*(1-j/overlap)+wave[j]*(j/overlap)) for j in range(overlap)]
        tracks.append(wave[overlap:n]+blended)
    out=array.array('h')
    for a,b in zip(*tracks):out.extend((a,b))
    if sys.byteorder!='little':out.byteswap()
    (APP/'Rain').write_bytes(out.tobytes())

def sprite():
    # Native old-style 4 bpp sprite: a folded pale towel on a chrome rail.
    w=h=34;stride=20
    pal=[(255,255,255),(235,245,250),(207,225,233),(165,194,207),
         (111,145,160),(50,83,104),(26,50,70),(9,24,36),
         (27,110,176),(54,158,202),(107,198,216),(179,230,235),
         (192,200,206),(129,141,151),(71,83,95),(224,188,99)]
    pixels=[[None]*w for _ in range(h)]
    def rect(x0,y0,x1,y1,c):
        for y in range(y0,y1):
            for x in range(x0,x1):pixels[y][x]=c
    rect(2,8,5,15,14);rect(29,8,32,15,14)
    rect(3,9,31,13,13);rect(3,9,31,10,0);rect(3,10,31,11,12)
    rect(10,11,26,31,5);rect(9,10,25,30,3)
    rect(8,9,23,29,1);rect(8,9,23,11,0)
    rect(9,12,22,14,2);rect(21,11,23,27,2)
    rect(9,25,22,27,8);rect(9,27,22,28,10)
    rect(11,15,12,24,0);rect(18,15,19,24,2)
    image=bytearray(stride*h);mask=bytearray(stride*h)
    for y in range(h):
        for x in range(w):
            c=pixels[y][x]
            if c is not None:
                off=y*stride+x//2;shift=x%2*4
                image[off]|=c<<shift;mask[off]|=15<<shift
    palette=b''.join(struct.pack('<II',r<<8|g<<16|b<<24,r<<8|g<<16|b<<24) for r,g,b in pal)
    img=44+len(palette);msk=img+len(image);size=msk+len(mask)
    header=struct.pack('<I12s7I',size,b'!answers',stride//4-1,h-1,0,7,img,msk,27)
    (APP/'!Sprites').write_bytes(struct.pack('<III',1,16,16+size)+header+palette+image+mask)
    # Diagnostic preview outside the distributable tree.
    rgb=bytes(v for row in pixels for c in row for v in (pal[c] if c is not None else (236,236,236)))
    (ROOT.parent/'Answers-towel.ppm').write_bytes(b'P6\n34 34\n255\n'+rgb)

def make_zip():
    target=ROOT.parent/'Answers-riscos5.zip'
    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,'SoundCode':0xffd,'Voice':0xffd,'Rain':0xffd}
    with zipfile.ZipFile(target,'w',zipfile.ZIP_DEFLATED) as z:
        for p in sorted(ROOT.rglob('*')):
            if not p.is_file():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)
            metadata=struct.pack('<4sIIII',b'ARC0',load,stamp&0xffffffff,0x33,0)
            zi.extra=struct.pack('<HH',0x4341,len(metadata))+metadata
            z.writestr(zi,p.read_bytes())
    return target

if __name__=='__main__':
    if '--speech' in sys.argv or not (APP/'Voice').exists():speech()
    dictionary_source();lines=build_basic();soundcode();rain();sprite()
    print(f'{make_zip()}: {lines} BASIC lines; native sprites and sound callback')
