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

# Function to get version name and build number from pubspec.yaml
get_pubspec_version() {
    if [ -f "pubspec.yaml" ]; then
        # Extract the version line (handles leading spaces, trims comments)
        VERSION_LINE=$(grep "^[[:space:]]*version:" pubspec.yaml | head -n 1 | cut -d'#' -f1 | xargs)

        # Debug output
        echo "DEBUG: Found version line: '$VERSION_LINE'" >&2

        if [[ -n "$VERSION_LINE" ]]; then
            # Remove 'version:' prefix
            VERSION_VALUE=${VERSION_LINE#version:}
            VERSION_VALUE=$(echo "$VERSION_VALUE" | xargs) # Trim whitespace

            # Debug output
            echo "DEBUG: Extracted version value: '$VERSION_VALUE'" >&2

            # Split into version name and build number using string manipulation
            if [[ "$VERSION_VALUE" == *"+"* ]]; then
                # Has build number
                VERSION_NAME="${VERSION_VALUE%+*}"  # Everything before +
                BUILD_NUMBER="${VERSION_VALUE#*+}"  # Everything after +
            else
                # No build number
                VERSION_NAME="$VERSION_VALUE"
                BUILD_NUMBER="1"
            fi

            # Validate version format (x.y.z)
            if [[ "$VERSION_NAME" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
                echo "VERSION_NAME=$VERSION_NAME"
                echo "BUILD_NUMBER=$BUILD_NUMBER"
                return 0
            else
                echo "DEBUG: Invalid version format: '$VERSION_NAME'" >&2
            fi
        else
            echo "DEBUG: No version line found in pubspec.yaml" >&2
        fi
    else
        echo "DEBUG: pubspec.yaml file not found" >&2
    fi

    # Fallback if pubspec.yaml not found or invalid format
    echo "DEBUG: Using fallback values" >&2
    echo "VERSION_NAME=0.0.1"
    echo "BUILD_NUMBER=1"
}

# Function to get just the build number from pubspec.yaml
get_build_number() {
    local version_info
    version_info=$(get_pubspec_version)

    # Extract BUILD_NUMBER from the output
    echo "$version_info" | grep "BUILD_NUMBER=" | cut -d'=' -f2
}

# Function to increment build number in pubspec.yaml
increment_build_number() {
    if [ ! -f "pubspec.yaml" ]; then
        echo -e "${RED}Error: pubspec.yaml not found${NC}"
        return 1
    fi

    # Get current version info
    eval "$(get_pubspec_version)"

    # Increment build number
    local new_build_number=$((BUILD_NUMBER + 1))
    local new_version="${VERSION_NAME}+${new_build_number}"

    # Update pubspec.yaml
    if grep -q "^[[:space:]]*version:" pubspec.yaml; then
        # Use different sed syntax for macOS vs Linux
        if [[ "$OSTYPE" == "darwin"* ]]; then
            sed -i '' "s|^[[:space:]]*version:.*|version: $new_version|" pubspec.yaml
        else
            sed -i "s|^[[:space:]]*version:.*|version: $new_version|" pubspec.yaml
        fi

        echo -e "${GREEN}✅ Incremented build number: $BUILD_NUMBER → $new_build_number${NC}"
        echo -e "${YELLOW}Updated pubspec.yaml to version: $new_version${NC}"

        # Return the new build number
        echo "$new_build_number"
    else
        echo -e "${RED}Error: Could not find version line in pubspec.yaml${NC}"
        return 1
    fi
}

# Function to validate the presence of required files
validate_required_files() {
    local files=("$@")
    for file in "${files[@]}"; do
        if [ ! -f "$file" ]; then
            echo -e "${RED}Error: Required file not found - $file${NC}"
            exit 1
        fi
    done
}

# Validate required files
validate_required_files "android/app/upload-keystore.jks" "android/key.properties" "android/local.properties" "pubspec.yaml" "android/app/build.gradle"

# Get current version information from pubspec.yaml
echo -e "${YELLOW}Reading current version information from pubspec.yaml...${NC}"
eval "$(get_pubspec_version)"
echo -e "${YELLOW}Current version: $VERSION_NAME+$BUILD_NUMBER${NC}"

# Increment build number and update pubspec.yaml
echo -e "${YELLOW}Incrementing build number...${NC}"
NEW_BUILD_NUMBER=$(increment_build_number)

# Get updated version information
eval "$(get_pubspec_version)"
echo -e "${GREEN}New version: $VERSION_NAME+$BUILD_NUMBER${NC}"

# Update android/local.properties to match pubspec.yaml
echo -e "${YELLOW}Updating android/local.properties...${NC}"
sed -i '' "s|flutter.versionCode=.*|flutter.versionCode=$BUILD_NUMBER|" android/local.properties

# Change package name
echo -e "${YELLOW}Updating package name...${NC}"
fvm dart run change_app_package_name:main "com.lazycoders.fluentcommunity"

echo -e "${GREEN}✅ Building Android...${NC}"

gradle_file="android/app/build.gradle"
fvm flutter clean
fvm flutter pub get

# Check if 'signingConfigs { release' already exists in the gradle file using awk
if ! awk '/signingConfigs *{/{found=1} /release *{/{if (found) {print "found"; exit}}' "$gradle_file" | grep -q 'found'; then
    echo -e "${YELLOW}Adding signing configuration to build.gradle...${NC}"
    # If it does not exist, insert the signing configuration
    sed -i '' '/buildTypes {/i\
    \
    signingConfigs {\
        release {\
          keyAlias keystoreProperties['\''keyAlias'\'']\
          keyPassword keystoreProperties['\''keyPassword'\'']\
          storeFile keystoreProperties['\''storeFile'\''] ? file(keystoreProperties['\''storeFile'\'']) : null\
          storePassword keystoreProperties['\''storePassword'\'']\
        }\
    }\
    ' "$gradle_file"
else
    echo -e "${YELLOW}⚠️  Signing config already exists in build.gradle. Skipping addition.${NC}"
fi

# Update build type to use release signing configuration if not already set
if ! grep -q 'signingConfig signingConfigs.release' "$gradle_file"; then
    echo -e "${YELLOW}Updating signing configuration...${NC}"
    sed -i '' "s|signingConfig signingConfigs.debug|signingConfig signingConfigs.release|" "$gradle_file"
fi

# Build appbundle using the appropriate main file (always prod environment)
echo -e "${YELLOW}Building AAB for PRODUCTION environment${NC}"
fvm flutter build appbundle --release --dart-define=ENVIRONMENT=prod

# Create output filename with version info
OUTPUT_FILENAME="app_android_${VERSION_NAME}_build_${BUILD_NUMBER}.aab"

# Copy the app bundle to a versioned file
echo -e "${YELLOW}Copying build artifacts...${NC}"
cp build/app/outputs/bundle/release/app-release.aab "$OUTPUT_FILENAME"

# Copy to desktop
cp build/app/outputs/bundle/release/app-release.aab ~/Desktop/"$OUTPUT_FILENAME"

echo -e "${GREEN}✅ Android build completed! ✅${NC}\n"
echo -e "${YELLOW}🔗 Path to the generated AAB: $(pwd)/$OUTPUT_FILENAME${NC}\n"
echo -e "${YELLOW}🔗 Also copied to Desktop: ~/Desktop/$OUTPUT_FILENAME${NC}\n"