"""Build the four pocket players. Requires an activated Emscripten SDK."""
from pathlib import Path
import subprocess,os
ROOT=Path(__file__).resolve().parents[2];BUILD=ROOT/'artifacts/console-build';UP=BUILD/'upstream'
def run(args,cwd):
 args=[str(a.relative_to(ROOT)) if isinstance(a,Path) and a.is_absolute() and cwd==ROOT else str(a) for a in args]
 subprocess.run(args,cwd=cwd,check=True)
p=UP/'binjgb'
run([os.environ.get('EMCC','emcc'),*[p/f'src/{name}.c' for name in ['memory','common','emulator','joypad','rewind']],p/'src/emscripten/wrapper.c','-I',p/'src','-O3','-s','EXPORTED_FUNCTIONS=@'+str((p/'src/emscripten/exported.json').relative_to(ROOT)),'-s','EXPORTED_RUNTIME_METHODS=["HEAP8","HEAPU8"]','-s','MODULARIZE=1','-s','EXPORT_NAME=Binjgb','-s','ENVIRONMENT=web','-s','FILESYSTEM=0','-o',BUILD/'binjgb.js'],ROOT)
gbdk=Path(os.environ.get('GBDK',str(UP/'gbdk-tools/gbdk')));lcc=gbdk/'bin/lcc';p=UP/'gbcorp'
for name in ['gbcorp','music']:run([lcc,'-Wa-l','-Wl-m','-Wl-j','-c','-o',name+'.o',name+'.c'],p)
for name in ['gbt_player','gbt_player_bank1']:run([gbdk/'bin/sdasgb','-plosgff','-Ilibc','-o',name+'.o',name+'.s'],p)
run([lcc,'-Wl-yt0x1B','-Wl-yo2','-Wl-ya1','-Wm-ynGB-Corp','-Wm-ys','-Wm-yc','-o','gbcorp.gb','gbcorp.o','music.o','gbt_player.o','gbt_player_bank1.o'],p)
p=UP/'squishy';(p/'processed').mkdir(exist_ok=True)
for name,bank in {'base_sprites':1,'base_tiles':1,'title_tiles':4,'world_0':2,'title_screens':4}.items():
 text=(p/'graphics'/f'{name}.z80').read_text();text='\n'.join(line for line in text.splitlines() if 'equ' not in line and 'end' not in line).replace('.byte','.db').replace('$','0x')
 (p/'processed'/f'{name}.s').write_text(f'.area _CODE_{bank}\n.globl _{name}\n'+text+'\n')
run(['make','CC='+str(lcc)],p)
print('Pocket ROMs and emulator built locally.')
