#!/usr/bin/env python3
"""Build the deterministic connected-release zip application.

The builder reads one reviewed version input and writes one zipapp with stable
metadata. It performs local file I/O only, overwrites the requested output, and
fails before writing for an unsupported version or unreadable input. Identical
inputs produce identical bytes; callers must serialize writes to one output.
"""

from __future__ import annotations

import argparse
from pathlib import Path
import zipfile


VERSIONS = {"known-good-a", "candidate-b"}


def application_source(version: str) -> bytes:
    """Render the loopback-only HTTP fixture for an allowed version.

    Args:
        version: Exact release version from ``version.txt``.

    Returns:
        UTF-8 Python source for the zipapp entry point.

    Raises:
        ValueError: If the version is outside the two-value fixture contract.

    Side effects:
        None. Rendering is deterministic and safe for concurrent callers.
    """
    if version not in VERSIONS:
        raise ValueError(f"unsupported fixture version: {version!r}")
    return f'''import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
VERSION = {version!r}
class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/healthz":
            status, body = 200, {{"status": "ok", "version": VERSION}}
        elif self.path == "/version":
            status, body = 200, {{"version": VERSION}}
        else:
            status, body = 404, {{"error": "not found"}}
        payload = json.dumps(body, sort_keys=True).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)
    def log_message(self, format, *values):
        return
ThreadingHTTPServer(("127.0.0.1", 8080), Handler).serve_forever()
'''.encode()


def read_version(path: Path) -> str:
    """Read and validate the single-line release version input.

    Args:
        path: UTF-8 file containing one allowed version and an optional newline.

    Returns:
        Validated version without surrounding whitespace.

    Raises:
        OSError: If the file cannot be read.
        ValueError: If whitespace changes more than the final newline or the
            value is unsupported.

    Side effects:
        Reads one local file. Concurrent reads are safe.
    """
    raw = path.read_text(encoding="utf-8")
    version = raw.removesuffix("\n")
    if version not in VERSIONS or raw not in {version, version + "\n"}:
        raise ValueError("version file must contain one exact supported value")
    return version


def build(version_file: Path, output: Path) -> None:
    """Write a deterministic zipapp for the reviewed version input.

    Args:
        version_file: Path validated by :func:`read_version`.
        output: Destination zipapp. Its parent must already exist.

    Returns:
        None.

    Raises:
        OSError: If an input cannot be read or the output cannot be written.
        ValueError: If the version input is invalid.

    Side effects:
        Replaces ``output`` with a zip archive. Callers must not write the same
        path concurrently. Stable timestamps, permissions and compression make
        the result deterministic for identical Python/zlib implementations.
    """
    source = application_source(read_version(version_file))
    info = zipfile.ZipInfo("__main__.py", (2020, 1, 1, 0, 0, 0))
    info.compress_type = zipfile.ZIP_DEFLATED
    info.external_attr = 0o644 << 16
    with zipfile.ZipFile(
        output, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9
    ) as archive:
        archive.writestr(info, source)


def main() -> None:
    """Parse the CLI and build one fixture artifact.

    Inputs are local paths supplied on the command line. The function writes
    only the requested output and propagates validation or file errors with a
    nonzero process exit. It has no network or concurrency behavior.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument("--version-file", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    build(args.version_file, args.output)


if __name__ == "__main__":
    main()
