"""Synthetic, network-isolated Docker cron evidence. Never uses PingCron endpoints."""
import datetime
import hashlib
import json
import os
from pathlib import Path
import platform
import re
import subprocess
import sys
import time
import traceback


def utc():
    return datetime.datetime.now(datetime.timezone.utc).isoformat()


JOB = r'''#!/bin/sh
set -u
run_id=$(date +%s)
printf '%s\n' "$run_id" >> /evidence/work-attempts
mode=$(cat /fixture/mode)
/fixture/work.sh "$mode" "$run_id"
work_rc=$?
validation_rc=0
report_rc=not_attempted
if [ "$work_rc" -eq 0 ]; then
  if [ "$(cat /evidence/output)" != "completed:$run_id" ]; then
    validation_rc=42
  else
    printf '%s\n' "$run_id" >> /evidence/report-attempts
    port=8080
    [ "$mode" != report_failure ] || port=8081
    wget -q -T 3 -O /dev/null "http://127.0.0.1:$port/cgi-bin/receipt?$run_id"
    report_rc=$?
  fi
fi
printf '{"run_id":"%s","work_rc":%s,"validation_rc":%s,"report_rc":"%s"}\n' \
  "$run_id" "$work_rc" "$validation_rc" "$report_rc" > /evidence/result.tmp
mv /evidence/result.tmp /evidence/result.json
[ "$work_rc" -eq 0 ] || exit "$work_rc"
[ "$validation_rc" -eq 0 ] || exit "$validation_rc"
if [ "$report_rc" != 0 ]; then
  printf 'Work completed, but the completion report failed. Do not rerun the work to retry telemetry.\n' >&2
fi
exit 0
'''

WORK = r'''#!/bin/sh
mode=$1
run_id=$2
[ "$mode" != work_failure ] || exit 23
if [ "$mode" != stale_output ]; then
  printf 'completed:%s\n' "$run_id" > /evidence/output
fi
printf '%s\n' "$run_id" >> /evidence/work-completed
exit 0
'''

LAUNCH = r'''#!/bin/sh
/fixture/job.sh
rc=$?
echo "$rc" > /evidence/wrapper-exit
exit "$rc"
'''

COLLECTOR = r'''#!/bin/sh
case "$QUERY_STRING" in ''|*[!0-9]*) printf 'Status: 400 Bad Request\r\n\r\n'; exit 0;; esac
printf '%s\n' "$QUERY_STRING" >> /evidence/receipts
printf 'Content-Type: text/plain\r\n\r\naccepted\n'
'''

ENTRY = r'''#!/bin/sh
set -eu
printf 'source crontab uid=%s\n' "$(stat -c %u /fixture/crontabs/root)"
mkdir -p /tmp/cron-tabs
cp /fixture/crontabs/root /tmp/cron-tabs/root
chmod 600 /tmp/cron-tabs/root
printf 'installed crontab uid=%s\n' "$(stat -c %u /tmp/cron-tabs/root)"
httpd -p 127.0.0.1:8080 -h /fixture/www
exec crond -f -l 8 -L /dev/stdout -c /tmp/cron-tabs
'''


def main():
    if (sys.argv[1:] != ["--ack-disposable-github-runner"]
            or platform.system() != "Linux"
            or os.environ.get("GITHUB_ACTIONS") != "true"
            or os.environ.get("RUNNER_ENVIRONMENT") != "github-hosted"):
        print("Refusing: requires explicit disposable GitHub-hosted Linux runner acknowledgement.")
        return 2
    run_id = os.environ.get("GITHUB_RUN_ID", "")
    attempt = os.environ.get("GITHUB_RUN_ATTEMPT", "")
    if not re.fullmatch(r"[0-9]+", run_id) or not re.fullmatch(r"[0-9]+", attempt):
        raise RuntimeError("Missing numeric run identity")
    root = Path.cwd() / "docker-cron-evidence"
    root.mkdir(exist_ok=False)
    report = {"started_at": utc(), "status": "running", "cleanup": "not_verified",
              "run_id": run_id, "run_attempt": attempt,
              "commit": os.environ.get("GITHUB_SHA"), "runner_image": os.environ.get("ImageVersion"),
              "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
              "cases": {}, "commands": []}
    containers = []
    cleanup_errors = []

    def checkpoint():
        tmp = root / "report.tmp"
        tmp.write_text(json.dumps(report, indent=2), encoding="utf-8")
        tmp.replace(root / "report.json")

    def command(args, timeout=30, check=True, persist=True):
        entry = {"at": utc(), "args": args}
        report["commands"].append(entry)
        if persist:
            checkpoint()
        try:
            p = subprocess.run(args, capture_output=True, text=True, timeout=timeout)
            entry.update(returncode=p.returncode, stdout=p.stdout, stderr=p.stderr)
            if persist:
                checkpoint()
            if check and p.returncode:
                raise RuntimeError(f"Command failed: {args[0:3]}: {p.stderr}")
            return p
        except Exception as exc:
            entry["error"] = str(exc)
            if persist:
                checkpoint()
            raise

    try:
        report["docker_server"] = json.loads(command(["docker", "version", "--format", "{{json .Server}}"]).stdout)
        command(["docker", "pull", "busybox:1.37.0"], timeout=120)
        info = json.loads(command(["docker", "image", "inspect", "busybox:1.37.0"]).stdout)[0]
        digest = info["RepoDigests"][0]
        report["image"] = {"reference": digest, "id": info["Id"], "architecture": info["Architecture"]}
        preflight_name = f"pingcron-evidence-{run_id}-{attempt}-preflight"
        containers.append(preflight_name)
        applets = command(["docker", "run", "--name", preflight_name, "--network", "none",
                           digest, "busybox", "--list"]).stdout.splitlines()
        report["required_applets"] = {name: name in applets for name in ("crond", "httpd", "wget")}
        if not all(report["required_applets"].values()):
            raise RuntimeError("The selected image lacks a required fixture applet")
        # One container per case, all with no external network. All mounts are synthetic.
        for mode in ("success", "work_failure", "stale_output", "report_failure"):
            case_root = root / mode
            fixture = case_root / "fixture"
            evidence = case_root / "observed"
            (fixture / "www/cgi-bin").mkdir(parents=True)
            (fixture / "crontabs").mkdir()
            evidence.mkdir()
            (evidence / "output").write_text("stale-before-this-run\n", encoding="utf-8")
            texts = {"job.sh": JOB, "work.sh": WORK, "launch.sh": LAUNCH, "entry.sh": ENTRY,
                     "www/cgi-bin/receipt": COLLECTOR, "mode": mode + "\n",
                     "crontabs/root": "* * * * * /fixture/launch.sh >> /evidence/job.log 2>&1\n"}
            for name, content in texts.items():
                path = fixture / name
                path.write_text(content, encoding="utf-8", newline="\n")
                path.chmod(0o755 if name.endswith(".sh") or name.endswith("receipt") else 0o644)
            name = f"pingcron-evidence-{run_id}-{attempt}-{mode.replace('_', '-')}"
            containers.append(name)
            report["cases"][mode] = {"container": name, "started_at": utc(), "status": "waiting",
                                     "fixture_hashes": {k: hashlib.sha256(v.encode()).hexdigest() for k, v in texts.items()}}
            checkpoint()
            command(["docker", "run", "-d", "--name", name, "--network", "none", "--init",
                     "--pids-limit", "64", "--memory", "64m", "--cpus", "0.5",
                     "--mount", f"type=bind,source={fixture},target=/fixture,readonly",
                     "--mount", f"type=bind,source={evidence},target=/evidence",
                     "--health-cmd", "true", "--health-interval", "1s", "--health-timeout", "1s",
                     "--health-retries", "1", digest, "/fixture/entry.sh"])
        report["busybox"] = command(["docker", "exec", report["cases"]["success"]["container"], "busybox"]).stdout.splitlines()[0]
        for case in report["cases"].values():
            owners = command(["docker", "exec", case["container"], "stat", "-c", "%u",
                              "/fixture/crontabs/root", "/tmp/cron-tabs/root"]).stdout.splitlines()
            case["crontab_uids"] = {"source": owners[0], "installed": owners[1]}
            assert owners[1] == "0", (case["container"], owners)
        checkpoint()
        pending = set(report["cases"])
        deadline = time.monotonic() + 95
        while pending and time.monotonic() < deadline:
            for mode in list(pending):
                evidence = root / mode / "observed"
                if not (evidence / "wrapper-exit").exists():
                    continue
                case = report["cases"][mode]
                name = case["container"]
                state = json.loads(command(["docker", "inspect", "--format", "{{json .State}}", name]).stdout)
                health_deadline = time.monotonic() + 5
                while state.get("Health", {}).get("Status") == "starting" and time.monotonic() < health_deadline:
                    time.sleep(0.2)
                    state = json.loads(command(["docker", "inspect", "--format", "{{json .State}}", name]).stdout)
                case["state_before_stop"] = state
                command(["docker", "stop", "--time", "3", name], timeout=15)
                case["finished_at"] = utc()
                case["observed"] = {p.name: p.read_text(encoding="utf-8") for p in evidence.iterdir() if p.is_file()}
                result = json.loads(case["observed"]["result.json"])
                count = lambda file: len(case["observed"].get(file, "").splitlines())
                assert state["Running"] and state["Health"]["Status"] == "healthy", (mode, state)
                assert count("work-attempts") == 1, (mode, "work repeated")
                assert count("work-completed") == (0 if mode == "work_failure" else 1), mode
                assert count("receipts") == (1 if mode == "success" else 0), mode
                assert count("report-attempts") == (1 if mode in ("success", "report_failure") else 0), mode
                assert result["work_rc"] == (23 if mode == "work_failure" else 0), mode
                assert result["validation_rc"] == (42 if mode == "stale_output" else 0), mode
                assert int(case["observed"]["wrapper-exit"]) == (23 if mode == "work_failure" else 42 if mode == "stale_output" else 0), mode
                if mode == "success":
                    assert result["report_rc"] == "0", result
                    assert case["observed"]["receipts"].strip() == result["run_id"], result
                elif mode == "report_failure":
                    assert result["report_rc"].isdigit() and int(result["report_rc"]) != 0, result
                else:
                    assert result["report_rc"] == "not_attempted", result
                case["status"] = "passed"
                pending.remove(mode)
                checkpoint()
            if pending:
                time.sleep(0.5)
        if pending:
            raise TimeoutError(f"Cron observations incomplete: {sorted(pending)}")
        report["status"] = "passed"
    except Exception:
        report["status"] = "failed"
        report["error"] = traceback.format_exc()
    finally:
        try:
            checkpoint()
        except Exception as exc:
            cleanup_errors.append(f"Pre-cleanup checkpoint: {exc}")
        for name in containers:
            try:
                command(["docker", "stop", "--time", "3", name], timeout=15, check=False, persist=False)
            except Exception as exc:
                cleanup_errors.append(f"Stop {name}: {exc}")
            try:
                log = command(["docker", "logs", name], check=False, persist=False)
                (root / f"{name}.log").write_text(log.stdout + log.stderr, encoding="utf-8")
            except Exception as exc:
                cleanup_errors.append(f"Log capture {name}: {exc}")
            try:
                command(["docker", "rm", "-f", name], timeout=15, persist=False)
                remaining = command(["docker", "ps", "-a", "--filter", f"name=^/{name}$", "--format", "{{.Names}}"], persist=False)
                if remaining.stdout.strip():
                    raise RuntimeError(f"Fixture container still exists: {name}")
            except Exception as exc:
                cleanup_errors.append(str(exc))
        # The bind-mounted raw evidence and fixture files stay in the artifact on failure.
        report["cleanup"] = "passed" if not cleanup_errors else "failed"
        report["cleanup_errors"] = cleanup_errors
        report["finished_at"] = utc()
        try:
            checkpoint()
        except Exception as exc:
            print(f"Final evidence checkpoint failed: {exc}", file=sys.stderr)
            return 1
    print(json.dumps({k: report[k] for k in ("status", "cleanup", "started_at", "finished_at")}, indent=2))
    return 0 if report["status"] == "passed" and report["cleanup"] == "passed" else 1


if __name__ == "__main__":
    sys.exit(main())
