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

# usage-example.sh - Complete workflow demonstration for update-opencode skill
#
# This script demonstrates the full update workflow:
# 1. Check current vs latest version
# 2. Fetch SHA256 for new version
# 3. Update Nix file (dry-run, then actual)
# 4. Trigger system rebuild
# 5. Verify installation
#
# NOTE: This is a demonstration script. In production, steps 3-5 should only
#       run after user confirmation due to system rebuild impact.

SCRIPTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../scripts" && pwd)"
DOTFILES_PATH="${DOTFILES_PATH:-$HOME/proj/dotfiles}"

echo "=== OpenCode Update Workflow Demo ==="
echo ""

# Step 1: Check for updates
echo "Step 1: Checking current version vs latest..."
VERSION_INFO=$("$SCRIPTS_DIR/check-version.sh" --dotfiles "$DOTFILES_PATH")
echo "$VERSION_INFO"
echo ""

# Parse version info
CURRENT=$(echo "$VERSION_INFO" | grep '^current=' | cut -d= -f2)
LATEST=$(echo "$VERSION_INFO" | grep '^latest=' | cut -d= -f2)
UPDATE_AVAILABLE=$(echo "$VERSION_INFO" | grep '^update_available=' | cut -d= -f2)

if [[ "$UPDATE_AVAILABLE" != "yes" ]]; then
  echo "✓ Already on latest version ($CURRENT)"
  exit 0
fi

echo "Update available: $CURRENT → $LATEST"
echo ""

# Step 2: Fetch SHA256 hash
echo "Step 2: Fetching SHA256 hash for version $LATEST..."
SHA256=$("$SCRIPTS_DIR/fetch-sha256.sh" "$LATEST")
echo "SHA256: $SHA256"
echo ""

# Step 3a: Preview changes (dry-run)
echo "Step 3a: Previewing Nix file changes (dry-run)..."
"$SCRIPTS_DIR/update-nix-file.sh" "$LATEST" "$SHA256" --dotfiles "$DOTFILES_PATH" --dry-run
echo ""

# Step 3b: Apply changes
echo "Step 3b: Applying Nix file updates..."
echo "⚠️  WARNING: This would modify $DOTFILES_PATH/pkgs/opencode/default.nix"
echo "⚠️  In a real workflow, ask user for confirmation before proceeding."
echo ""
read -p "Continue with file update? (y/N) " -n 1 -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  echo "Aborted by user"
  exit 1
fi

"$SCRIPTS_DIR/update-nix-file.sh" "$LATEST" "$SHA256" --dotfiles "$DOTFILES_PATH"
echo ""

# Step 4: Rebuild system
echo "Step 4: Triggering system rebuild..."
echo "⚠️  WARNING: This will run 'sudo nixos-rebuild switch'"
echo "⚠️  This may take several minutes and will modify your system."
echo ""
read -p "Continue with system rebuild? (y/N) " -n 1 -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  echo "Aborted by user"
  echo "⚠️  Nix file has been updated but system not rebuilt."
  echo "   Run manually: cd $DOTFILES_PATH && sudo nixos-rebuild switch --flake .#<hostname>"
  exit 1
fi

cd "$DOTFILES_PATH"
HOSTNAME=$(hostname)
sudo nixos-rebuild switch --flake ".#$HOSTNAME"
echo ""

# Step 5: Verify installation
echo "Step 5: Verifying installation..."
"$SCRIPTS_DIR/verify-update.sh" "$LATEST"
echo ""

echo "=== Update Complete ==="
echo "OpenCode has been updated from $CURRENT to $LATEST"
