"""Rebuild the application payload using the original 3.8.7 Windows EXE.

Run with CPython 3.12: python build/rebuild.py ORIGINAL_EXE BoltStudio387.exe
The Windows bootloader and third-party dependencies come from the original.
"""
import importlib.util
import marshal
import struct
import sys
import zlib
from pathlib import Path

COOKIE = struct.Struct('!8sIIII64s')
TOC = struct.Struct('!IIIIBc')
MAGIC = b'MEI\x0c\x0b\x0a\x0b\x0e'


def compile_module(path):
    return marshal.dumps(compile(path.read_bytes(), path.name, 'exec',
                                 dont_inherit=True, optimize=0))


def read_archive(exe):
    end = exe.rindex(MAGIC)
    magic, length, toc_off, toc_len, version, dll = COOKIE.unpack_from(exe, end)
    base = end + COOKIE.size - length
    assert end + COOKIE.size == len(exe) and version == 312
    assert magic == MAGIC and dll.rstrip(b'\0') == b'python312.dll'
    cursor = base + toc_off
    entries = []
    while cursor < base + toc_off + toc_len:
        size, offset, packed, unpacked, compressed, kind = TOC.unpack_from(exe, cursor)
        name = exe[cursor + TOC.size:cursor + size].split(b'\0', 1)[0]
        entries.append((name, exe[base + offset:base + offset + packed],
                        unpacked, compressed, kind))
        cursor += size
    assert cursor == base + toc_off + toc_len
    return exe[:base], entries, dll


def read_pyz(pyz):
    assert pyz[:8] == b'PYZ\0' + importlib.util.MAGIC_NUMBER
    offset = struct.unpack_from('!I', pyz, 8)[0]
    return marshal.loads(pyz[offset:])


def rebuild_pyz(pyz, modules):
    payload = bytearray(pyz[:17])
    toc = []
    for name, (kind, start, length) in read_pyz(pyz):
        if name in modules:
            continue
        toc.append((name, (kind, len(payload), length)))
        payload.extend(pyz[start:start + length])
    for name, code in sorted(modules.items()):
        packed = zlib.compress(code, 9)
        toc.append((name, (0, len(payload), len(packed))))
        payload.extend(packed)
    struct.pack_into('!I', payload, 8, len(payload))
    payload.extend(marshal.dumps(toc))
    return bytes(payload)


def write_archive(bootloader, entries, dll):
    payload = bytearray()
    toc = bytearray()
    for name, packed, unpacked, compressed, kind in entries:
        padded = (TOC.size + len(name) + 16) // 16 * 16
        toc.extend(TOC.pack(padded, len(payload), len(packed), unpacked, compressed, kind))
        toc.extend(name.ljust(padded - TOC.size, b'\0'))
        payload.extend(packed)
    cookie = COOKIE.pack(MAGIC, len(payload) + len(toc) + COOKIE.size,
                         len(payload), len(toc), 312, dll)
    return bootloader + payload + toc + cookie


def main(original, output):
    assert sys.version_info[:2] == (3, 12), 'Use CPython 3.12'
    build_dir = Path(__file__).resolve().parent
    sources = build_dir.parent / 'source387'
    modules = {path.stem: compile_module(path) for path in sources.glob('*.py')}
    assert len(modules) == 19 and 'app' in modules
    bootloader, entries, dll = read_archive(original.read_bytes())
    scripts = {b'app': compile_module(build_dir / 'boltstudio_launcher.py'),
               b'qt_runtime': compile_module(build_dir / 'qt_runtime.py')}
    rebuilt = []
    for name, packed, unpacked, compressed, kind in entries:
        if name in scripts:
            unpacked, packed, compressed = len(scripts[name]), zlib.compress(scripts[name], 9), 1
        elif kind == b'z':
            packed = rebuild_pyz(packed, modules)
            unpacked = len(packed)
        rebuilt.append((name, packed, unpacked, compressed, kind))
    output.write_bytes(write_archive(bootloader, rebuilt, dll))
    actual_bootloader, actual, actual_dll = read_archive(output.read_bytes())
    assert actual_bootloader == bootloader and actual == rebuilt and actual_dll == dll
    pyz, = (data for _, data, _, _, kind in actual if kind == b'z')
    toc = dict(read_pyz(pyz))
    for name, expected in modules.items():
        kind, offset, length = toc[name]
        assert kind == 0 and zlib.decompress(pyz[offset:offset + length]) == expected, name
    print(f'Windows x64 EXE rebuilt and verified against {len(modules)} source modules.')


if __name__ == '__main__':
    if len(sys.argv) != 3:
        raise SystemExit(__doc__)
    main(Path(sys.argv[1]), Path(sys.argv[2]))
