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

if [[ $# -lt 2 ]]; then
  echo "Usage: ./tools/experiment-run.sh <profile> <udid> [org]"
  echo "Profiles: current, legacy, partial-safe, partial-lite"
  exit 2
fi

profile="$1"
udid="$2"
org="${3:-ReBreak}"

ts="$(date +%Y%m%d-%H%M%S)"
run_id="${ts}-${profile}"
run_dir="tools/runs/${run_id}"
mkdir -p "$run_dir"

console_log="$run_dir/console.log"
summary_file="$run_dir/summary.txt"
meta_file="$run_dir/meta.env"
obs_file="$run_dir/user-observation.md"

{
  echo "RUN_ID=$run_id"
  echo "TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  echo "PROFILE=$profile"
  echo "UDID=$udid"
  echo "ORG=$org"
  echo "PWD=$PWD"
  echo "GIT_HEAD=$(git rev-parse --short HEAD 2>/dev/null || echo unknown)"
  echo "AB_SERVE_TIMEOUT_SEC=${AB_SERVE_TIMEOUT_SEC:-240}"
} > "$meta_file"

cat > "$obs_file" <<'EOF'
# User Observation

- First screen after reboot:
- "iPhone ist teilweise eingerichtet" shown (yes/no):
- Next screen (Apple Intelligence / Kamera / SOS / Registrierung):
- Sprache korrekt (yes/no):
- Region korrekt (yes/no):
- Apple-Account bleibt eingeloggt (yes/no):
- Additional notes:
EOF

echo "[experiment] run_id=$run_id"
echo "[experiment] profile=$profile udid=$udid org=$org"
echo "[experiment] writing logs to $console_log"

set +e
./tools/ab-profile.sh "$profile" "$udid" "$org" 2>&1 | tee "$console_log"
run_exit=${pipestatus[1]}
set -e

verdict="UNKNOWN"
if grep -q "MBErrorDomain/211" "$console_log"; then
  verdict="BLOCKED_FMI"
elif grep -q "InvalidHostID" "$console_log"; then
  verdict="BLOCKED_PAIRING"
elif grep -q "serve timeout" "$console_log"; then
  verdict="BLOCKED_SERVE_TIMEOUT"
elif grep -q "DONE — Settings should show" "$console_log"; then
  verdict="TECH_SUCCESS"
fi

{
  echo "run_id=$run_id"
  echo "exit_code=$run_exit"
  echo "verdict=$verdict"
  echo "console_log=$console_log"
  echo "meta=$meta_file"
  echo "user_observation=$obs_file"
} > "$summary_file"

cat "$summary_file"

echo "[experiment] fill UI results in $obs_file"

exit "$run_exit"
