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

# check-version.sh - Compare current OpenCode version in Nix with latest GitHub release
#
# Usage: check-version.sh [--dotfiles PATH]
#
# Outputs: key=value pairs for parsing
#   current=X.Y.Z
#   latest=X.Y.Z
#   update_available=yes|no

# Default dotfiles path
DOTFILES_PATH="${HOME}/proj/dotfiles"

# Parse arguments
while [[ $# -gt 0 ]]; do
  case "$1" in
    --dotfiles)
      DOTFILES_PATH="$2"
      shift 2
      ;;
    *)
      echo "Error: Unknown argument '$1'" >&2
      echo "Usage: $0 [--dotfiles PATH]" >&2
      exit 1
      ;;
  esac
done

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

# Validate dotfiles path
NIX_FILE="${DOTFILES_PATH}/pkgs/opencode/default.nix"
if [[ ! -f "$NIX_FILE" ]]; then
  echo "Error: Nix file not found at $NIX_FILE" >&2
  exit 1
fi

# Extract current version from Nix file
CURRENT_VERSION=$(grep -oP 'version\s*=\s*"\K[^"]+' "$NIX_FILE" || true)
if [[ -z "$CURRENT_VERSION" ]]; then
  echo "Error: Could not parse version from $NIX_FILE" >&2
  exit 1
fi

# Query GitHub API for latest release
GITHUB_API="https://api.github.com/repos/sst/opencode/releases/latest"
LATEST_RELEASE=$(curl -s "$GITHUB_API" || true)
if [[ -z "$LATEST_RELEASE" ]]; then
  echo "Error: Failed to query GitHub API at $GITHUB_API" >&2
  exit 1
fi

# Extract version from tag_name (format: "v1.0.44" -> "1.0.44")
LATEST_VERSION=$(echo "$LATEST_RELEASE" | jq -r '.tag_name' | sed 's/^v//')
if [[ -z "$LATEST_VERSION" || "$LATEST_VERSION" == "null" ]]; then
  echo "Error: Could not parse latest version from GitHub API response" >&2
  exit 1
fi

# Compare versions using sort -V (version sort)
if [[ "$CURRENT_VERSION" == "$LATEST_VERSION" ]]; then
  UPDATE_AVAILABLE="no"
else
  # Check if latest is newer than current
  NEWER=$(printf "%s\n%s" "$CURRENT_VERSION" "$LATEST_VERSION" | sort -V | tail -1)
  if [[ "$NEWER" == "$LATEST_VERSION" ]]; then
    UPDATE_AVAILABLE="yes"
  else
    UPDATE_AVAILABLE="no"
  fi
fi

# Output results
echo "current=$CURRENT_VERSION"
echo "latest=$LATEST_VERSION"
echo "update_available=$UPDATE_AVAILABLE"
