#!/bin/bash
# scripts/fresh_install_smoke.sh — Simulate a fresh install for testing first-run and onboarding.
#
# Backs up ~/.mugi, clears it, then optionally launches the app. Use this to verify:
# - Python bootstrap (download or extract)
# - Backend venv creation (~/.mugi/venv)
# - Mugi Homebrew + Pillow build deps
# - Workspace and template creation (BOOTSTRAP.md, etc.)
# - Onboarding UI flow
# - LLM setup (llmster, model download) — do manually in Settings
# - Agent BOOTSTRAP ritual — send first message in a new chat
#
# Usage:
#   ./scripts/fresh_install_smoke.sh           # Backup, clear, then prompt to launch
#   ./scripts/fresh_install_smoke.sh --launch  # Same, then run `make run-swift`
#   ./scripts/fresh_install_smoke.sh --restore # Restore from most recent backup
#
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
MUGI_DIR="$HOME/.mugi"
BACKUP_PREFIX="$HOME/.mugi_fresh_test_backup"

restore() {
    local latest
    latest=$(ls -td "$BACKUP_PREFIX"_* 2>/dev/null | head -1)
    if [ -z "$latest" ]; then
        echo "No backup found."
        exit 1
    fi
    if [ -d "$MUGI_DIR" ]; then
        echo "Removing current $MUGI_DIR..."
        rm -rf "$MUGI_DIR"
    fi
    echo "Restoring from $latest..."
    mv "$latest" "$MUGI_DIR"
    echo "Restored. You can launch Mugi again."
}

if [ "$1" = "--restore" ]; then
    restore
    exit 0
fi

if [ -d "$MUGI_DIR" ]; then
    TS=$(date +%Y%m%d_%H%M%S)
    BACKUP="${BACKUP_PREFIX}_${TS}"
    echo "Backing up $MUGI_DIR to $BACKUP..."
    mv "$MUGI_DIR" "$BACKUP"
    echo "Backup done."
else
    echo "No existing $MUGI_DIR. Starting fresh."
fi

echo ""
echo "Mugi data cleared. On first launch the app will:"
echo "  1. Download or extract Python (~/.mugi/python-3.12)"
echo "  2. Create backend venv (~/.mugi/venv) and pip install"
echo "  3. Create workspace and templates (BOOTSTRAP.md, etc.)"
echo "  4. Show onboarding walkthrough"
echo ""
echo "After that, go to Settings → LLMs to install llmster and a model."
echo "Then open a new chat and let the agent run the BOOTSTRAP ritual."
echo ""

if [ "$1" = "--launch" ]; then
    echo "Launching Mugi..."
    cd "$REPO_ROOT"
    make run-swift
else
    echo "To launch Mugi:  make run-swift"
    echo "To restore your previous ~/.mugi:  $0 --restore"
fi
