#!/usr/bin/env python3
"""Build the tokenised BASIC application, native sprite and RISC OS ZIP.
Python 3 with Pillow for artwork; the ready-built app has no such dependency. 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 hashlib
import math
import re
import struct
import zipfile
import shutil
from types import SimpleNamespace

ROOT = Path(__file__).resolve().parent
DIST = ROOT.parent.parent
APP = DIST / '!Xmas26'
# 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 = {
 'OSCLI':'ff','CALL':'d6','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] in 'ABCDEFGH' and line[i+1:i+2]=='%':
            result.append(ord(line[i])); i+=1
        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(text):
    out = bytearray()
    lines = text.splitlines()
    for number,line in enumerate(lines,1):
        tokenised = tokenise_line(line)
        length = 4+len(tokenised)
        if length > 255 or number*5>65279:
            raise ValueError(f'BASIC line {number*5} too long or program too large')
        out.extend(bytes((13, (number*5)>>8, (number*5)&255, length)))
        out.extend(tokenised)
    out.extend(b'\r\xff')
    (APP/'!RunImage').write_bytes(out)
    return len(lines)


import runpy, json, bisect

def path_points():
    raw=[(204+105*math.cos(i*math.tau/4096),337+30*math.sin(i*math.tau/4096)) for i in range(4097)]
    arc=[0]
    for a,b in zip(raw,raw[1:]):arc.append(arc[-1]+math.hypot(b[0]-a[0],b[1]-a[1]))
    points=[]
    for i in range(256):
        distance=arc[-1]*i/256;j=max(0,bisect.bisect_right(arc,distance)-1);part=(distance-arc[j])/(arc[j+1]-arc[j])
        theta=(j+part)*math.tau/4096
        x=204+105*math.cos(theta);y=337+30*math.sin(theta)
        angle=math.atan2(math.cos(theta),-math.sin(theta))%math.tau
        points.append((x,y,round(angle*64/math.tau)%64))
    return arc[-1],points

def sources(assets,groups,lights,streams):
    pathlength,path=path_points()
    out=['REM Generated assets and geometry. Edit Art, Score, Main, Music or Timing.',
         'DEF PROCassets','LOCAL i%,name$',
         f'DIM sprite%({len(assets)-1}),spritew%({len(assets)-1}),spriteh%({len(assets)-1})',
         'DIM lightx%(29),lighty%(29),lightcolour%(29),lightphase%(29),lightperiod%(29)',
         'DIM pathx(255),pathy(255),pathdir%(255)']
    out += [f'{name}base%={value}' for name,value in groups.items()]
    out += [f'pathlength={pathlength:.9f}',f'FOR i%=0 TO {len(assets)-1}',
            '  READ name$,spritew%(i%),spriteh%(i%)',
            '  SYS "OS_SpriteOp",&118,sprites%,name$ TO ,,sprite%(i%)','NEXT',
            'FOR i%=0 TO 29:READ lightx%(i%),lighty%(i%),lightcolour%(i%),lightphase%(i%),lightperiod%(i%):NEXT',
            'FOR i%=0 TO 255:READ pathx(i%),pathy(i%),pathdir%(i%):NEXT','ENDPROC',':',
            'DEF PROCscoredata','LOCAL i%,c%,bytes%',
            'SYS "OS_File",5,"<Xmas26$Dir>.Carols" TO ,,,,bytes%',
            'DIM bank% bytes%-1',
            'SYS "OS_File",255,"<Xmas26$Dir>.Carols",bank%,0',
            'IF !bank%<>&4D363258 OR bank%!4<>1 THEN ERROR 1,"Invalid carol bank"',
            'songcount%=bank%!8',
            'IF songcount%<>46 OR bytes%<>16+bank%!12*12 THEN ERROR 1,"Incomplete carol bank"',
            'notebank%=bank%+16',
            'DIM songtitle$(songcount%-1),songlength%(songcount%-1),songbase%(songcount%-1,2),songnotes%(songcount%-1,2)',
            'FOR i%=0 TO songcount%-1',
            '  READ songtitle$(i%),songlength%(i%)',
            '  FOR c%=0 TO 2:READ songbase%(i%,c%),songnotes%(i%,c%):NEXT',
            'NEXT','ENDPROC',':']
    out += [f'DATA "{name}",{im.width},{im.height}' for name,im in assets]
    out += ['DATA '+','.join(map(str,row)) for row in lights]
    out += [f'DATA {x:.6f},{y:.6f},{d}' for x,y,d in path]
    for song in streams:
        values=[song['duration_cs']]
        for base,count in zip(song['bases'],song['counts']):values += [base,count]
        out.append('DATA "'+song['title']+'",'+','.join(map(str,values)))
    text='\n'.join((ROOT/p).read_text().rstrip() for p in ('Main','Music','Timing','Lighting','Surprises','Eggs','Santa','NightSanta','DailyElf','Dog','Interactions','LampParty','Effects','FestiveExtras','Cupboard','RoomDetail','Game','Playlist','CarolUI','LicenseUI','View','Tracker','DJMix','Media','Karaoke','HiRes'))+'\n'+ '\n'.join(out)+'\n'

    meta=json.loads((ROOT/'Geometry').read_text());meta.update(pathlength=pathlength,path=path)
    (ROOT/'Geometry').write_text(json.dumps(meta,indent=2)+'\n')

    return text

def assembled_source():
    geometry=json.loads((ROOT/'Geometry').read_text())
    assets=[(name,SimpleNamespace(width=w,height=h)) for name,w,h in geometry['sprites']]
    music=json.loads((ROOT/'MusicData').read_text())
    return sources(assets,geometry['groups'],geometry['lights'],music['songs'])

def make_zip():
    if DIST.name=='!Xmas26':
        raise ValueError('Use the Build file in the outer Docs/build directory.')
    # The Filer Help action and the outer ReadMe always present identical text.
    shutil.copyfile(DIST/'ReadMe',APP/'!Help')
    mirror=APP/'Docs'
    if mirror.exists():
        shutil.rmtree(mirror)
    shutil.copytree(ROOT.parent,mirror,ignore=shutil.ignore_patterns('Manifest','__pycache__','*.pyc'))

    # Refresh the transparent file inventory for every packaged build.
    manifest=ROOT/'Manifest'
    entries=[]
    for p in sorted(DIST.rglob('*')):
        if not p.is_file() or p==manifest or '__pycache__' in p.parts or any(x.startswith('.') for x in p.relative_to(DIST).parts):continue
        entries.append(hashlib.sha256(p.read_bytes()).hexdigest()+'  '+p.relative_to(DIST).as_posix())
    manifest.write_text('SHA-256 inventory; excludes this file. This is not a digital signature.\n'+'\n'.join(entries)+'\n')
    target=DIST.parent/'Xmas26-v2.52-beta-riscos5.zip,a91'
    now=datetime.datetime.now(datetime.timezone.utc)
    stamp=int((now-datetime.datetime(1900,1,1,tzinfo=datetime.timezone.utc)).total_seconds()*100)
    types={'OpenScores':0xa91,'OakLogo':0xff9,'!Run':0xfeb,'!Boot':0xfeb,'!RunImage':0xffb,'!Sprites':0xff9,'Sprites':0xff9,'Carols':0xffd,'Lyrics':0xffd,'NoteView':0xffd,'KaraScore':0xffd,'NeonMOD':0xcb6,'NeonDTT':0xcb6,'QTMModule':0xffa,'Index':0xffd,'SampleBank':0xffd,'FXBank':0xffd,'FXCode':0xffd,'SourcePDF':0xadf}
    temporary=target.with_name(target.name+'.tmp')
    with zipfile.ZipFile(temporary,'w',zipfile.ZIP_DEFLATED) as z:
        for p in sorted(DIST.rglob('*')):
            if not p.is_file() or '__pycache__' in p.parts or any(x.startswith('.') for x in p.relative_to(DIST).parts):continue
            zi=zipfile.ZipInfo(p.relative_to(DIST).as_posix(),now.timetuple()[:6]);zi.create_system=13;zi.compress_type=zipfile.ZIP_DEFLATED
            load=0xfff00000|((0xaf1 if p.parent.name in ('Maestros','MaestrosPluck') and p.name!='ReadMe' else (0xcb6 if p.parent.name in ('Chill','Dance','Class','Trance') and p.name.startswith('C') else 0xffd if p.parent.name in ('Chill','Dance','Class','Trance') and p.name.startswith('M') else 0xcb6 if p.name=='DJDeck' else 0xffd if p.parent.name=='Mix' and p.name.startswith('J') else types.get(p.name,0xfff)))<<8)|((stamp>>32)&255)
            extra=struct.pack('<4sIIII',b'ARC0',load,stamp&0xffffffff,0x33,0)
            zi.extra=struct.pack('<HH',0x4341,len(extra))+extra;z.writestr(zi,p.read_bytes())
    temporary.replace(target)
    return target

if __name__=='__main__':
    if DIST.name=='!Xmas26':
        raise SystemExit('Run the Build file in the outer Docs/build directory of the full release.')

    for outer,inner in [('MusicSources','MusicSrc'),('AppSources','AppSrc')]:
        (APP/inner).write_bytes((ROOT/outer).read_bytes())
    (APP/'Licences').write_bytes((DIST/'Docs/Licences'/'Overview').read_bytes())
    runpy.run_path(str(ROOT/'Shchedryk'))['build'](ROOT)
    assets,groups,lights,palette=runpy.run_path(str(ROOT/'Art'))['build_art'](ROOT)
    runpy.run_path(str(ROOT/'JingleMake'))['build'](ROOT)
    runpy.run_path(str(ROOT/'TwelveFull'))['build'](ROOT)
    runpy.run_path(str(ROOT/'AdditionalCarols'))['build'](ROOT)
    streams=runpy.run_path(str(ROOT/'Score'))['build_score'](ROOT)
    runpy.run_path(str(ROOT/'BuildTrackers'))['build'](ROOT)
    runpy.run_path(str(ROOT/'BuildDJ'))['build']()
    runpy.run_path(str(ROOT/'Medley'))['build'](ROOT)
    runpy.run_path(str(ROOT/'BuildMedia'))['build'](ROOT)
    runpy.run_path(str(ROOT/'BuildKara'))['build'](ROOT)
    runpy.run_path(str(ROOT/'BuildEffects'))['build'](ROOT)
    lines=build_basic(sources(assets,groups,lights,streams))
    runpy.run_path(str(ROOT/'SongList'))['build'](ROOT)
    runpy.run_path(str(ROOT/'LyricFiles'))['build'](ROOT)
    runpy.run_path(str(ROOT/'Engrave'))['build'](ROOT)
    runpy.run_path(str(ROOT/'CheckScores'))['run']()
    runpy.run_path(str(ROOT/'CheckRights'))['check'](ROOT)
    print(f'{make_zip()}: {lines} BASIC lines; {len(assets)} native sprites; 46-song year-round playlist')
