"""Run one deterministic data transformation inside a restricted container.

The trusted operator mounts this reviewed program and one harmless JSON input as
read-only files. The task validates its identity and local boundaries, performs
a loopback exchange, proves that an off-host test address is unreachable, uses
the bounded workspace, and prints one canonical JSON result. It performs no
dependency installation and makes no persistent write.
"""

from __future__ import annotations

import errno
import hashlib
import json
import os
from pathlib import Path
import socket
import threading
from typing import NoReturn


INPUT = Path("/input/request.json")
PROGRAM = Path("/program/task.py")
WORKSPACE = Path("/workspace")
EXPECTED_ENVIRONMENT = {
    "GSS_TASK_MODE": "isolated",
    "LANG": "C.UTF-8",
    "PATH": "/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
}


def fail(message: str) -> NoReturn:
    """Stop the task with a stable diagnostic when one boundary differs.

    Args:
        message: Non-secret explanation of the failed invariant.

    Raises:
        RuntimeError: Always, so the container exits nonzero and emits no result.

    Side effects:
        None before the exception is raised. Calls are deterministic and serial.
    """
    raise RuntimeError(message)


def require_identity_and_environment() -> None:
    """Require the intended non-root identity and deliberately minimal process environment.

    Inputs:
        Reads the current process UID, GID, and environment.

    Outputs:
        Returns only when UID/GID are both 65532 and the environment exactly
        matches ``EXPECTED_ENVIRONMENT``.

    Raises:
        RuntimeError: If identity or any environment key/value differs.

    Side effects:
        None. The check is deterministic and safe to repeat within this process.
    """
    if (os.getuid(), os.getgid()) != (65532, 65532):
        fail("unexpected task identity")
    if dict(os.environ) != EXPECTED_ENVIRONMENT:
        fail("unexpected process environment")


def require_read_only(path: Path) -> None:
    """Require one mounted file to reject an append as read-only or non-writable.

    Args:
        path: Existing program or input file on a read-only bind mount.

    Raises:
        RuntimeError: If the append succeeds or fails for a reason other than
        ``EACCES`` or ``EROFS``.

    Side effects:
        Attempts one zero-byte append. A correctly mounted file is unchanged.
        Calls are sequential; no concurrent writer is supported.
    """
    try:
        with path.open("ab"):
            pass
    except OSError as error:
        if error.errno in {errno.EACCES, errno.EROFS}:
            return
        fail(f"read-only probe returned errno {error.errno}")
    fail("read-only probe unexpectedly succeeded")


def require_read_only_root() -> None:
    """Require the non-root task to be unable to create a top-level file.

    Raises:
        RuntimeError: If the write succeeds or does not fail with ``EACCES`` or
        ``EROFS``. Docker inspection separately proves the read-only root flag.

    Side effects:
        Attempts one file create at ``/gss-root-write-probe``. The expected path
        is never created. Execution is deterministic and single-threaded.
    """
    try:
        Path("/gss-root-write-probe").write_text("unexpected\n", encoding="utf-8")
    except OSError as error:
        if error.errno in {errno.EACCES, errno.EROFS}:
            return
        fail(f"root write probe returned errno {error.errno}")
    fail("root filesystem write unexpectedly succeeded")


def loopback_exchange() -> str:
    """Exchange one fixed message with an in-process loopback TCP helper.

    Returns:
        The helper's UTF-8 response, expected to be ``loopback-ok``.

    Raises:
        RuntimeError: If the helper does not bind only to loopback, complete in
        two seconds, or return the exact response.

    Side effects:
        Opens one ephemeral loopback listener and one client connection. A
        single helper thread is joined before return; no listener remains.
    """
    response: list[bytes] = []
    ready = threading.Event()
    port: list[int] = []

    def serve() -> None:
        """Serve one loopback request and close the ephemeral listener.

        Side effects:
            Binds ``127.0.0.1`` on an ephemeral port and handles one connection.
            Exceptions remain visible through the missing expected response.
        """
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
            server.bind(("127.0.0.1", 0))
            server.listen(1)
            server.settimeout(2)
            port.append(server.getsockname()[1])
            ready.set()
            connection, _ = server.accept()
            with connection:
                if connection.recv(64) != b"task-probe":
                    return
                connection.sendall(b"loopback-ok")

    thread = threading.Thread(target=serve, name="loopback-helper", daemon=False)
    thread.start()
    if not ready.wait(2) or len(port) != 1:
        fail("loopback helper did not become ready")
    with socket.create_connection(("127.0.0.1", port[0]), timeout=2) as client:
        client.sendall(b"task-probe")
        response.append(client.recv(64))
    thread.join(2)
    if thread.is_alive() or response != [b"loopback-ok"]:
        fail("loopback exchange differed")
    return response[0].decode("utf-8")


def require_off_host_unreachable() -> int:
    """Require the documentation-only off-host address to fail with ``ENETUNREACH``.

    Returns:
        The observed numeric errno, exactly ``errno.ENETUNREACH``.

    Raises:
        RuntimeError: If connection succeeds, times out, or fails with another
        errno. A timeout is uncertainty and is never classified as isolation.

    Side effects:
        Attempts one TCP connection to ``198.51.100.1:9`` with a one-second
        timeout. No retry is performed.
    """
    try:
        with socket.create_connection(("198.51.100.1", 9), timeout=1):
            fail("off-host connection unexpectedly succeeded")
    except socket.timeout:
        fail("off-host connection timed out")
    except OSError as error:
        if error.errno != errno.ENETUNREACH:
            fail(f"off-host probe returned errno {error.errno}")
        return error.errno
    fail("off-host probe returned no result")


def exercise_workspace() -> int:
    """Fill the one-MiB tmpfs until ``ENOSPC``, then remove the probe file.

    Returns:
        Number of bytes accepted before the exact bounded-space failure.

    Raises:
        RuntimeError: If the directory identity is wrong, the write fails with
        another errno, or two MiB are accepted without ``ENOSPC``.

    Side effects:
        Creates and removes ``/workspace/fill.bin``. Writes at most two MiB in
        64-KiB chunks, sequentially, with flush after every chunk.
    """
    stat = WORKSPACE.stat()
    if (stat.st_uid, stat.st_gid) != (65532, 65532):
        fail("workspace ownership differs")
    target = WORKSPACE / "fill.bin"
    written = 0
    try:
        with target.open("wb", buffering=0) as stream:
            for _ in range(32):
                try:
                    written += stream.write(b"x" * 65536)
                except OSError as error:
                    if error.errno != errno.ENOSPC:
                        fail(f"workspace probe returned errno {error.errno}")
                    return written
    finally:
        target.unlink(missing_ok=True)
    fail("workspace accepted more than its configured bound")


def load_and_transform() -> dict[str, object]:
    """Validate the fixed-format input and calculate a deterministic summary.

    Returns:
        Dictionary containing the schema, sorted unique integer values, count,
        sum, and SHA-256 of the canonical input JSON.

    Raises:
        RuntimeError: If the input is not the exact supported schema or contains
        non-integers, booleans, too many values, or out-of-range values.

    Side effects:
        Reads the immutable input once. No file or global state is changed;
        identical input bytes produce identical output.
    """
    raw = INPUT.read_bytes()
    try:
        value = json.loads(raw)
    except (UnicodeDecodeError, json.JSONDecodeError):
        fail("input is not valid UTF-8 JSON")
    if not isinstance(value, dict) or set(value) != {"schema", "values"} \
            or value.get("schema") != "gss-isolated-task-input-v1":
        fail("input schema differs")
    values = value.get("values")
    if not isinstance(values, list) or not 1 <= len(values) <= 32 \
            or any(isinstance(item, bool) or not isinstance(item, int) or abs(item) > 1_000_000
                   for item in values):
        fail("input values differ")
    canonical = json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8")
    unique = sorted(set(values))
    return {
        "schema": "gss-isolated-task-result-v1",
        "input_sha256": hashlib.sha256(canonical).hexdigest(),
        "values": unique,
        "count": len(unique),
        "sum": sum(unique),
    }


def main() -> None:
    """Run all checks and print one canonical result only after they pass.

    Outputs:
        Writes one newline-terminated canonical JSON object to standard output.

    Raises:
        RuntimeError or an input/filesystem/socket exception on any failed
        prerequisite. Partial success never emits a result object.

    Side effects:
        Performs the documented read-only, loopback, off-host, and tmpfs probes.
        The tmpfs probe is removed before output. Calls must be serialized.
    """
    require_identity_and_environment()
    require_read_only(PROGRAM)
    require_read_only(INPUT)
    require_read_only_root()
    loopback = loopback_exchange()
    unreachable_errno = require_off_host_unreachable()
    exercise_workspace()
    result = load_and_transform()
    result.update({
        "gid": os.getgid(),
        "loopback": loopback,
        "off_host_errno": unreachable_errno,
        "uid": os.getuid(),
        "workspace_enospc": True,
    })
    print(json.dumps(result, sort_keys=True, separators=(",", ":")), flush=True)


if __name__ == "__main__":
    main()
