"""Isolated source-bound worker bootstrap for the normalized C3-S attempt."""

import hashlib
import json
import os
from pathlib import Path
import sys
import time
import types

MODULES = (
    "pf002_c3s_m1_nominal_checker",
    "pf002_c3s_m1_nominal_oracle",
    "pf002_c3s_m1_nominal_supervisor",
    "pf002_c3s_m1_nominal_activation_v1",
)


def main():
    root, attempt, parent, plan_digest, deadline = sys.argv[1:]
    root, attempt = Path(root), Path(attempt)
    deadline = float(deadline)
    if not (sys.flags.isolated and sys.flags.no_site and sys.flags.dont_write_bytecode
            and os.getppid() == int(parent) and time.monotonic() < deadline):
        return 2
    with (attempt / "launch.json").open("rb") as stream:
        receipt = json.loads(stream.read(65536))
    envelope = receipt["envelope"]
    plan = envelope["plan"]
    payload = (json.dumps(plan, sort_keys=True, separators=(",", ":")) + "\n").encode()
    if (receipt["parent_pid"] != os.getppid() or receipt["worker_deadline"] != deadline
            or envelope["plan_sha256"] != plan_digest
            or hashlib.sha256(payload).hexdigest() != plan_digest):
        return 2
    digest = hashlib.sha256()
    with Path(sys.executable).open("rb") as stream:
        for block in iter(lambda: stream.read(65536), b""):
            if time.monotonic() >= deadline:
                return 2
            digest.update(block)
    if digest.hexdigest() != plan["runtime"]["executable_sha256"]:
        return 2
    for name in MODULES:
        path = root / (name + ".py")
        with path.open("rb") as stream:
            data = stream.read(65537)
        if (len(data) > 65536 or hashlib.sha256(data).hexdigest() != plan["source_sha256"][path.name]
                or time.monotonic() >= deadline or name in sys.modules):
            return 2
        module = types.ModuleType(name)
        module.__file__ = str(path)
        sys.modules[name] = module
        exec(compile(data, str(path), "exec"), module.__dict__)
    return module.run_worker(attempt, plan_digest, deadline)


if __name__ == "__main__":
    raise SystemExit(main())
