#!/usr/bin/env python3
"""Build the standalone, decoder-only minimp3 module with Emscripten 4.0.10.
python3 scripts/audio/build-mp3.py --emsdk /path/to/emsdk
No source modifications; project bridge is mp3.c. Source files are vendored.
"""
import argparse, hashlib, json, os, re, subprocess
from pathlib import Path
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--emsdk', required=True)
a = p.parse_args()
root = Path(__file__).resolve().parents[2]
record = root / 'third_party/audio-codecs'
raw = subprocess.check_output(['bash', '-c', 'source "$1/emsdk_env.sh" >/dev/null 2>&1; env -0', 'bash', str(Path(a.emsdk).resolve())])
env = dict(x.decode().split('=', 1) for x in raw.split(b'\0') if x)
version = subprocess.check_output(['emcc', '--version'], env=env, text=True)
if not re.search(r'\b4\.0\.10\b', version): raise SystemExit('Emscripten 4.0.10 required')
source = record / 'minimp3'
pin = json.loads((record / 'minimp3-source.json').read_text())
for f, expected in pin['files'].items():
    if hashlib.sha256((source / f).read_bytes()).hexdigest() != expected: raise SystemExit('Source changed: ' + f)
out = record / 'core/mp3-core.js'
command = ['emcc', 'scripts/audio/mp3.c', '-Ithird_party/audio-codecs/minimp3', '-O2',
 '-sMODULARIZE=1', '-sEXPORT_ES6=1', '-sENVIRONMENT=web,worker', '-sFILESYSTEM=0',
 '-sALLOW_MEMORY_GROWTH=1', '-sMAXIMUM_MEMORY=67108864', '-sINITIAL_MEMORY=16777216',
 '-sSTACK_SIZE=1048576', '-sABORTING_MALLOC=0', '-sEXPORTED_FUNCTIONS=["_malloc","_free"]',
 '-sEXPORTED_RUNTIME_METHODS=["HEAPU8","HEAPF32"]',
 '-Wl,-Map=third_party/audio-codecs/core/mp3-core.map', '--no-entry', '-o', str(out.relative_to(root))]
subprocess.run(command, cwd=root, env=env, check=True)
files = ['scripts/audio/mp3.c', 'scripts/audio/build-mp3.py', 'third_party/audio-codecs/minimp3-source.json',
 *['third_party/audio-codecs/core/mp3-core.' + ext for ext in ['js', 'wasm', 'map']]]
manifest = {'emscripten': '4.0.10', 'revision': pin['revision'], 'license': 'CC0-1.0',
 'maximumMemory': 67108864, 'command': command, 'compilerVersion': version.strip(),
 'files': {f: {'sha256': hashlib.sha256((root/f).read_bytes()).hexdigest(), 'bytes': (root/f).stat().st_size} for f in files}}
(record / 'mp3-build.json').write_text(json.dumps(manifest, indent=2) + '\n')
