#!/usr/bin/env bash
set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
results_dir="${LEOCLEAN_NOSEND_RESULTS_DIR:-${repo_root}/.crabbox-results}"
receipt="${LEOCLEAN_NOSEND_RECEIPT:-${results_dir}/leoclean-nosend-runtime.json}"
uv_bin="${UV_BIN:-$(command -v uv || true)}"
python_bin="${PYTHON_BIN:-python3}"
artifact_output="${LEOCLEAN_NOSEND_ARTIFACT_OUTPUT:-}"
artifact_output_partial=""

if [[ -z "$uv_bin" || ! -x "$uv_bin" ]]; then
  echo "uv 0.9.30 is required" >&2
  exit 69
fi
if [[ "$($uv_bin --version | awk '{print $2}')" != "0.9.30" ]]; then
  echo "uv must be exactly 0.9.30" >&2
  exit 69
fi
if ! command -v "$python_bin" >/dev/null 2>&1; then
  echo "the compiler Python is unavailable: $python_bin" >&2
  exit 69
fi

temporary="$(mktemp -d "${TMPDIR:-/tmp}/livingip-nosend-runtime.XXXXXX")"
cleanup() {
  if [[ -n "$artifact_output_partial" ]]; then
    chmod -R u+w "$artifact_output_partial" 2>/dev/null || true
    rm -rf "$artifact_output_partial"
  fi
  chmod -R u+w "$temporary" 2>/dev/null || true
  rm -rf "$temporary"
}
trap cleanup EXIT INT TERM

artifact="$temporary/artifact"
repeat_artifact="$temporary/artifact-repeat"
hermes_build="$temporary/hermes-build"
runtime_venv="$temporary/runtime-venv"
mkdir -p "$results_dir" "$(dirname "$receipt")"
rm -f "$receipt"

"$python_bin" "$repo_root/scripts/compile_leoclean_nosend_runtime.py" \
  --repo-root "$repo_root" \
  --output "$artifact" \
  --download-timeout 60 \
  >"$temporary/compile-primary.json"
"$python_bin" "$repo_root/scripts/compile_leoclean_nosend_runtime.py" \
  --repo-root "$repo_root" \
  --output "$repeat_artifact" \
  --download-timeout 60 \
  >"$temporary/compile-repeat.json"

"$python_bin" - "$artifact/artifact-manifest.json" "$repeat_artifact/artifact-manifest.json" <<'PY'
import json
import sys
from pathlib import Path

first = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
second = json.loads(Path(sys.argv[2]).read_text(encoding="utf-8"))
if first != second or first.get("content", {}).get("sha256") != second.get("content", {}).get("sha256"):
    raise SystemExit("two clean compiles did not produce the same artifact manifest")
PY

cp -R "$artifact/hermes-agent" "$hermes_build"
"$uv_bin" venv --python 3.11.9 --no-project "$runtime_venv"
VIRTUAL_ENV="$runtime_venv" "$uv_bin" sync \
  --directory "$hermes_build" \
  --active \
  --frozen \
  --no-dev \
  --extra cron \
  --no-editable

"$runtime_venv/bin/python" "$repo_root/scripts/verify_leoclean_nosend_runtime.py" \
  --repo-root "$repo_root" \
  --artifact "$artifact" \
  --runtime-python "$runtime_venv/bin/python" \
  --uv-bin "$uv_bin" \
  --output "$receipt"

"$runtime_venv/bin/python" - "$receipt" <<'PY'
import json
import sys
from pathlib import Path

receipt = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
if receipt.get("status") != "pass" or receipt.get("verification_mode") != "release":
    raise SystemExit("no-send runtime receipt did not pass in release mode")
print(json.dumps({"artifact_sha256": receipt["artifact_sha256"], "status": "pass"}, sort_keys=True))
PY

if [[ -n "$artifact_output" ]]; then
  if [[ -e "$artifact_output" || -L "$artifact_output" ]]; then
    echo "retained artifact output already exists: $artifact_output" >&2
    exit 65
  fi
  mkdir -p "$(dirname "$artifact_output")"
  artifact_output_partial="${artifact_output}.partial.$$"
  if [[ -e "$artifact_output_partial" || -L "$artifact_output_partial" ]]; then
    echo "retained artifact partial output already exists: $artifact_output_partial" >&2
    exit 65
  fi
  cp -pR "$artifact" "$artifact_output_partial"
  mv "$artifact_output_partial" "$artifact_output"
  artifact_output_partial=""
fi
