#!/usr/bin/env bash
set -uo pipefail
umask 077

readonly EVIDENCE_ROOT="/home/cube/projects/richard/traning coach/.omo/evidence/task26/task26-gates18-20-activation-successor-30bcd6633875050aa4f56f49a8bb26cd616ffa2409fc04caef523a8a62d5d1cc-st_01a0080c"
readonly CANDIDATE_ROOT="/home/cube/projects/richard/traning coach/.omo/evidence/task26/task26-activation-cutover-successor-30bcd6633875050aa4f56f49a8bb26cd616ffa2409fc04caef523a8a62d5d1cc"
readonly REPO="/home/cube/projects/richard/hermes-agent"
readonly PY="$REPO/.venv/bin/python"
readonly DIGEST="30bcd6633875050aa4f56f49a8bb26cd616ffa2409fc04caef523a8a62d5d1cc"
readonly WHEEL="$CANDIDATE_ROOT/artifacts/hermes_agent-0.17.0-py3-none-any.whl"
readonly MATRIX="/home/cube/projects/richard/traning coach/.omo/evidence/task26/task26-gate19-50685ac2c063c5b18fa895cc1991e3473368d177c7309bf54af0374ea67ba1d1-matrix.json"
mkdir -p "$EVIDENCE_ROOT/artifacts" "$EVIDENCE_ROOT/receipts"
chmod 700 "$EVIDENCE_ROOT" "$EVIDENCE_ROOT/artifacts" "$EVIDENCE_ROOT/receipts"

run_recorded() {
  local name="$1"; shift
  local dir="$EVIDENCE_ROOT/artifacts/$name"
  mkdir -p "$dir"; chmod 700 "$dir"
  printf '%q ' "$@" >"$dir/command.txt"; printf '\n' >>"$dir/command.txt"
  date --utc +%Y-%m-%dT%H:%M:%S.%NZ >"$dir/started-at-utc.txt"
  local start end rc pid
  start=$(date +%s%N)
  "$@" >"$dir/stdout.txt" 2>"$dir/stderr.txt" &
  pid=$!
  wait "$pid"; rc=$?
  end=$(date +%s%N)
  date --utc +%Y-%m-%dT%H:%M:%S.%NZ >"$dir/ended-at-utc.txt"
  printf '%s\n' "$rc" >"$dir/exit-code.txt"
  printf '%s\n' "$(( (end-start)/1000000 ))" >"$dir/duration-ms.txt"
  (cd "$dir" && sha256sum command.txt started-at-utc.txt ended-at-utc.txt exit-code.txt duration-ms.txt stdout.txt stderr.txt >files.sha256)
  chmod 600 "$dir"/*
  return 0
}

cd "$REPO"
git status --porcelain=v1 -z >"$EVIDENCE_ROOT/artifacts/git-status-before.nul"
sha256sum "$CANDIDATE_ROOT/candidate-manifest.json" "$CANDIDATE_ROOT/candidate-checkpoint.json" "$WHEEL" >"$EVIDENCE_ROOT/artifacts/candidate-pins-before.sha256"
systemctl --user show hermes-gateway-dualcoachtest.service -p ActiveState -p SubState -p MainPID >"$EVIDENCE_ROOT/artifacts/service-before.txt" 2>&1 || true

run_recorded candidate-preverify "$PY" "$CANDIDATE_ROOT/verify_candidate.py" "$CANDIDATE_ROOT/verifier-input.json"

run_recorded source-wheel-parity "$PY" -c '
import hashlib,json,sys,zipfile
from pathlib import Path
repo=Path(sys.argv[1]); wheel=Path(sys.argv[2])
paths=["gateway/platforms/dualcoach_activation_cutover.py","gateway/platforms/dualcoach_admin.py","gateway/platforms/telegram_customer_bootstrap.py"]
rows=[]
with zipfile.ZipFile(wheel) as z:
 for path in paths:
  source=(repo/path).read_bytes(); shipped=z.read(path)
  rows.append({"path":path,"source_sha256":hashlib.sha256(source).hexdigest(),"wheel_sha256":hashlib.sha256(shipped).hexdigest(),"byte_identical":source==shipped})
result={"candidate_digest":sys.argv[3],"production_module_count":len(rows),"modules":rows,"status":"PASS" if all(x["byte_identical"] for x in rows) else "FAIL"}
print(json.dumps(result,sort_keys=True,separators=(",",":")))
raise SystemExit(result["status"]!="PASS")
' "$REPO" "$WHEEL" "$DIGEST"

run_recorded gate18 bwrap --die-with-parent --unshare-net --ro-bind / / --bind "$EVIDENCE_ROOT" "$EVIDENCE_ROOT" --tmpfs /tmp --tmpfs "$REPO/.pytest-cache" --dev /dev --proc /proc --setenv HOME /tmp --setenv TMPDIR /tmp --setenv PYTHONDONTWRITEBYTECODE 1 --chdir "$REPO" "$PY" -B -W error -m pytest -q -p no:cacheprovider --junitxml="$EVIDENCE_ROOT/artifacts/gate18.junit.xml" tests/gateway/test_nutrition_coaching.py::test_dualcoach_golden_path

mapfile -t GATE19_NODES < <("$PY" -c 'import json,sys; print("\n".join(json.load(open(sys.argv[1]))["exact_nodes"]))' "$MATRIX")
run_recorded gate19 bwrap --die-with-parent --unshare-net --ro-bind / / --bind "$EVIDENCE_ROOT" "$EVIDENCE_ROOT" --tmpfs /tmp --tmpfs "$REPO/.pytest-cache" --dev /dev --proc /proc --setenv HOME /tmp --setenv TMPDIR /tmp --setenv PYTHONDONTWRITEBYTECODE 1 --chdir "$REPO" "$PY" -B -W error -m pytest -q -p no:cacheprovider --junitxml="$EVIDENCE_ROOT/artifacts/gate19.junit.xml" "${GATE19_NODES[@]}"

run_recorded successor-focused bwrap --die-with-parent --unshare-net --ro-bind / / --bind "$EVIDENCE_ROOT" "$EVIDENCE_ROOT" --tmpfs /tmp --tmpfs "$REPO/.pytest-cache" --dev /dev --proc /proc --setenv HOME /tmp --setenv TMPDIR /tmp --setenv PYTHONDONTWRITEBYTECODE 1 --chdir "$REPO" "$PY" -B -W error -m pytest -q -p no:cacheprovider --junitxml="$EVIDENCE_ROOT/artifacts/successor-focused.junit.xml" tests/gateway/test_dualcoach_activation_cutover.py tests/gateway/test_dualcoach_admin_provider_auth.py tests/gateway/test_telegram_customer_bootstrap.py

run_recorded ruff "$REPO/.venv/bin/ruff" check --no-cache gateway/platforms/dualcoach_activation_cutover.py gateway/platforms/dualcoach_admin.py gateway/platforms/telegram_customer_bootstrap.py tests/gateway/test_dualcoach_activation_cutover.py tests/gateway/test_telegram_customer_bootstrap.py
run_recorded compile "$PY" -B -c 'import sys; from pathlib import Path; [compile(Path(p).read_bytes(),p,"exec",dont_inherit=True) for p in sys.argv[1:]]' gateway/platforms/dualcoach_activation_cutover.py gateway/platforms/dualcoach_admin.py gateway/platforms/telegram_customer_bootstrap.py tests/gateway/test_dualcoach_activation_cutover.py tests/gateway/test_telegram_customer_bootstrap.py
run_recorded basedpyright-new uvx --offline basedpyright --outputjson gateway/platforms/dualcoach_activation_cutover.py tests/gateway/test_dualcoach_activation_cutover.py
run_recorded basedpyright-full uvx --offline basedpyright --outputjson gateway/platforms/dualcoach_admin.py gateway/platforms/telegram_customer_bootstrap.py tests/gateway/test_telegram_customer_bootstrap.py gateway/platforms/dualcoach_activation_cutover.py tests/gateway/test_dualcoach_activation_cutover.py

readonly PARENT_TMP="$EVIDENCE_ROOT/artifacts/parent-type-input"
mkdir -p "$PARENT_TMP/gateway/platforms" "$PARENT_TMP/tests/gateway"
unzip -p "$CANDIDATE_ROOT/historical/predecessor-candidate/artifacts/hermes_agent-0.17.0-py3-none-any.whl" gateway/platforms/dualcoach_admin.py >"$PARENT_TMP/gateway/platforms/dualcoach_admin.py"
cp "/home/cube/projects/richard/traning coach/.omo/evidence/task26/task26-owner-customer-v1-candidate-v3/snapshot/worktree-status/tests/gateway/test_telegram_customer_bootstrap.py" "$PARENT_TMP/tests/gateway/test_telegram_customer_bootstrap.py"
run_recorded basedpyright-parent uvx --offline basedpyright --outputjson "$PARENT_TMP/gateway/platforms/dualcoach_admin.py" "$PARENT_TMP/tests/gateway/test_telegram_customer_bootstrap.py"

readonly BUILD_OUT="$EVIDENCE_ROOT/artifacts/reproducible-build-output"
mkdir -p "$BUILD_OUT"
run_recorded reproducible-build bwrap --die-with-parent --unshare-net --ro-bind / / --tmpfs /tmp --dev /dev --proc /proc --bind "$BUILD_OUT" /tmp/wheel-out --setenv HOME /tmp --setenv TMPDIR /tmp --setenv UV_CACHE_DIR /home/cube/.cache/uv --chdir "$REPO" "$REPO/scripts/reproducible-wheel-build" "$REPO" /tmp/wheel-out
sha256sum "$BUILD_OUT"/*.whl >"$EVIDENCE_ROOT/artifacts/reproducible-build.sha256" 2>&1 || true

readonly INSTALL_TMP="$EVIDENCE_ROOT/artifacts/installed-wheel-root"
mkdir -p "$INSTALL_TMP"
run_recorded wheel-install "$PY" -m pip install --no-deps --no-compile --target "$INSTALL_TMP" "$WHEEL"
mkdir -p "$EVIDENCE_ROOT/artifacts/wheel-tests"
cp tests/gateway/test_dualcoach_activation_cutover.py tests/gateway/test_dualcoach_admin_provider_auth.py tests/gateway/test_telegram_customer_bootstrap.py "$EVIDENCE_ROOT/artifacts/wheel-tests/"
run_recorded installed-wheel-tests bwrap --die-with-parent --unshare-net --ro-bind / / --tmpfs /tmp --dev /dev --proc /proc --setenv HOME /tmp --setenv TMPDIR /tmp --setenv PYTHONDONTWRITEBYTECODE 1 --setenv PYTHONPATH "$INSTALL_TMP" --chdir /tmp "$PY" -B -W error -m pytest -q -p no:cacheprovider --junitxml="$EVIDENCE_ROOT/artifacts/installed-wheel-tests.junit.xml" "$EVIDENCE_ROOT/artifacts/wheel-tests/test_dualcoach_activation_cutover.py" "$EVIDENCE_ROOT/artifacts/wheel-tests/test_dualcoach_admin_provider_auth.py" "$EVIDENCE_ROOT/artifacts/wheel-tests/test_telegram_customer_bootstrap.py::test_customer_activation_commits_only_the_exact_bound_session"
run_recorded installed-wheel-import-closure bwrap --die-with-parent --unshare-net --ro-bind / / --tmpfs /tmp --dev /dev --proc /proc --setenv HOME /tmp --setenv TMPDIR /tmp --setenv PYTHONDONTWRITEBYTECODE 1 --setenv PYTHONPATH "$INSTALL_TMP" --chdir /tmp "$PY" -B -c '
import importlib,json,sys
from pathlib import Path
root=Path(sys.argv[1]).resolve()
names=["gateway.platforms.dualcoach_activation_cutover","gateway.platforms.dualcoach_admin","gateway.platforms.telegram_customer_bootstrap"]
rows=[]
for name in names:
 module=importlib.import_module(name); origin=Path(module.__file__).resolve(); rows.append({"module":name,"origin":str(origin),"inside_installed_wheel":origin.is_relative_to(root)})
leaks=[]
for name,module in sorted(sys.modules.items()):
 if name=="gateway" or name.startswith("gateway."):
  path=getattr(module,"__file__",None)
  if path and not Path(path).resolve().is_relative_to(root): leaks.append({"module":name,"origin":str(Path(path).resolve())})
result={"candidate_digest":sys.argv[2],"imports":rows,"gateway_source_fallbacks":leaks,"status":"PASS" if all(x["inside_installed_wheel"] for x in rows) and not leaks else "FAIL"}
print(json.dumps(result,sort_keys=True,separators=(",",":")))
raise SystemExit(result["status"]!="PASS")
' "$INSTALL_TMP" "$DIGEST"
run_recorded installed-wheel-cli bwrap --die-with-parent --unshare-net --ro-bind / / --tmpfs /tmp --dev /dev --proc /proc --setenv HOME /tmp --setenv TMPDIR /tmp --setenv PYTHONDONTWRITEBYTECODE 1 --setenv PYTHONPATH "$INSTALL_TMP" --chdir /tmp "$PY" -B -m gateway.platforms.dualcoach_admin customer activate --help

run_recorded gate20-full-gateway bwrap --die-with-parent --unshare-net --ro-bind / / --bind "$EVIDENCE_ROOT" "$EVIDENCE_ROOT" --tmpfs /tmp --tmpfs "$REPO/.pytest-cache" --dev /dev --proc /proc --setenv HOME /tmp --setenv TMPDIR /tmp --setenv PYTHONDONTWRITEBYTECODE 1 --chdir "$REPO" "$PY" -B -m pytest -q -p no:cacheprovider --junitxml="$EVIDENCE_ROOT/artifacts/gate20-full-gateway.junit.xml" tests/gateway

run_recorded candidate-postverify "$PY" "$CANDIDATE_ROOT/verify_candidate.py" "$CANDIDATE_ROOT/verifier-input.json"
git status --porcelain=v1 -z >"$EVIDENCE_ROOT/artifacts/git-status-after.nul"
sha256sum "$CANDIDATE_ROOT/candidate-manifest.json" "$CANDIDATE_ROOT/candidate-checkpoint.json" "$WHEEL" >"$EVIDENCE_ROOT/artifacts/candidate-pins-after.sha256"
systemctl --user show hermes-gateway-dualcoachtest.service -p ActiveState -p SubState -p MainPID >"$EVIDENCE_ROOT/artifacts/service-after.txt" 2>&1 || true
chmod 600 "$EVIDENCE_ROOT/artifacts"/* 2>/dev/null || true
