"""Separate, unreleased C3-S launch path using the reviewed cleanup policy."""

import json
import math
import os
from pathlib import Path
import subprocess
import sys

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))

import pf002_c3_completion_activate_v1 as bindings
import pf002_c3_completion_activate_v2 as spent
import pf002_c3_completion_report_v2 as report
import pf002_c3_completion_supervisor_v1 as supervisor
import pf002_c3_completion_supervisor_v2 as cleanup

from pf002_c3_completion_activate_v2 import _digest, _inspect_report, _provenance, _read

REVIEWED_CLEANUP = "efb1e861ef00944582dad0aadaed01c93d1f26eb"
RUN_DIRECTORY = "pf002-c3-completion-v2-cleanup-qualified-single-run"
RELEASE_NAME = "pf002-c3-completion-v2-cleanup-qualified-release.json"
PLAN_CAP = spent.PLAN_CAP
RESERVE = spent.RESERVE
SPENT_V2_FILES = {
    "launch.json": "829fb85719cd366a4dd089cfc0e1b6a79d5ac254e0fcb672cd6e35e0d88ad374",
    "plan.json": "1c67692feaef381d4d2c88cd3d203bdec64638ad45772b091cd98479351e769a",
    "receipt.json": "ddb477767e91b5a449c6b74a8f13750c6684b4d5d35615ad1f0b3c4c721dbf30",
    "report.json": "b28f92a055365ae733639a266184453ec57ae1977ee0ad7c09f89341bda13472",
    "terminal.json": "351a18acf26b3e93c0200c2cdf56ea238af85141e3917b8f6b001adee4385572",
    "worker-start.json": "09dead09324b49c40d1fb09a2f820293032ca65cd6069e1afebeed893045ab8a",
    "stdout.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "stderr.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
}
SPENT_V2_RELEASE_SHA256 = "825a17bb3ddb30e1a45c232a3b99ff0fbd58875bb00bd398eb81844cd966981f"


def _command():
    return [sys.executable, "-I", "-B", str(Path(__file__).resolve())]


def build_plan(clock):
    # The existing read-only preflight binds v2 science and checks the
    # original v1 slot. Neither earlier launch entry point is called.
    plan = spent.build_plan(clock)
    head = plan["git_head"]
    additions = ("pf002_c3_completion_activate_v2.py",
                 "pf002_c3_completion_supervisor_v2.py")
    bindings._git(clock, "merge-base", "--is-ancestor", REVIEWED_CLEANUP, head)
    bindings._git(clock, "diff", "--quiet", REVIEWED_CLEANUP, head, "--", *additions)
    for name in additions:
        plan["source_sha256"][name] = supervisor.sha_file(HERE / name, clock)
    old = Path(plan["output"])
    common = old.parent
    if old.is_symlink() or not old.is_dir():
        raise ValueError("spent_v2_slot_missing")
    evidence = {old / name: sha for name, sha in SPENT_V2_FILES.items()}
    evidence[Path(plan["release"])] = SPENT_V2_RELEASE_SHA256
    for path, sha in evidence.items():
        clock.timeout(supervisor.TOTAL_DEADLINE)
        if _digest(_read(path, plan["limits"]["record_bytes"])) != sha:
            raise ValueError("spent_v2_evidence_drift")
    output = common / RUN_DIRECTORY
    plan.update(
        schema="pf002-c3-completion-v2-cleanup-qualified-plan/1",
        reviewed_cleanup=REVIEWED_CLEANUP,
        activation_sha256=supervisor.sha_file(__file__, clock),
        output=str(output), release=str(common / RELEASE_NAME),
        supervisor_argv=_command(), worker_argv=[*_command(), "--worker", str(output)],
        spent_v2_evidence_sha256={**SPENT_V2_FILES, "release.json": SPENT_V2_RELEASE_SHA256},
    )
    return plan


def _release_bytes(plan, sha):
    return bindings._json_bytes({"schema": "pf002-c3-completion-v2-cleanup-qualified-release/1",
                                "plan_sha256": sha, "git_head": plan["git_head"],
                                "authorised_runs": 1})


def _release_digest(plan, sha):
    raw = _read(Path(plan["release"]), 4096)
    if raw != _release_bytes(plan, sha):
        raise ValueError("release_binding")
    return _digest(raw)


def _worker(output, clock):
    if not output.is_absolute() or output.name != RUN_DIRECTORY or output.is_symlink():
        raise ValueError("worker_output")
    raw = _read(output / "plan.json", PLAN_CAP)
    plan, sha = json.loads(raw), _digest(raw)
    launch = json.loads(_read(output / "launch.json", PLAN_CAP))
    argv = [*_command(), "--worker", str(output)]
    if (launch["supervisor_pid"] != os.getppid() or launch["plan_sha256"] != sha
            or plan["output"] != str(output) or plan["worker_argv"] != argv
            or sys.orig_argv[1:] != argv[1:] or plan["runtime"] != sys.version):
        raise ValueError("worker_binding")
    started = launch["clock_started_monotonic"]
    if type(started) is not float or not math.isfinite(started) or not 0 < started <= clock.start:
        raise ValueError("worker_clock_binding")
    clock.start = started
    if bindings._json_bytes(build_plan(clock)) != raw:
        raise ValueError("worker_plan_drift")
    if _release_digest(plan, sha) != launch["release_sha256"]:
        raise ValueError("worker_release_drift")
    clock.timeout(supervisor.TOTAL_DEADLINE, RESERVE)
    supervisor._publish_receipt(output, "worker-start.json", {
        "pid": os.getpid(), "ppid": os.getppid(), "started_utc": bindings._utc(),
        "argv": argv, "invoked_argv": sys.orig_argv, "plan_sha256": sha})
    data = report.build_report_record(report.checker.evaluate_report_rows(), _provenance(plan, sha))
    clock.timeout(supervisor.TOTAL_DEADLINE, RESERVE)
    report.parent_report.write_record_no_clobber(output / "report.json", data)


def _run(approved_sha, clock):
    plan = build_plan(clock)
    raw = bindings._json_bytes(plan)
    sha = _digest(raw)
    if approved_sha != sha or len(raw) > PLAN_CAP:
        raise ValueError("activation_plan_digest")
    release_sha = _release_digest(plan, sha)
    supervisor._ps_table(clock)
    clock.timeout(supervisor.TOTAL_DEADLINE, RESERVE)
    output = Path(plan["output"])
    output.mkdir(mode=0o700)
    report.parent_report.write_record_no_clobber(output / "plan.json", raw)
    launch = {"plan_sha256": sha, "release_sha256": release_sha,
              "supervisor_pid": os.getpid(), "parent_pid": os.getppid(),
              "argv": [*plan["supervisor_argv"], "--run", sha], "invoked_argv": sys.orig_argv,
              "started_utc": bindings._utc(), "clock_started_monotonic": clock.start}
    supervisor._publish_receipt(output, "launch.json", launch)
    record = {"launch": launch}

    def postflight(shared_clock):
        after = build_plan(shared_clock)
        match = after == plan and _release_digest(after, sha) == release_sha
        result = {"before_after_match": match,
                  "git_head_after": after["git_head"], "source_sha256_after": after["source_sha256"],
                  "runtime_sha256_after": after["runtime_sha256"],
                  "activation_sha256_after": after["activation_sha256"],
                  "parent_evidence_sha256_after": after["parent_evidence_sha256"],
                  "spent_v2_evidence_sha256_after": after["spent_v2_evidence_sha256"]}
        if match and record["child_success"]:
            result["report"] = _inspect_report(output, plan, sha, record["child_pid"], shared_clock)
        return result

    interrupted = None
    try:
        cleanup.supervise(plan["worker_argv"], HERE, output, record, clock,
                             reserve=RESERVE, postflight=postflight)
    except supervisor.SupervisorSignal as error:
        interrupted = error.signum
    candidate = bool(record.pop("success", False) and record.get("after", {}).get("report"))
    state = "provisional" if candidate and clock.remaining() > 0 else "failed"
    supervisor._publish_receipt(output, "terminal.json", {
        "state": state, "plan_sha256": sha, "supervisor_pid": os.getpid(),
        "supervision": record, "terminal_snapshot_utc": bindings._utc(),
        "elapsed_seconds_before_terminal_write": clock.elapsed()})
    if clock.remaining() <= 0:
        supervisor._retain_publication_failure(output, dict(record, deadline_exceeded=True))
        return 1
    if interrupted is not None:
        return 128 + interrupted
    return 0 if state == "provisional" else 1


def main(argv):
    clock = supervisor.Clock(supervisor.TOTAL_DEADLINE)
    if not sys.flags.isolated or not sys.dont_write_bytecode:
        return 2
    try:
        if argv == ["--plan"]:
            plan = build_plan(clock)
            sys.stdout.buffer.write(bindings._json_bytes({
                "plan": plan, "plan_sha256": _digest(bindings._json_bytes(plan))}))
        elif len(argv) == 2 and argv[0] == "--run":
            if sys.orig_argv[1:] != [*_command()[1:], *argv]:
                raise ValueError("supervisor_argv_binding")
            return _run(argv[1], clock)
        elif len(argv) == 2 and argv[0] == "--worker":
            _worker(Path(argv[1]), clock)
        else:
            return 2
    except (OSError, ValueError, KeyError, TypeError, TimeoutError, subprocess.SubprocessError) as error:
        sys.stderr.write(f"C3-S cleanup-qualified activation refused or failed: {error}\n")
        return 2
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
