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

DRY_RUN=false

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --dry-run|-n)
            DRY_RUN=true
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --dry-run, -n    Show what would be updated without making changes"
            echo "  --help, -h       Show this help message"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

CASK_URL="https://raw.githubusercontent.com/Homebrew/homebrew-cask/HEAD/Casks/c/claude-code.rb"
REPO_ROOT="${REPO_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"
NIX_FILE="$REPO_ROOT/packages/claude-code/default.nix"

echo "Fetching latest claude-code version from Homebrew cask..."

# Fetch the cask file
CASK_CONTENT=$(curl -fsSL "$CASK_URL")

# Extract version (format: version "X.Y.Z")
NEW_VERSION=$(echo "$CASK_CONTENT" | grep -m1 'version' | sed -E 's/.*version "([^"]+)".*/\1/')

# Extract SHA256 hashes (be specific to match sha256 lines only)
SHA_ARM=$(echo "$CASK_CONTENT" | grep 'sha256 arm:' | sed -E 's/.*"([a-f0-9]{64})".*/\1/')
SHA_X86_64=$(echo "$CASK_CONTENT" | grep 'x86_64:' | sed -E 's/.*"([a-f0-9]{64})".*/\1/')
SHA_X86_64_LINUX=$(echo "$CASK_CONTENT" | grep 'x86_64_linux:' | sed -E 's/.*"([a-f0-9]{64})".*/\1/')
SHA_ARM64_LINUX=$(echo "$CASK_CONTENT" | grep 'arm64_linux:' | sed -E 's/.*"([a-f0-9]{64})".*/\1/')

# Get current version
CURRENT_VERSION=$(grep -m1 'version = ' "$NIX_FILE" | sed -E 's/.*version = "([^"]+)".*/\1/')

# Validate extracted data
if [ -z "$NEW_VERSION" ] || [ -z "$SHA_ARM" ] || [ -z "$SHA_X86_64" ] || [ -z "$SHA_X86_64_LINUX" ] || [ -z "$SHA_ARM64_LINUX" ]; then
    echo -e "${RED}Error: Failed to extract all required values from Homebrew cask${NC}"
    echo "Version: $NEW_VERSION"
    echo "ARM: $SHA_ARM"
    echo "x86_64: $SHA_X86_64"
    echo "x86_64_linux: $SHA_X86_64_LINUX"
    echo "arm64_linux: $SHA_ARM64_LINUX"
    exit 1
fi

# Check if update is needed
if [ "$CURRENT_VERSION" = "$NEW_VERSION" ]; then
    echo -e "${GREEN}Already up to date: $CURRENT_VERSION${NC}"
    exit 0
fi

echo -e "${YELLOW}Updating from $CURRENT_VERSION to $NEW_VERSION${NC}"

if [ "$DRY_RUN" = true ]; then
    echo -e "${YELLOW}DRY RUN - No changes will be made${NC}"
    echo ""
    echo "Would update:"
    echo "  Version: $CURRENT_VERSION -> $NEW_VERSION"
    echo "  aarch64-darwin SHA: $SHA_ARM"
    echo "  x86_64-darwin SHA:  $SHA_X86_64"
    echo "  x86_64-linux SHA:   $SHA_X86_64_LINUX"
    echo "  aarch64-linux SHA:  $SHA_ARM64_LINUX"
    exit 0
fi

# Update version
sed -i.tmp "s/version = \".*\";/version = \"$NEW_VERSION\";/" "$NIX_FILE"

# Update SHA256 hashes using awk for more reliable parsing
awk -v sha_arm="$SHA_ARM" -v sha_x86="$SHA_X86_64" -v sha_x86_linux="$SHA_X86_64_LINUX" -v sha_arm_linux="$SHA_ARM64_LINUX" '
/aarch64-darwin = {/ { in_arm = 1 }
/x86_64-darwin = {/ { in_x86 = 1 }
/x86_64-linux = {/ { in_x86_linux = 1 }
/aarch64-linux = {/ { in_arm_linux = 1 }
/};/ {
  in_arm = 0
  in_x86 = 0
  in_x86_linux = 0
  in_arm_linux = 0
}
/sha256 = / {
  if (in_arm) {
    sub(/sha256 = ".*";/, "sha256 = \"" sha_arm "\";")
  } else if (in_x86) {
    sub(/sha256 = ".*";/, "sha256 = \"" sha_x86 "\";")
  } else if (in_x86_linux) {
    sub(/sha256 = ".*";/, "sha256 = \"" sha_x86_linux "\";")
  } else if (in_arm_linux) {
    sub(/sha256 = ".*";/, "sha256 = \"" sha_arm_linux "\";")
  }
}
{ print }
' "$NIX_FILE" > "$NIX_FILE.new"

mv "$NIX_FILE.new" "$NIX_FILE"

# Clean up temp files
rm -f "$NIX_FILE.tmp"

echo -e "${GREEN}Successfully updated to version $NEW_VERSION${NC}"
echo ""
echo "Updated SHA256 hashes:"
echo "  aarch64-darwin: $SHA_ARM"
echo "  x86_64-darwin:  $SHA_X86_64"
echo "  x86_64-linux:   $SHA_X86_64_LINUX"
echo "  aarch64-linux:  $SHA_ARM64_LINUX"
echo ""
echo "Next steps:"
echo "  1. Review changes: git diff $NIX_FILE"
echo "  2. Test build: NIXPKGS_ALLOW_UNFREE=1 nix-build -E 'with import <nixpkgs> { config.allowUnfree = true; }; callPackage ./packages/claude-code {}'"
echo "  3. Verify version: ./result/bin/claude --version"
echo "  4. Commit: git add $NIX_FILE && git commit -m 'claude-code: Update to version $NEW_VERSION'"
