#!/usr/bin/env bash
#
# syncMiseToml.sh
# Synchronizes mise.toml with version files (.node-version, .ruby-version, .java-version)
# to ensure consistency across version management systems.
#
# Usage:
#   ./scripts/syncMiseToml.sh
#   yarn sync-mise

set -euo pipefail

# Get script directory and project root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Version files
NODE_VERSION_FILE="$PROJECT_ROOT/.node-version"
RUBY_VERSION_FILE="$PROJECT_ROOT/.ruby-version"
JAVA_VERSION_FILE="$PROJECT_ROOT/.java-version"
MISE_TOML="$PROJECT_ROOT/mise.toml"

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo "🔄 Synchronizing mise.toml with version files..."
echo ""

# Check if version files exist
if [ ! -f "$NODE_VERSION_FILE" ]; then
    echo -e "${RED}❌ Error: .node-version file not found${NC}"
    exit 1
fi

if [ ! -f "$RUBY_VERSION_FILE" ]; then
    echo -e "${RED}❌ Error: .ruby-version file not found${NC}"
    exit 1
fi

if [ ! -f "$JAVA_VERSION_FILE" ]; then
    echo -e "${RED}❌ Error: .java-version file not found${NC}"
    exit 1
fi

if [ ! -f "$MISE_TOML" ]; then
    echo -e "${RED}❌ Error: mise.toml file not found${NC}"
    exit 1
fi

# Read versions from files
NODE_VERSION=$(cat "$NODE_VERSION_FILE" | tr -d '[:space:]')
RUBY_VERSION=$(cat "$RUBY_VERSION_FILE" | tr -d '[:space:]')
JAVA_VERSION=$(cat "$JAVA_VERSION_FILE" | tr -d '[:space:]')

echo -e "${BLUE}📖 Reading version files:${NC}"
echo "   Node.js: $NODE_VERSION"
echo "   Ruby:    $RUBY_VERSION"
echo "   Java:    $JAVA_VERSION"
echo ""

# Convert Java version to mise format
# Examples:
#   17.0.17-amzn -> corretto-17.0.17.10.1
#   11.0.21-amzn -> corretto-11.0.21.9.1
convert_java_version() {
    local version="$1"

    # If already in corretto format, return as-is
    if [[ "$version" == corretto-* ]]; then
        echo "$version"
        return
    fi

    # Handle -amzn suffix (Amazon Corretto)
    if [[ "$version" == *-amzn ]]; then
        local base_version="${version%-amzn}"

        # Try to get exact Corretto build version from SDKMAN if available
        if command -v sdk >/dev/null 2>&1 && [ -s "$HOME/.sdkman/bin/sdkman-init.sh" ]; then
            set +u
            # shellcheck disable=SC1090
            source "$HOME/.sdkman/bin/sdkman-init.sh" 2>/dev/null || true

            # List available Corretto versions matching the base version
            local corretto_version
            corretto_version=$(sdk list java 2>/dev/null | grep -i corretto | grep "^[[:space:]]*${base_version}" | awk '{print $NF}' | head -1 || echo "")

            set -u

            if [ -n "$corretto_version" ]; then
                echo "$corretto_version"
                return
            fi
        fi

        # Fallback: construct corretto version from base version
        # Amazon Corretto versions follow pattern: base_version.build.patch
        # We'll use a reasonable default build number
        echo "corretto-${base_version}.10.1"
        return
    fi

    # For other formats, return as-is
    echo "$version"
}

MISE_JAVA_VERSION=$(convert_java_version "$JAVA_VERSION")

echo -e "${BLUE}🔧 Converting Java version for mise:${NC}"
echo "   $JAVA_VERSION -> $MISE_JAVA_VERSION"
echo ""

# Create backup of mise.toml
BACKUP_FILE="${MISE_TOML}.backup.$(date +%Y%m%d_%H%M%S)"
cp "$MISE_TOML" "$BACKUP_FILE"
echo -e "${YELLOW}💾 Created backup: ${BACKUP_FILE}${NC}"
echo ""

# Update mise.toml
# Use a temporary file to ensure atomic update
TEMP_FILE=$(mktemp)

# Read mise.toml and update versions
while IFS= read -r line; do
    if [[ "$line" =~ ^node[[:space:]]*=[[:space:]]*\".*\".*$ ]]; then
        echo "node = \"$NODE_VERSION\""
    elif [[ "$line" =~ ^ruby[[:space:]]*=[[:space:]]*\".*\".*$ ]]; then
        echo "ruby = \"$RUBY_VERSION\""
    elif [[ "$line" =~ ^java[[:space:]]*=[[:space:]]*\".*\".*$ ]]; then
        echo "java = \"$MISE_JAVA_VERSION\"   # JDK vendor/version ($JAVA_VERSION)"
    else
        echo "$line"
    fi
done < "$MISE_TOML" > "$TEMP_FILE"

# Replace original file
mv "$TEMP_FILE" "$MISE_TOML"

echo -e "${GREEN}✅ Successfully updated mise.toml${NC}"
echo ""

# Show the updated versions
echo -e "${BLUE}📝 Updated mise.toml [tools] section:${NC}"
grep -A 10 '^\[tools\]' "$MISE_TOML" | grep -v '^$' || true
echo ""

# Verify the changes
echo -e "${BLUE}🔍 Verifying changes:${NC}"
MISE_NODE=$(grep '^node' "$MISE_TOML" | sed 's/.*"\(.*\)".*/\1/')
MISE_RUBY=$(grep '^ruby' "$MISE_TOML" | sed 's/.*"\(.*\)".*/\1/')
MISE_JAVA=$(grep '^java' "$MISE_TOML" | sed 's/.*"\(.*\)".*/\1/')

if [ "$MISE_NODE" = "$NODE_VERSION" ]; then
    echo -e "   Node.js: ${GREEN}✅ $MISE_NODE${NC}"
else
    echo -e "   Node.js: ${RED}❌ Mismatch: $MISE_NODE vs $NODE_VERSION${NC}"
fi

if [ "$MISE_RUBY" = "$RUBY_VERSION" ]; then
    echo -e "   Ruby:    ${GREEN}✅ $MISE_RUBY${NC}"
else
    echo -e "   Ruby:    ${RED}❌ Mismatch: $MISE_RUBY vs $RUBY_VERSION${NC}"
fi

if [ "$MISE_JAVA" = "$MISE_JAVA_VERSION" ]; then
    echo -e "   Java:    ${GREEN}✅ $MISE_JAVA${NC}"
else
    echo -e "   Java:    ${RED}❌ Mismatch: $MISE_JAVA vs $MISE_JAVA_VERSION${NC}"
fi

echo ""
echo -e "${GREEN}✨ Synchronization complete!${NC}"
echo ""
echo -e "${YELLOW}💡 Next steps:${NC}"
echo "   1. Review the changes: git diff mise.toml"
echo "   2. Run mise to update tools: mise install"
echo "   3. Commit the changes: git commit mise.toml"
