#!/bin/bash
set -euo pipefail

# Fresh install release gate.
# Run this on a clean profile (or after backing up/removing ~/.mugi) before shipping installer builds.

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
LOG_FILE="$HOME/.mugi/logs/backend.jsonl"

echo "[gate] Fresh-install E2E gate starting"
echo "[gate] 1) Reset ~/.mugi (manually or via scripts/fresh_install_smoke.sh)"
echo "[gate] 2) Launch app and complete Recommended setup"
echo "[gate] 3) Verify first message succeeds"

if [ ! -f "$LOG_FILE" ]; then
  echo "[gate] backend log not found at $LOG_FILE"
  echo "[gate] run the app once before checking this gate."
  exit 1
fi

if rg -n "\"summary\": \"Agent run failed\"" "$LOG_FILE" >/dev/null; then
  echo "[gate] FAIL: agent failure events found in backend log"
  exit 1
fi

if rg -n "apply_chat_template|multimodal stream|chat template" "$LOG_FILE" >/dev/null; then
  echo "[gate] FAIL: template/multimodal startup errors detected"
  exit 1
fi

echo "[gate] PASS: no startup chat failures detected in backend log"
echo "[gate] Recommended follow-up: run targeted tests once pytest is available:"
echo "        python3 -m pytest -q tests/test_mlx_download_progress.py tests/test_mlx_recommended_models.py"
