#!/usr/bin/env python3
"""SPDX-License-Identifier: GPL-2.0-or-later.
Created by Electronics Workbench, 2026-11-19: reproducibly package the TS build
source with replacement icon material, excluding unused legacy distributions.
This is a downstream source package, not the unmodified official archive.
"""
import argparse
import hashlib
from pathlib import Path
import zipfile

UPSTREAM_COMMIT = '8ac55f22a03606579b822b3dccd4dc10de1ddc5b'
UPSTREAM_SHA256 = 'a4ce8ee4a3f969902e4b6041ac76cf43ea536dcb00891b4fa74ce49c0c41d014'
UPSTREAM_ROOT = 'circuitjs1-' + UPSTREAM_COMMIT + '/'
PACKAGE_ROOT = 'circuitjs1-8ac55f22-corresponding-source/'
EXCLUDED_PARTS = {'node_modules', 'dist', '.cache', '__pycache__', '.git'}


def build_package(upstream_archive, resources, output):
    if hashlib.sha256(upstream_archive.read_bytes()).hexdigest() != UPSTREAM_SHA256:
        raise ValueError('Original upstream archive SHA-256 does not match the recorded provenance.')
    files = {}
    with zipfile.ZipFile(upstream_archive) as upstream:
        for member in upstream.infolist():
            if member.is_dir() or not member.filename.startswith(UPSTREAM_ROOT):
                continue
            relative = member.filename[len(UPSTREAM_ROOT):]
            parts = Path(relative).parts
            if '..' in parts or EXCLUDED_PARTS.intersection(parts):
                continue
            if relative not in {'README.md', 'COPYING.txt'} and not relative.startswith('ts/'):
                continue
            if relative.startswith(('ts/public/images/', 'ts/public/circuitjs/font/')):
                continue
            files[relative] = upstream.read(member)

    font_root = resources / 'circuitjs/font'
    if not font_root.is_dir():
        font_root = resources / 'ts/public/circuitjs/font'
    icon_root = resources / 'icon-source'
    if not icon_root.is_dir():
        raise ValueError('Replacement icon generation source is required before packaging.')
    for file in sorted(font_root.rglob('*')):
        if not file.is_file() or file.is_symlink():
            continue
        if file.suffix.lower() not in {'.css', '.json', '.ttf', '.woff', '.woff2', '.txt', '.html'}:
            raise ValueError('Unexpected legacy or undocumented font asset: ' + file.name)
        files['ts/public/circuitjs/font/' + file.relative_to(font_root).as_posix()] = file.read_bytes()
    for file in sorted(icon_root.rglob('*')):
        if not file.is_file() or file.is_symlink() or EXCLUDED_PARTS.intersection(file.relative_to(icon_root).parts):
            continue
        files['icon-source/' + file.relative_to(icon_root).as_posix()] = file.read_bytes()
    runtime_root = resources / 'third-party-source'
    if not (runtime_root / 'lz-string/libs/lz-string.js').is_file():
        raise ValueError('The bundled lz-string runtime readable source is required.')
    for file in sorted(runtime_root.rglob('*')):
        if file.is_file() and not file.is_symlink() and not EXCLUDED_PARTS.intersection(file.relative_to(runtime_root).parts):
            files['third-party-source/' + file.relative_to(runtime_root).as_posix()] = file.read_bytes()
    if not any(name.endswith(('.ttf', '.woff', '.woff2')) for name in files if name.startswith('ts/public/circuitjs/font/')):
        raise ValueError('Generated replacement font files are missing.')
    files['package-source.py'] = Path(__file__).read_bytes()
    files['SOURCE-PACKAGE.txt'] = (
        'Electronics Workbench corresponding source package, 2026-11-19\n'
        'This is a downstream TS-build source subset with replacement icon assets;\n'
        'it is not the unmodified official upstream ZIP.\n'
        'Upstream: https://github.com/pfalstad/circuitjs1\n'
        'Fixed commit: ' + UPSTREAM_COMMIT + '\n'
        'Original official ZIP SHA-256: ' + UPSTREAM_SHA256 + '\n'
        'Original upstream README and GPL COPYING.txt are retained verbatim.\n'
        'Included TS source, lockfile and Vite/TypeScript config are original,\n'
        'including main.ts, UIManager.ts, CircuitElm.ts and style.css. Apply the\n'
        'separately provided deterministic rebuild.py/source patch to them once.\n'
        'The original font directory is replaced by the reviewed/generated icon\n'
        'font and its generation source/attribution under icon-source/.\n'
        'Unused Java/war/cxx/app resources, original custom font binaries and\n'
        'six unused legacy PNGs are excluded. node_modules/dist/cache are excluded.\n'
        'The upstream Vite copy step expects an images directory; rebuild.py\n'
        'creates an empty temporary directory, without distributing old images.\n'
        'Readable lz-string 1.5.0 runtime source and MIT notices are supplied in\n'
        'third-party-source/ and checked against the installed build dependency.\n'
        'Read the accompanying BUILD.txt for the exact build and font commands.\n'
    ).encode('utf-8')
    output.parent.mkdir(parents=True, exist_ok=True)
    with zipfile.ZipFile(output, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
        for relative, content in sorted(files.items()):
            info = zipfile.ZipInfo(PACKAGE_ROOT + relative, date_time=(2026, 11, 19, 0, 0, 0))
            info.compress_type = zipfile.ZIP_DEFLATED
            info.external_attr = 0o100644 << 16
            archive.writestr(info, content, compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)
    return len(files)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--upstream-source', type=Path, required=True)
    parser.add_argument('--resources', type=Path, default=Path(__file__).resolve().parent)
    parser.add_argument('--output', type=Path, required=True)
    args = parser.parse_args()
    count = build_package(args.upstream_source.resolve(), args.resources.resolve(), args.output.resolve())
    print('Packaged', count, 'files; SHA-256', hashlib.sha256(args.output.read_bytes()).hexdigest())


if __name__ == '__main__':
    main()
