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

# verify-update.sh - Verify OpenCode installation after rebuild
#
# Usage: verify-update.sh <expected-version>
#
# Example: verify-update.sh 1.0.58
#
# Exit codes:
#   0 - Verification succeeded
#   1 - Verification failed or error

# Check arguments
if [[ $# -ne 1 ]]; then
  echo "Error: Missing required argument" >&2
  echo "Usage: $0 <expected-version>" >&2
  echo "Example: $0 1.0.58" >&2
  exit 1
fi

EXPECTED_VERSION="$1"

# Validate version format
if ! echo "$EXPECTED_VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
  echo "Error: Invalid version format '$EXPECTED_VERSION' (expected X.Y.Z)" >&2
  exit 1
fi

# Check dependencies
for cmd in timeout grep; do
  if ! command -v "$cmd" >/dev/null 2>&1; then
    echo "Error: Required command '$cmd' not found" >&2
    exit 1
  fi
done

# Check if opencode is available
if ! command -v opencode >/dev/null 2>&1; then
  echo "Error: opencode command not found in PATH" >&2
  echo "       Ensure NixOS rebuild completed successfully" >&2
  exit 1
fi

# Query OpenCode version with timeout
# Output varies by version, extract first semver match
ACTUAL_VERSION=$(timeout 5 opencode --version 2>&1 | grep -oP '\d+\.\d+\.\d+' | head -1 || true)

if [[ -z "$ACTUAL_VERSION" ]]; then
  echo "Error: Could not determine OpenCode version" >&2
  echo "       Command 'opencode --version' failed or returned unexpected format" >&2
  exit 1
fi

# Compare versions
if [[ "$ACTUAL_VERSION" == "$EXPECTED_VERSION" ]]; then
  echo "✓ Verification succeeded"
  echo "  OpenCode version: $ACTUAL_VERSION"
  exit 0
else
  echo "✗ Verification failed" >&2
  echo "  Expected: $EXPECTED_VERSION" >&2
  echo "  Actual:   $ACTUAL_VERSION" >&2
  exit 1
fi
