#!/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 / '!DualClock'
# 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 = {
 '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()}
WORDS = 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 WORDS:
                if line.startswith(k,i):
                    result.extend(TOKENS[k])
                    i += len(k)
                    if k == 'REM':
                        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)


def build_sprite():
    # Old-format 4 bpp mode 27 (90 dpi), 34 x 34 pixels, explicit palette,
    # and a matching 4 bpp transparency mask. Rows are top to bottom.
    w = h = 34
    stride = 20
    palette = [(255,255,255),(221,221,221),(187,187,187),(153,153,153),
               (119,119,119),(85,85,85),(51,51,51),(0,0,0),
               (0,68,153),(238,238,204),(0,170,0),(221,0,0),
               (238,221,187),(0,119,0),(255,187,0),(0,187,255)]
    image, mask = bytearray(stride*h),bytearray(stride*h)
    def line_distance(x,y,x1,y1,x2,y2):
        t=max(0,min(1,((x-x1)*(x2-x1)+(y-y1)*(y2-y1))/((x2-x1)**2+(y2-y1)**2)))
        return math.hypot(x-x1-t*(x2-x1),y-y1-t*(y2-y1))
    for y in range(h):
        for x in range(w):
            dx=x-16.5;dy=y-16.5;r=math.hypot(dx,dy)
            if r>16:
                continue
            c=8 if r>14.2 else 0
            if r<13.7 and r>11.6:
                a=math.atan2(dx,-dy)
                if abs(math.sin(a*6))<0.18:
                    c=7
            if line_distance(x,y,16.5,16.5,11,10)<0.9 or line_distance(x,y,16.5,16.5,24,12)<0.7:
                c=7
            if line_distance(x,y,16.5,16.5,19,27)<0.45 or r<1.5:
                c=11
            offset=y*stride+x//2;shift=(x%2)*4
            image[offset]|=c<<shift
            mask[offset]|=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)
    image_offset=44+len(pal)
    mask_offset=image_offset+len(image)
    sprite_size=mask_offset+len(mask)
    header=struct.pack('<I12s7I',sprite_size,b'!dualclock',stride//4-1,h-1,0,7,image_offset,mask_offset,27)
    area=struct.pack('<III',1,16,16+sprite_size)
    (APP/'!Sprites').write_bytes(area+header+pal+image+mask)


def make_zip():
    target=ROOT.parent/'DualClock-riscos5.zip,a91'
    # Date stamped RISC OS load/exec words: 40-bit centiseconds since 1900.
    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}
    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
            path=p.relative_to(ROOT).as_posix()
            zi=zipfile.ZipInfo(path,datetime.datetime.now().timetuple()[:6])
            zi.create_system=13  # Acorn RISC OS
            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__':
    lines=build_basic()
    build_sprite()
    target=make_zip()
    print(f'{target}: {lines} BASIC lines, tokenised program, native sprite, Acorn filetype metadata')
