#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Original isolated feasibility build; never modifies sibling codec sources.

import argparse
import hashlib
import json
import os
from pathlib import Path
import shlex
import subprocess
import tarfile
import urllib.request

ROOT = Path(__file__).resolve().parent
PINS = json.loads((ROOT / "pins.json").read_text())
COMMANDS = []
PNG_SOURCES = [
    "png.c", "pngerror.c", "pngget.c", "pngmem.c", "pngpread.c", "pngread.c",
    "pngrio.c", "pngrtran.c", "pngrutil.c", "pngset.c", "pngtrans.c", "pngwio.c",
    "pngwrite.c", "pngwtran.c", "pngwutil.c",
]
ZLIB_SOURCES = [
    "adler32.c", "compress.c", "crc32.c", "deflate.c", "gzclose.c", "gzlib.c",
    "gzread.c", "gzwrite.c", "infback.c", "inffast.c", "inflate.c", "inftrees.c",
    "trees.c", "uncompr.c", "zutil.c",
]


def digest(path, algorithm="sha256"):
    value = hashlib.new(algorithm)
    with path.open("rb") as source:
        for block in iter(lambda: source.read(1024 * 1024), b""):
            value.update(block)
    return value.hexdigest()


def require_hash(path, expected, algorithm="sha256"):
    if not path.is_file() or digest(path, algorithm) != expected:
        raise RuntimeError(f"Pinned {algorithm} input missing or changed: {path}")


def check_archive_source(archive, destination, override=None):
    with tarfile.open(archive, "r:gz") as bundle:
        for member in bundle.getmembers():
            if not member.isfile():
                continue
            path = destination / member.name
            if override is not None and path == override:
                continue
            with bundle.extractfile(member) as source:
                expected = hashlib.sha256(source.read()).hexdigest()
            require_hash(path, expected)


def acquire_port(pin):
    downloads = ROOT / "work/downloads"
    downloads.mkdir(parents=True, exist_ok=True)
    archive = downloads / pin["archive"]
    if not archive.exists():
        cached = ROOT / pin["cachedArchive"]
        partial = archive.with_suffix(archive.suffix + ".part")
        try:
            if cached.is_file():
                require_hash(cached, pin["sha512"], "sha512")
                partial.write_bytes(cached.read_bytes())
            else:
                # Codec source acquisition only. No image upload/download path.
                with urllib.request.urlopen(pin["sourceUrl"]) as response, partial.open("wb") as output:
                    for block in iter(lambda: response.read(1024 * 1024), b""):
                        output.write(block)
            require_hash(partial, pin["sha512"], "sha512")
            partial.replace(archive)
        finally:
            partial.unlink(missing_ok=True)
    require_hash(archive, pin["sha512"], "sha512")
    require_hash(archive, pin["sha256"])
    destination = ROOT / "work/sources"
    destination.mkdir(parents=True, exist_ok=True)
    source = destination / pin["archiveRoot"]
    configuration = ROOT / pin["configurationSource"]
    require_hash(configuration, pin["configurationSha256"])
    require_hash(ROOT / pin["portRecipe"], pin["portRecipeSha256"])
    local_header = source / pin["configurationHeader"]
    if not source.exists():
        with tarfile.open(archive, "r:gz") as bundle:
            bundle.extractall(destination, filter="data")
        # Same sole configuration-header overlay as the pinned Emscripten port.
        local_header.write_bytes(configuration.read_bytes())
    check_archive_source(archive, destination, override=local_header)
    require_hash(local_header, pin["configurationSha256"])
    return source


def check_mozjpeg():
    pin = PINS["mozjpeg"]
    archive = ROOT / pin["archivePath"]
    require_hash(archive, pin["sha256"])
    source = ROOT / pin["sourcePath"]
    check_archive_source(archive, source.parent)
    for relative, expected in pin["readonlyInputSha256"].items():
        require_hash(ROOT / relative, expected)
    return source, ROOT / pin["buildPath"], ROOT / pin["libraryPath"]


def command(args, environment):
    values = [str(arg) for arg in args]
    COMMANDS.append(values)
    print(shlex.join(values), flush=True)
    subprocess.run(values, cwd=ROOT, env=environment, check=True)


def compile_archive(name, source, filenames, includes, emcc, emar, environment):
    build = ROOT / "work/build" / name
    build.mkdir(parents=True, exist_ok=True)
    objects = []
    for filename in filenames:
        output = build / (Path(filename).stem + ".o")
        command([emcc, "-std=c11", "-O3", "-sSUPPORT_LONGJMP=emscripten",
                 *[flag for include in includes for flag in ("-I", include)],
                 "-c", source / filename, "-o", output], environment)
        objects.append(output)
    archive = build / f"lib{name}.a"
    # Replace only our own archive, so obsolete object members cannot survive.
    archive.unlink(missing_ok=True)
    command([emar, "rcs", archive, *objects], environment)
    return archive


def main():
    parser = argparse.ArgumentParser(description="Build strict owned PNG/JPEG raw Wasm decoders")
    parser.add_argument("--prepare-only", action="store_true",
                        help="Acquire/verify pinned inputs without any compiler/runtime execution")
    options = parser.parse_args()
    png_source = acquire_port(PINS["ports"]["libpng"])
    zlib_source = acquire_port(PINS["ports"]["zlib"])
    jpeg_source, jpeg_build, jpeg_library = check_mozjpeg()
    notices = json.loads((ROOT / "notices-manifest.json").read_text())
    for notice in notices["notices"]:
        require_hash(ROOT / notice["file"], notice["sha256"])
    if options.prepare_only:
        print("Pinned decoder inputs prepared; no compilation or runtime execution.")
        return

    feasibility = ROOT.parent
    sdk = feasibility / "emsdk"
    emscripten = sdk / "upstream/emscripten"
    environment = os.environ.copy()
    environment["EM_CONFIG"] = str(sdk / ".emscripten")
    environment["SOURCE_DATE_EPOCH"] = str(PINS["toolchain"]["sourceDateEpoch"])
    environment["PATH"] = os.pathsep.join([
        str(feasibility / "build-env/bin"), str(emscripten), str(sdk / "upstream/bin"),
        environment.get("PATH", ""),
    ])
    actual_version = (emscripten / "emscripten-version.txt").read_text().strip().strip('"')
    if actual_version != PINS["toolchain"]["emscriptenVersion"]:
        raise RuntimeError(f"Unexpected Emscripten version: {actual_version}")
    emcc = emscripten / "emcc"
    emar = emscripten / "emar"
    version = subprocess.check_output([str(emcc), "--version"], env=environment, text=True)
    if PINS["toolchain"]["emscriptenSourceRevision"] not in version:
        raise RuntimeError("emcc does not report the pinned actual Emscripten source revision")
    # Explicit local builds use the port archives/configuration, rather than
    # silently trusting an unrecorded cached port binary or mutating its source.
    # No -pthread/-msimd128, native SIMD source, or filesystem ABI is enabled.
    zlib_library = compile_archive("z", zlib_source, ZLIB_SOURCES,
                                  [zlib_source], emcc, emar, environment)
    png_library = compile_archive("png", png_source, PNG_SOURCES,
                                 [png_source, zlib_source], emcc, emar, environment)
    exports = [
        "_malloc", "_free", "_pd_png_decode", "_pd_jpeg_decode", "_pd_result_free",
        "_pd_result_data", "_pd_result_size", "_pd_result_width", "_pd_result_height",
        "_pd_result_stride", "_pd_result_layout", "_pd_result_source_precision",
        "_pd_result_source_color", "_pd_result_flags", "_pd_result_status",
        "_pd_result_codec_status", "_pd_result_error",
    ]
    output = ROOT / "out"
    output.mkdir(exist_ok=True)
    command([emcc, ROOT / "raw_decode.c", ROOT / "png_decode.c", ROOT / "jpeg_decode.c",
             "-I", ROOT, "-I", png_source, "-I", zlib_source,
             "-I", jpeg_source, "-I", jpeg_build, png_library, zlib_library, jpeg_library,
             "-std=c11", "-O3", "--no-entry", "-sSUPPORT_LONGJMP=emscripten",
             "-sMODULARIZE=1", "-sEXPORT_ES6=1", "-sENVIRONMENT=worker,node",
             "-sFILESYSTEM=0", "-sALLOW_MEMORY_GROWTH=1", "-sABORTING_MALLOC=0",
             "-sMALLOC=dlmalloc", "-sINITIAL_MEMORY=67108864", "-sMAXIMUM_MEMORY=2147483648",
             "-sSTACK_SIZE=1048576", '-sEXPORTED_RUNTIME_METHODS=["HEAPU8","UTF8ToString"]',
             "-sEXPORTED_FUNCTIONS=" + json.dumps(exports), "-o", output / "raw-decode.mjs"], environment)
    own_inputs = ["raw_decode.h", "raw_decode.c", "png_decode.c", "jpeg_decode.c", "loader.mjs",
                  "build.py", "pins.json", "notices-manifest.json", "smoke.mjs", "BUILD-NOTES.txt"]
    source_inputs = [png_source / filename for filename in PNG_SOURCES]
    source_inputs += [zlib_source / filename for filename in ZLIB_SOURCES]
    source_inputs += [png_source / "pnglibconf.h", zlib_source / "zconf.h"]
    manifest = {
        "status": "Compilation/link commands completed only; no runtime/corpus/capacity gate implied",
        "pins": PINS, "emccVersion": version.strip(), "commands": COMMANDS,
        "environment": {key: environment[key] for key in ("EM_CONFIG", "SOURCE_DATE_EPOCH", "PATH")},
        "inputSha256": {name: digest(ROOT / name) for name in own_inputs},
        "sourceInputSha256": {str(path.relative_to(ROOT)): digest(path) for path in source_inputs},
        "noticeSha256": {notice["file"]: digest(ROOT / notice["file"]) for notice in notices["notices"]},
        "linkedArchiveSha256": {str(path): digest(path) for path in (png_library, zlib_library, jpeg_library)},
        "toolBinarySha256": {name: digest(sdk / "upstream/bin" / name) for name in ("clang", "wasm-ld")},
        "artifactSha256": {name: digest(output / name) for name in ("raw-decode.mjs", "raw-decode.wasm")},
    }
    (output / "build-metadata.json").write_text(json.dumps(manifest, indent=2) + "\n")
    print("Raw decoder module written. Parent must run smoke, worker/color and capacity gates separately.")


if __name__ == "__main__":
    main()
