#!/bin/bash

# ======================================
# CONSTANTS AND SETUP
# ======================================

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

# Set up logging
LOG_FILE="build_flow_$(date +%Y%m%d_%H%M%S).log"
timeStamp=$(date +%Y%m%d_%H%M%S)

# ======================================
# LOGGING FUNCTIONS
# ======================================

# Function to log messages with timestamps
log() {
    local level="$1"
    local message="$2"
    local color="$NC"

    case "$level" in
        "INFO") color="$GREEN" ;;
        "WARN") color="$YELLOW" ;;
        "ERROR") color="$RED" ;;
    esac

    # Format the log entry
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local colored_entry="[${timestamp}] ${color}${level}${NC}: ${message}"
    local plain_entry="[${timestamp}] ${level}: ${message}"

    # Output to console with colors
    echo -e "${colored_entry}"

    # Output to log file without colors
    # echo "${plain_entry}" >> "${LOG_FILE}"
}

# Error handler function
handle_error() {
    local line="$1"
    local command="$2"
    local code="$3"
    log "ERROR" "Command '${command}' failed with exit code ${code} at line ${line}"
    exit "$code"
}

# ======================================
# ENVIRONMENT SETUP
# ======================================

# Configure error handling
setup_error_handling() {
    # Enable exit on error and undefined variables
    set -e  # Exit immediately if a command exits with non-zero status
    set -u  # Treat unset variables as an error

    # Set up error trap
    trap 'handle_error ${LINENO} "$BASH_COMMAND" $?' ERR
}

# Find required tools and setup environment
setup_environment() {
    # Custom FVM absolute path
    local fvm_path="/opt/homebrew/bin/fvm"

    # Check if FVM exists at the given path
    local use_fvm=false
    if [ -x "$fvm_path" ]; then
        use_fvm=true
        log "INFO" "FVM detected at: $fvm_path"

        # Check if .fvmrc exists in the project
        if [ -f ".fvmrc" ]; then
            local fvm_version=$(grep -o '"flutter"[[:space:]]*:[[:space:]]*"[^"]*"' .fvmrc | cut -d'"' -f4)
            log "INFO" "FVM configuration found: Flutter $fvm_version"
        fi
    else
        log "WARN" "FVM not found at provided path. Using global Flutter/Dart installation"
    fi

    # -------------------------
    # Resolve Flutter path
    # -------------------------
    if [ "$use_fvm" = true ]; then
        env_flutter="$fvm_path flutter"
        log "INFO" "Using FVM Flutter command: $env_flutter"
    elif command -v flutter &> /dev/null; then
        env_flutter=$(which flutter)
        log "INFO" "Found Flutter at: $env_flutter"
    else
        log "WARN" "Flutter not found in PATH. Using default path."
        env_flutter="/Users/$(whoami)/development/flutter/bin/flutter"
    fi

    # -------------------------
    # Resolve Dart path
    # -------------------------
    if [ "$use_fvm" = true ]; then
        env_dart="$fvm_path dart"
        log "INFO" "Using FVM Dart command: $env_dart"
    elif command -v dart &> /dev/null; then
        env_dart=$(which dart)
        log "INFO" "Found Dart at: $env_dart"
    else
        log "WARN" "Dart not found in PATH. Using default path."
        env_dart="/Users/$(whoami)/development/flutter/bin/dart"
    fi

    # -------------------------
    # Pod
    # -------------------------
    if command -v pod &> /dev/null; then
        env_pod=$(which pod)
        log "INFO" "Found Pod at: $env_pod"
    else
        log "WARN" "Pod not found in PATH. Using default path."
        env_pod="/usr/local/bin/pod"
    fi

    # -------------------------
    # Fastlane
    # -------------------------
    if command -v fastlane &> /dev/null; then
        env_fastlane=$(which fastlane)
        log "INFO" "Found Fastlane at: $env_fastlane"
    else
        log "WARN" "Fastlane not found in PATH. Using default path."
        env_fastlane="/opt/homebrew/bin/fastlane"
    fi

    # -------------------------
    # Security
    # -------------------------
    if command -v security &> /dev/null; then
        env_security=$(which security)
        log "INFO" "Found Security at: $env_security"
    else
        log "WARN" "Security not found in PATH. Using default path."
        env_security="/usr/bin/security"
    fi

    # -------------------------
    # Python 3
    # -------------------------
    if command -v python3 &> /dev/null; then
        env_python3=$(which python3)
        log "INFO" "Found Python3 at: $env_python3"
    else
        log "WARN" "Python3 not found in PATH. Using default path."
        env_python3="/opt/homebrew/bin/python3"
    fi

    # User
    current_user=$(whoami)

    # -------------------------
    # Summary
    # -------------------------
    log "INFO" "Environment Setup Complete"
    log "INFO" "========================================"
    log "INFO" "Build Environment Summary"
    log "INFO" "========================================"
    log "INFO" "User: $current_user"
    log "INFO" "Timestamp: $timeStamp"
    log "INFO" "Log File: $LOG_FILE"
    log "INFO" "----------------------------------------"
    log "INFO" "Tool Paths:"
    log "INFO" "  Flutter: $env_flutter"
    log "INFO" "  Dart: $env_dart"
    log "INFO" "  Pod: $env_pod"
    log "INFO" "  Fastlane: $env_fastlane"
    log "INFO" "  Security: $env_security"
    log "INFO" "  Python3: $env_python3"
    log "INFO" "========================================"
}

# ======================================
# ARGUMENT HANDLING
# ======================================

# Initialize variables
PACKAGE_NAME=""
APP_NAME=""
DOMAIN=""
APP_LICENSE_CHECK_URL=""
BASE_SUFFIX=""
BASE_URL=""
BUILD_NUMBER=""
SHOULD_BUILD_ANDROID=false
SHOULD_BUILD_IOS=false
HAS_PUSH_NOTIFICATION=false
HAS_GOOGLE_LOGIN=false
GOOGLE_WEB_CLIENT_ID=""
GOOGLE_IOS_CLIENT_ID=""
KEY_ID=""
ISSUER_ID=""
KEY_FILEPATH=""
APP_IDENTIFIER=""
TEAM_ID=""

# Function to display usage
usage() {
    echo -e "${YELLOW}Usage: $0 [OPTIONS]${NC}"
    echo ""
    echo -e "${GREEN}Required Options:${NC}"
    echo "  --app-name <NAME>           Application display name"
    echo "  --domain <URL>              API domain (e.g., https://api.example.com)"
    echo "  --app-license-check-url <URL>  License check endpoint"
    echo "  --base-suffix <PATH>        API base path (e.g., /api/v1)"
    echo "  --base-url <URL>            Base URL for app"
    echo "  --build-number <NUMBER>     Build number (integer)"
    echo ""
    echo -e "${GREEN}Platform Options (at least one required):${NC}"
    echo "  --should-build-android      Build for Android"
    echo "  --should-build-ios          Build for iOS"
    echo ""
    echo -e "${GREEN}Android-Specific Options (required if building Android):${NC}"
    echo "  --package-name <NAME>       Android package name (e.g., com.example.app)"
    echo ""
    echo -e "${GREEN}iOS-Specific Options (required if building iOS):${NC}"
    echo "  --key-id <ID>              App Store Connect API Key ID"
    echo "  --issuer-id <ID>           App Store Connect Issuer ID"
    echo "  --key-filepath <PATH>      Path to .p8 key file (relative to ios/)"
    echo "  --app-identifier <ID>      iOS Bundle ID (e.g., com.example.app)"
    echo "  --team-id <ID>             Apple Developer Team ID"
    echo ""
    echo -e "${GREEN}Optional Features:${NC}"
    echo "  --has-push-notification     Enable Firebase push notifications"
    echo "  --has-google-login          Enable Google Sign-In"
    echo "  --google-web-client-id <ID> Google OAuth Web Client ID (required if --has-google-login)"
    echo "  --google-ios-client-id <ID> Google OAuth iOS Client ID (required for iOS with Google login)"
    echo ""
    echo -e "${YELLOW}Examples:${NC}"
    echo ""
    echo -e "  ${GREEN}# Android only build${NC}"
    echo "  $0 --should-build-android \\"
    echo "     --package-name com.example.myapp \\"
    echo "     --app-name \"My App\" \\"
    echo "     --domain https://api.example.com \\"
    echo "     --app-license-check-url https://license.example.com \\"
    echo "     --base-suffix /api/v1 \\"
    echo "     --base-url https://app.example.com \\"
    echo "     --build-number 42"
    echo ""
    echo -e "  ${GREEN}# iOS only build with Google login${NC}"
    echo "  $0 --should-build-ios \\"
    echo "     --app-identifier com.example.myapp \\"
    echo "     --app-name \"My App\" \\"
    echo "     --domain https://api.example.com \\"
    echo "     --app-license-check-url https://license.example.com \\"
    echo "     --base-suffix /api/v1 \\"
    echo "     --base-url https://app.example.com \\"
    echo "     --build-number 42 \\"
    echo "     --key-id ABC123 \\"
    echo "     --issuer-id DEF456 \\"
    echo "     --key-filepath AuthKey_ABC123.p8 \\"
    echo "     --team-id GHI789 \\"
    echo "     --has-google-login \\"
    echo "     --google-web-client-id 123-xyz.apps.googleusercontent.com \\"
    echo "     --google-ios-client-id 456-abc.apps.googleusercontent.com"
    echo ""
    echo -e "  ${GREEN}# Both platforms with Firebase${NC}"
    echo "  $0 --should-build-android --should-build-ios \\"
    echo "     --package-name com.example.myapp \\"
    echo "     --app-identifier com.example.myapp \\"
    echo "     --app-name \"My App\" \\"
    echo "     --domain https://api.example.com \\"
    echo "     --app-license-check-url https://license.example.com \\"
    echo "     --base-suffix /api/v1 \\"
    echo "     --base-url https://app.example.com \\"
    echo "     --build-number 42 \\"
    echo "     --key-id ABC123 \\"
    echo "     --issuer-id DEF456 \\"
    echo "     --key-filepath AuthKey_ABC123.p8 \\"
    echo "     --team-id GHI789 \\"
    echo "     --has-push-notification"
    echo ""
    exit 1
}

# Function to validate required arguments
validate_required_arg() {
    local arg_name="$1"
    local arg_value="$2"
    if [ -z "$arg_value" ]; then
        log "ERROR" "Error: $arg_name is required."
        usage
    fi
}

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

# Function to parse script arguments
parse_args() {
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --package-name) PACKAGE_NAME="$2"; shift 2 ;;
            --app-name) APP_NAME="$2"; shift 2 ;;
            --domain) DOMAIN="$2"; shift 2 ;;
            --app-license-check-url) APP_LICENSE_CHECK_URL="$2"; shift 2 ;;
            --base-suffix) BASE_SUFFIX="$2"; shift 2 ;;
            --base-url) BASE_URL="$2"; shift 2 ;;
            --build-number) BUILD_NUMBER="$2"; shift 2 ;;
            --should-build-android) SHOULD_BUILD_ANDROID=true; shift ;;
            --should-build-ios) SHOULD_BUILD_IOS=true; shift ;;
            --has-push-notification) HAS_PUSH_NOTIFICATION=true; shift ;;
            --has-google-login) HAS_GOOGLE_LOGIN=true; shift ;;
            --google-web-client-id) GOOGLE_WEB_CLIENT_ID="$2"; shift 2 ;;
            --google-ios-client-id) GOOGLE_IOS_CLIENT_ID="$2"; shift 2 ;;
            --key-id) KEY_ID="$2"; shift 2 ;;
            --issuer-id) ISSUER_ID="$2"; shift 2 ;;
            --key-filepath) KEY_FILEPATH="$2"; shift 2 ;;
            --app-identifier) APP_IDENTIFIER="$2"; shift 2 ;;
            --team-id) TEAM_ID="$2"; shift 2 ;;
            *) log "ERROR" "Unknown parameter passed: $1"; usage ;;
        esac
    done
}

# Function to validate arguments
validate_args() {
    # Check if at least one platform is selected
    if [ "$SHOULD_BUILD_ANDROID" = false ] && [ "$SHOULD_BUILD_IOS" = false ]; then
        log "ERROR" "Error: At least one platform should be selected for build."
        usage
    fi

    # Validate required arguments
    validate_required_arg "APP_NAME" "$APP_NAME"
    validate_required_arg "DOMAIN" "$DOMAIN"
    validate_required_arg "APP_LICENSE_CHECK_URL" "$APP_LICENSE_CHECK_URL"
    validate_required_arg "BASE_SUFFIX" "$BASE_SUFFIX"
    validate_required_arg "BASE_URL" "$BASE_URL"
    validate_required_arg "BUILD_NUMBER" "$BUILD_NUMBER"

    # Validate android build arguments
    if [ "$SHOULD_BUILD_ANDROID" = true ]; then
        validate_required_arg "PACKAGE_NAME" "$PACKAGE_NAME"
        validate_required_files "android/app/upload-keystore.jks" "android/key.properties"
    fi

    # Validate iOS build arguments
    if [ "$SHOULD_BUILD_IOS" = true ]; then
        validate_required_arg "KEY_ID" "$KEY_ID"
        validate_required_arg "ISSUER_ID" "$ISSUER_ID"
        validate_required_arg "KEY_FILEPATH" "$KEY_FILEPATH"
        validate_required_arg "APP_IDENTIFIER" "$APP_IDENTIFIER"
        validate_required_arg "TEAM_ID" "$TEAM_ID"
        validate_required_files "ios/${KEY_FILEPATH}"
    fi

    # Validate Google login arguments
    if [ "$HAS_GOOGLE_LOGIN" = true ]; then
        validate_required_arg "GOOGLE_WEB_CLIENT_ID" "$GOOGLE_WEB_CLIENT_ID"

        # iOS Client ID is only required when building for iOS
        if [ "$SHOULD_BUILD_IOS" = true ]; then
            validate_required_arg "GOOGLE_IOS_CLIENT_ID" "$GOOGLE_IOS_CLIENT_ID"
        fi
    fi

    # Print argument summary
    log_args_summary
}

# Function to print argument summary
log_args_summary() {
    log "INFO" "  ${GREEN}✅ Arguments:${NC}"
    log "INFO" "  ${GREEN}timeStamp:${NC} $timeStamp"
    log "INFO" "  ${GREEN}APP_NAME:${NC} $APP_NAME"
    log "INFO" "  ${GREEN}DOMAIN:${NC} $DOMAIN"
    log "INFO" "  ${GREEN}APP_LICENSE_CHECK_URL:${NC} $APP_LICENSE_CHECK_URL"
    log "INFO" "  ${GREEN}BASE_SUFFIX:${NC} $BASE_SUFFIX"
    log "INFO" "  ${GREEN}BASE_URL:${NC} $BASE_URL"
    log "INFO" "  ${GREEN}BUILD_NUMBER:${NC} $BUILD_NUMBER"
    log "INFO" "  ${GREEN}HAS_PUSH_NOTIFICATION:${NC} $HAS_PUSH_NOTIFICATION"
    log "INFO" "  ${GREEN}HAS_GOOGLE_LOGIN:${NC} $HAS_GOOGLE_LOGIN"

    if [ "$SHOULD_BUILD_ANDROID" = true ]; then
        log "INFO" "  ${GREEN}PACKAGE_NAME:${NC} $PACKAGE_NAME"
    fi

    if [ "$SHOULD_BUILD_IOS" = true ]; then
        log "INFO" "  ${GREEN}KEY_ID:${NC} $KEY_ID"
        log "INFO" "  ${GREEN}ISSUER_ID:${NC} $ISSUER_ID"
        log "INFO" "  ${GREEN}KEY_FILEPATH:${NC} $KEY_FILEPATH"
        log "INFO" "  ${GREEN}APP_IDENTIFIER:${NC} $APP_IDENTIFIER"
        log "INFO" "  ${GREEN}TEAM_ID:${NC} $TEAM_ID"
    fi

    if [ "$HAS_GOOGLE_LOGIN" = true ]; then
        log "INFO" "  ${GREEN}GOOGLE_WEB_CLIENT_ID:${NC} $GOOGLE_WEB_CLIENT_ID"
        log "INFO" "  ${GREEN}GOOGLE_IOS_CLIENT_ID:${NC} $GOOGLE_IOS_CLIENT_ID"
    fi

    log "INFO" "✅ Successfully validated required files."
}

# ======================================
# APP CONFIGURATION FUNCTIONS
# ======================================

# Function to update app configuration
# Escape characters unsafe for sed replacement
escape_for_sed() {
    printf '%s\n' "$1" | sed -e 's/[&|\\]/\\&/g'
}

update_app_config() {
    local config_file="lib/data/services/network/api_config.dart"
    local license_check_file="lib/services/license_service/license_repository.dart"

    SAFE_APP_NAME=$(escape_for_sed "$APP_NAME")
    SAFE_DOMAIN=$(escape_for_sed "$DOMAIN")
    SAFE_BASE_SUFFIX=$(escape_for_sed "$BASE_SUFFIX")
    SAFE_LICENSE_URL=$(escape_for_sed "$APP_LICENSE_CHECK_URL")

    # Update API domain
    sed -i '' "s|String _domain = '[^']*';|String _domain = '$SAFE_DOMAIN';|" "$config_file"

    # Update base suffix
    sed -i '' "s|String _baseSuffix = '[^']*';|String _baseSuffix = '$SAFE_BASE_SUFFIX';|" "$config_file"

    # Update build number safely
    sed -i '' "s|^version: .*|version: 1.0.0+$BUILD_NUMBER|" pubspec.yaml

    # Update Flutter MaterialApp title
    sed -i '' "s|title: '[^']*',|title: '$SAFE_APP_NAME',|" lib/app_initializer.dart

    # Update license API
    sed -i '' "s|baseUrl: '[^']*',|baseUrl: '$SAFE_LICENSE_URL/api/appza/v1',|" "$license_check_file"

    log "INFO" "✅ Updated API configuration:"
    log "INFO" "  Domain: $DOMAIN"
    log "INFO" "  Base Suffix: $BASE_SUFFIX"
}

# Function to update package name
update_package_name() {
   local package_name="$1"
   $env_flutter clean
   $env_flutter pub get
   $env_dart run change_app_package_name:main "$package_name"
}

# ======================================
# PLATFORM-SPECIFIC BUILD FUNCTIONS
# ======================================

# Function to build Android app
build_android() {
    log "INFO" "✅ Building Android..."

    local gradle_file="android/app/build.gradle"

    # Switch to release signing configuration if not already set
    if ! grep -q 'signingConfig signingConfigs.release' "$gradle_file"; then
        sed -i '' "s|signingConfig signingConfigs.debug|signingConfig signingConfigs.release|" "$gradle_file"
    fi

    # Check if 'signingConfigs { release' exists, and add it if missing
    if ! awk '/signingConfigs *{/{found=1} /release *{/{if (found) {print "found"; exit}}' "$gradle_file" | grep -q 'found'; then
        # Insert signing configuration for release if it doesn't exist
        sed -i '' '/buildTypes {/i\
        \
        signingConfigs {\
            release {\
                keyAlias keystoreProperties['\''keyAlias'\'']\
                keyPassword keystoreProperties['\''keyPassword'\'']\
                storeFile keystoreProperties['\''storeFile'\''] ? file(keystoreProperties['\''storeFile'\'']) : null\
                storePassword keystoreProperties['\''storePassword'\'']\
            }\
        }\
        ' "$gradle_file"
    fi

    # Build App Bundle
    log "INFO" "Building Android App Bundle (.aab)..."
    $env_flutter build appbundle --release
    cp build/app/outputs/bundle/release/app-release.aab "app_android_$timeStamp.aab"
    log "INFO" "✅ Android App Bundle (.aab) build completed!"

    # Build APK
    log "INFO" "Building Android APK (.apk)..."
    $env_flutter build apk --release
    cp build/app/outputs/flutter-apk/app-release.apk "app_android_$timeStamp.apk"
    log "INFO" "✅ Android APK (.apk) build completed!"
    # We need to remove this exit 0 ,if we want to build both android and ios at the same time
    exit 0
}

# Function to handle keychain operations for iOS
delete_keychain() {
    local app_identifier="$1"
    if $env_security list-keychains | grep -q "$app_identifier-db"; then
        log "INFO" "Keychain $app_identifier-db exists, deleting it..."
        $env_security delete-keychain "$app_identifier-db"
    else
        log "WARN" "Keychain $app_identifier-db not found, proceeding without deletion..."
    fi
}

# Function to build iOS app
build_ios() {
    log "INFO" "✅ Building iOS..."
    log "INFO" "Current date and time: $(date '+%Y-%m-%d %H:%M:%S')"

    # If Podfile.lock exists, remove it
    if (cd ios && [ -f Podfile.lock ] && rm Podfile.lock); then
        log "INFO" "✅ Podfile.lock removed."
    else
        log "WARN" "⚠️ No Podfile.lock found in ios directory. Continuing without removing. ⚠️"
    fi

    # Print the current directory
    pwd

    # Clean Flutter and get packages
    if $env_flutter clean && $env_flutter pub get; then
        log "INFO" "✅ Flutter clean and pub get completed."
    else
        log "ERROR" "❌ Flutter clean or pub get failed. Exiting."
        exit 1
    fi

    # Navigate to ios directory, install pods, and check for success
    if (cd ios && $env_pod install); then
        log "INFO" "✅ Pods installed successfully."
    else
        log "ERROR" "❌ Pod installation failed. Exiting."
        exit 1
    fi

    # give permission to the ios directory
    chmod -R 777 ios

    # Run Fastlane inside the ios directory
    if cd ios && $env_fastlane ios release key_id:"$KEY_ID" issuer_id:"$ISSUER_ID" key_filepath:"$KEY_FILEPATH" app_identifier:"$APP_IDENTIFIER" team_id:"$TEAM_ID" has_push_notification:"$HAS_PUSH_NOTIFICATION" --verbose; then
        log "INFO" "✅ iOS build completed successfully!"
        delete_keychain "$APP_IDENTIFIER"
    else
        log "ERROR" "❌ iOS build failed. Please check the logs for details."
        delete_keychain "$APP_IDENTIFIER"
        exit 1
    fi

    log "INFO" "Current date and time: $(date '+%Y-%m-%d %H:%M:%S')"
    log "INFO" "✅ $APP_IDENTIFIER ✅"

    # Return to the previous directory, handling potential failure gracefully
    if cd ..; then
        log "INFO" "✅ Returned to the previous directory."
    else
        log "ERROR" "❌ Could not return to the previous directory. Exiting."
    fi

    # We need to remove this exit 0 ,if we want to build both android and ios at the same time
    exit 0
}

# Function to delete apple certificates
delete_apple_certificates() {
    local app_identifier="$1"
    local key_id="$2"
    local issuer_id="$3"
    local key_filepath="$4"

    # Check if running interactively (stdin is a tty)
    if ! [ -t 0 ]; then
        log "INFO" "Running non-interactively, skipping certificate deletion"
        return 0
    fi

    # Validate required parameters
    if [ -z "$app_identifier" ] || [ -z "$key_id" ] || [ -z "$issuer_id" ] || [ -z "$key_filepath" ]; then
        log "ERROR" "Missing required parameters for certificate deletion"
        log "ERROR" "Required: app_identifier, key_id, issuer_id, key_filepath"
        return 1
    fi

    # Check if deletion script exists
    local script_path="ios/delete_apple_certificates.py"
    if [ ! -f "$script_path" ]; then
        log "ERROR" "Certificate deletion script not found at: $script_path"
        return 1
    fi

    # Verify key file exists
    local full_key_path="ios/${key_filepath}"
    if [ ! -f "$full_key_path" ]; then
        log "ERROR" "Key file not found at: $full_key_path"
        return 1
    fi

    log "INFO" "Deleting Apple certificates for $app_identifier..."

    local env_manual_python3="/opt/homebrew/bin/python3"
    if $env_manual_python3 "$script_path" \
        --identifier "$app_identifier" \
        --key-id "$key_id" \
        --issuer-id "$issuer_id" \
        --key-filepath "$full_key_path"; then
        log "INFO" "✅ Apple certificates deleted successfully!"
        return 0
    else
        local exit_code=$?
        log "ERROR" "❌ Apple certificates deletion failed with code: $exit_code"
        return $exit_code
    fi
}

remove_firebase() {
      log "INFO" "Removing Firebase files..."

      # Get the script directory
      SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
      PROJECT_ROOT="$SCRIPT_DIR"

      # update has_firebase in lib/app_build_constant.dart to false
      sed -i '' "s|const hasFirebase = true;|const hasFirebase = false;|" lib/app_build_constant.dart

      FILES_TO_REMOVE=(
          "firebase.json"
          "android/app/google-services.json"
          "ios/Runner/GoogleService-Info.plist"
      )

      for file in "${FILES_TO_REMOVE[@]}"; do
          if [ -f "$PROJECT_ROOT/$file" ]; then
              rm "$PROJECT_ROOT/$file"
             log "INFO" "Removed: $file"
          else
              log "WARN" "Not found (skipping): $file"
          fi
      done

      echo ""

      # Update android/app/build.gradle - Remove Firebase plugins
      ANDROID_BUILD_GRADLE="$PROJECT_ROOT/android/app/build.gradle"
      if [ -f "$ANDROID_BUILD_GRADLE" ]; then
          # Create backup
          cp "$ANDROID_BUILD_GRADLE" "$ANDROID_BUILD_GRADLE.backup"

          # Remove Firebase plugin lines
          sed -i.tmp '/com.google.gms.google-services/d' "$ANDROID_BUILD_GRADLE"
          sed -i.tmp '/com.google.firebase.firebase-perf/d' "$ANDROID_BUILD_GRADLE"
          sed -i.tmp '/com.google.firebase.crashlytics/d' "$ANDROID_BUILD_GRADLE"
          sed -i.tmp '/START: FlutterFire Configuration/d' "$ANDROID_BUILD_GRADLE"
          sed -i.tmp '/END: FlutterFire Configuration/d' "$ANDROID_BUILD_GRADLE"

          # Remove temporary files created by sed
          rm -f "$ANDROID_BUILD_GRADLE.tmp"

          log "INFO" "Updated: android/app/build.gradle"
      else
          log "WARN" "Not found: android/app/build.gradle"
      fi

      echo ""

      # Update ios/Runner/AppDelegate.swift - Remove Firebase completely
      IOS_APP_DELEGATE="$PROJECT_ROOT/ios/Runner/AppDelegate.swift"
      if [ -f "$IOS_APP_DELEGATE" ]; then
          # Create backup
          cp "$IOS_APP_DELEGATE" "$IOS_APP_DELEGATE.backup"

          # Replace entire file with clean AppDelegate (no Firebase)
          cat > "$IOS_APP_DELEGATE" << 'EOF'
import Flutter
import UIKit

@main
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
EOF

          log "INFO" "Updated: ios/Runner/AppDelegate.swift (removed all Firebase code)"
      else
          log "WARN" "Not found: ios/Runner/AppDelegate.swift"
      fi

      echo ""

      # ios/Runner/Info.plist - Remove push notification configurations
      IOS_INFO_PLIST="$PROJECT_ROOT/ios/Runner/Info.plist"
      if [ -f "$IOS_INFO_PLIST" ]; then
          # Create backup
          cp "$IOS_INFO_PLIST" "$IOS_INFO_PLIST.backup"

          # Use PlistBuddy for safe plist manipulation (avoids sed corruption issues)
          local PLIST_BUDDY="/usr/libexec/PlistBuddy"

          # Remove FirebaseAppDelegateProxyEnabled if present (ignore errors if not found)
          $PLIST_BUDDY -c "Delete :FirebaseAppDelegateProxyEnabled" "$IOS_INFO_PLIST" 2>/dev/null || true

          # Remove remote-notification from UIBackgroundModes array
          # First, check if UIBackgroundModes exists and find the index of remote-notification
          local bg_modes_count=$($PLIST_BUDDY -c "Print :UIBackgroundModes" "$IOS_INFO_PLIST" 2>/dev/null | grep -c "remote-notification" || echo "0")
          if [ "$bg_modes_count" -gt 0 ]; then
              # Find and remove remote-notification entry
              local index=0
              while true; do
                  local value=$($PLIST_BUDDY -c "Print :UIBackgroundModes:$index" "$IOS_INFO_PLIST" 2>/dev/null) || break
                  if [ "$value" = "remote-notification" ]; then
                      $PLIST_BUDDY -c "Delete :UIBackgroundModes:$index" "$IOS_INFO_PLIST" 2>/dev/null || true
                      break
                  fi
                  index=$((index + 1))
                  # Safety limit
                  if [ $index -gt 20 ]; then break; fi
              done
          fi

          # Check if UIBackgroundModes is now empty and remove it if so
          local remaining_count=$($PLIST_BUDDY -c "Print :UIBackgroundModes" "$IOS_INFO_PLIST" 2>/dev/null | grep -c "    " || echo "0")
          if [ "$remaining_count" -eq 0 ]; then
              $PLIST_BUDDY -c "Delete :UIBackgroundModes" "$IOS_INFO_PLIST" 2>/dev/null || true
          fi

          # Validate the plist is still valid
          if plutil -lint "$IOS_INFO_PLIST" > /dev/null 2>&1; then
              log "INFO" "Updated: ios/Runner/Info.plist (removed push notification configurations)"
          else
              log "ERROR" "❌ Info.plist validation failed after Firebase removal"
              # Restore from backup
              cp "$IOS_INFO_PLIST.backup" "$IOS_INFO_PLIST"
              log "ERROR" "Restored Info.plist from backup"
          fi
      else
          log "WARN" "Not found: ios/Runner/Info.plist"
      fi

      echo ""

      # ios/Runner/Runner.entitlements - Remove push notification entitlements
      IOS_ENTITLEMENTS="$PROJECT_ROOT/ios/Runner/Runner.entitlements"
      if [ -f "$IOS_ENTITLEMENTS" ]; then
          # Create backup
          cp "$IOS_ENTITLEMENTS" "$IOS_ENTITLEMENTS.backup"

          # Replace with empty entitlements file (no push notifications)
          cat > "$IOS_ENTITLEMENTS" << 'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
</dict>
</plist>
EOF

          log "INFO" "Updated: ios/Runner/Runner.entitlements (removed aps-environment)"
      else
          log "WARN" "Not found: ios/Runner/Runner.entitlements"
      fi

      echo ""

      # ios/Runner.xcodeproj/project.pbxproj - Remove Firebase references
      XCODE_PROJECT="$PROJECT_ROOT/ios/Runner.xcodeproj/project.pbxproj"
      if [ -f "$XCODE_PROJECT" ]; then
          # Create backup
          cp "$XCODE_PROJECT" "$XCODE_PROJECT.backup"

          # Remove all lines containing GoogleService-Info.plist
          sed -i.tmp '/GoogleService-Info\.plist/d' "$XCODE_PROJECT"

          # Remove the entire FlutterFire script build phase block
          # IMPORTANT: Do this BEFORE removing the reference line, so the pattern can match
          # Uses generic pattern (not hardcoded ID) to handle future changes
          # This removes from the opening brace to the closing brace
          sed -i.tmp '/.*FlutterFire.*upload-crashlytics-symbols.*= {/,/^[[:space:]]*};$/d' "$XCODE_PROJECT"

          # Remove FlutterFire Crashlytics upload script reference from build phases
          # Uses generic pattern to match any FlutterFire upload-crashlytics-symbols reference
          sed -i.tmp '/.*FlutterFire.*upload-crashlytics-symbols/d' "$XCODE_PROJECT"

          # Remove temporary files
          rm -f "$XCODE_PROJECT.tmp"

          log "INFO" "Updated: ios/Runner.xcodeproj/project.pbxproj (removed GoogleService-Info.plist and FlutterFire build script)"
      else
          log "WARN" "Not found: ios/Runner.xcodeproj/project.pbxproj"
      fi



    # Clean Flutter and get packages
      if $env_flutter clean && $env_flutter pub get; then
          log "INFO" "✅ Flutter clean and pub get completed."
      else
          log "ERROR" "❌ Flutter clean or pub get failed. Exiting."
          exit 1
      fi

      log "INFO" "Firebase files removed successfully!"

  }

update_google_login() {
    log "INFO" "Configuring Google login..."

    # Get the script directory
    SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    PROJECT_ROOT="$SCRIPT_DIR"

    local web_client_id="$1"
    local ios_client_id="$2"

    # Validate required parameters
    if [ -z "$web_client_id" ]; then
        log "ERROR" "Web Client ID is required for Google login"
        log "ERROR" "Usage: update_google_login <WEB_CLIENT_ID> <IOS_CLIENT_ID>"
        exit 1
    fi

    # iOS Client ID is only required when building for iOS
    if [ "$SHOULD_BUILD_IOS" = true ] && [ -z "$ios_client_id" ]; then
        log "ERROR" "iOS Client ID is required for Google login when building for iOS"
        log "ERROR" "Usage: update_google_login <WEB_CLIENT_ID> <IOS_CLIENT_ID>"
        exit 1
    fi

    log "INFO" "Web Client ID: $web_client_id"

    # Only process iOS client ID if building for iOS
    if [ "$SHOULD_BUILD_IOS" = true ]; then
        # Extract the reversed iOS client ID for URL scheme
        # Format: com.googleusercontent.apps.XXXXXXXX-YYYYYYYY
        local reversed_ios_client_id=$(echo "$ios_client_id" | sed 's/\.apps\.googleusercontent\.com$//' | awk -F'.' '{print "com.googleusercontent.apps."$1}')

        log "INFO" "iOS Client ID: $ios_client_id"
        log "INFO" "Reversed iOS Client ID: $reversed_ios_client_id"
    fi

    # 1. Update hasGoogleLogin flag in lib/app_build_constant.dart to true
    sed -i '' "s|const hasGoogleLogin = false;|const hasGoogleLogin = true;|" lib/app_build_constant.dart
    log "INFO" "✅ Updated hasGoogleLogin flag to true"

    # 2. Update Web Client ID in app_build_constant.dart
    local app_build_constant="$PROJECT_ROOT/lib/app_build_constant.dart"
    if [ -f "$app_build_constant" ]; then
        # Create backup
        cp "$app_build_constant" "$app_build_constant.backup"

        # Get the old client ID for logging
        local old_client_id=$(grep -o '"[0-9]\{1,\}-[a-zA-Z0-9]\{1,\}\.apps\.googleusercontent\.com"' "$app_build_constant" | head -1 | tr -d '"')

        # Update the googleWebClientId constant
        # This handles both single-line and multi-line formats by replacing any Google OAuth client ID
        sed -i.tmp 's|"[0-9]\{1,\}-[a-zA-Z0-9]\{1,\}\.apps\.googleusercontent\.com"|"'"$web_client_id"'"|g' "$app_build_constant"

        # Remove temporary files
        rm -f "$app_build_constant.tmp"

        # Verify the update
        local new_client_id=$(grep -o '"[0-9]\{1,\}-[a-zA-Z0-9]\{1,\}\.apps\.googleusercontent\.com"' "$app_build_constant" | head -1 | tr -d '"')

        if [ "$new_client_id" = "$web_client_id" ]; then
            log "INFO" "✅ Updated Web Client ID in app_build_constant.dart"
            log "INFO" "   Old: $old_client_id"
            log "INFO" "   New: $new_client_id"
        else
            log "ERROR" "Failed to update Web Client ID in app_build_constant.dart"
            log "ERROR" "Expected: $web_client_id"
            log "ERROR" "Got: $new_client_id"
            exit 1
        fi
    else
        log "ERROR" "app_build_constant.dart not found at: $app_build_constant"
        exit 1
    fi

    # 3. Update iOS Info.plist with Google Sign-In configuration (only if building for iOS)
    if [ "$SHOULD_BUILD_IOS" = true ]; then
        IOS_INFO_PLIST="$PROJECT_ROOT/ios/Runner/Info.plist"
        if [ -f "$IOS_INFO_PLIST" ]; then
            # Create backup
            cp "$IOS_INFO_PLIST" "$IOS_INFO_PLIST.backup"

            # Use PlistBuddy for safe plist manipulation (avoids sed corruption issues)
            local PLIST_BUDDY="/usr/libexec/PlistBuddy"

            # Remove existing Google configuration if present (ignore errors if not found)
            $PLIST_BUDDY -c "Delete :GIDClientID" "$IOS_INFO_PLIST" 2>/dev/null || true
            $PLIST_BUDDY -c "Delete :CFBundleURLTypes" "$IOS_INFO_PLIST" 2>/dev/null || true

            # Add GIDClientID
            $PLIST_BUDDY -c "Add :GIDClientID string $ios_client_id" "$IOS_INFO_PLIST"

            # Add CFBundleURLTypes array with Google URL scheme
            $PLIST_BUDDY -c "Add :CFBundleURLTypes array" "$IOS_INFO_PLIST"
            $PLIST_BUDDY -c "Add :CFBundleURLTypes:0 dict" "$IOS_INFO_PLIST"
            $PLIST_BUDDY -c "Add :CFBundleURLTypes:0:CFBundleTypeRole string Editor" "$IOS_INFO_PLIST"
            $PLIST_BUDDY -c "Add :CFBundleURLTypes:0:CFBundleURLSchemes array" "$IOS_INFO_PLIST"
            $PLIST_BUDDY -c "Add :CFBundleURLTypes:0:CFBundleURLSchemes:0 string $reversed_ios_client_id" "$IOS_INFO_PLIST"

            # Validate the plist is still valid
            if plutil -lint "$IOS_INFO_PLIST" > /dev/null 2>&1; then
                log "INFO" "✅ Updated iOS Info.plist with Google Sign-In configuration"
            else
                log "ERROR" "❌ Info.plist validation failed after update"
                # Restore from backup
                cp "$IOS_INFO_PLIST.backup" "$IOS_INFO_PLIST"
                log "ERROR" "Restored Info.plist from backup"
                exit 1
            fi
        else
            log "ERROR" "iOS Info.plist not found at: $IOS_INFO_PLIST"
            exit 1
        fi
    else
        log "INFO" "Skipping iOS Info.plist update (not building for iOS)"
    fi

    log "INFO" "✅ Google login configuration completed successfully!"
}

remove_google_login() {
    log "INFO" "Removing Google login configuration..."

    # Get the script directory
    SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    PROJECT_ROOT="$SCRIPT_DIR"

    # 1. Update hasGoogleLogin flag in lib/app_build_constant.dart to false
    sed -i '' "s|const hasGoogleLogin = true;|const hasGoogleLogin = false;|" lib/app_build_constant.dart
    log "INFO" "✅ Updated hasGoogleLogin flag to false"

    # 2. Remove Google Sign-In configuration from iOS Info.plist (only if building for iOS)
    if [ "$SHOULD_BUILD_IOS" = true ]; then
        IOS_INFO_PLIST="$PROJECT_ROOT/ios/Runner/Info.plist"
        if [ -f "$IOS_INFO_PLIST" ]; then
            # Create backup
            cp "$IOS_INFO_PLIST" "$IOS_INFO_PLIST.backup"

            # Use PlistBuddy for safe plist manipulation (avoids sed corruption issues)
            local PLIST_BUDDY="/usr/libexec/PlistBuddy"

            # Remove GIDClientID if present (ignore errors if not found)
            $PLIST_BUDDY -c "Delete :GIDClientID" "$IOS_INFO_PLIST" 2>/dev/null || true

            # Remove CFBundleURLTypes if present (ignore errors if not found)
            $PLIST_BUDDY -c "Delete :CFBundleURLTypes" "$IOS_INFO_PLIST" 2>/dev/null || true

            # Validate the plist is still valid
            if plutil -lint "$IOS_INFO_PLIST" > /dev/null 2>&1; then
                log "INFO" "✅ Removed Google Sign-In configuration from iOS Info.plist"
            else
                log "ERROR" "❌ Info.plist validation failed after removal"
                # Restore from backup
                cp "$IOS_INFO_PLIST.backup" "$IOS_INFO_PLIST"
                log "ERROR" "Restored Info.plist from backup"
            fi
        else
            log "WARN" "iOS Info.plist not found at: $IOS_INFO_PLIST"
        fi
    else
        log "INFO" "Skipping iOS Info.plist cleanup (not building for iOS)"
    fi

    # 3. Remove any commented Google OAuth configuration from Android build.gradle (only if building for Android)
    if [ "$SHOULD_BUILD_ANDROID" = true ]; then
        ANDROID_BUILD_GRADLE="$PROJECT_ROOT/android/app/build.gradle"
        if [ -f "$ANDROID_BUILD_GRADLE" ]; then
            # Create backup
            cp "$ANDROID_BUILD_GRADLE" "$ANDROID_BUILD_GRADLE.backup"

            # Remove commented Google OAuth Web Client ID line
            sed -i.tmp '/resValue "string", "default_web_client_id"/d' "$ANDROID_BUILD_GRADLE"

            # Remove temporary files
            rm -f "$ANDROID_BUILD_GRADLE.tmp"

            log "INFO" "✅ Cleaned Android build.gradle"
        else
            log "WARN" "Android build.gradle not found at: $ANDROID_BUILD_GRADLE"
        fi
    else
        log "INFO" "Skipping Android build.gradle cleanup (not building for Android)"
    fi

    log "INFO" "✅ Google login configuration removed successfully!"
    log "INFO" "Note: google_sign_in package remains in pubspec.yaml but won't be used"
}

# Function to generate lib/firebase_options.dart from platform-specific config files
generate_firebase_options_dart() {
    log "INFO" "Generating lib/firebase_options.dart from Firebase configuration files..."

    local android_config_file="android/app/google-services.json"
    local ios_config_file="ios/Runner/GoogleService-Info.plist"

    # Variables for Android
    local android_api_key=""
    local android_app_id=""
    local android_messaging_sender_id=""
    local android_project_id=""
    local android_storage_bucket=""

    # Variables for iOS
    local ios_api_key=""
    local ios_app_id=""
    local ios_messaging_sender_id=""
    local ios_project_id=""
    local ios_storage_bucket=""
    local ios_bundle_id=""

    local has_android=false
    local has_ios=false

    # Extract Android configuration if building for Android
    if [ "$SHOULD_BUILD_ANDROID" = true ] && [ -f "$android_config_file" ]; then
        has_android=true

        # Extract values from google-services.json
        android_project_id=$(grep -o '"project_id"[[:space:]]*:[[:space:]]*"[^"]*"' "$android_config_file" | head -1 | cut -d'"' -f4)
        android_storage_bucket=$(grep -o '"storage_bucket"[[:space:]]*:[[:space:]]*"[^"]*"' "$android_config_file" | head -1 | cut -d'"' -f4)
        android_app_id=$(grep -o '"mobilesdk_app_id"[[:space:]]*:[[:space:]]*"[^"]*"' "$android_config_file" | head -1 | cut -d'"' -f4)
        android_messaging_sender_id=$(grep -o '"project_number"[[:space:]]*:[[:space:]]*"[^"]*"' "$android_config_file" | head -1 | cut -d'"' -f4)
        android_api_key=$(grep -o '"current_key"[[:space:]]*:[[:space:]]*"[^"]*"' "$android_config_file" | head -1 | cut -d'"' -f4)

        log "INFO" "✅ Extracted Android Firebase configuration"
    fi

    # Extract iOS configuration if building for iOS
    if [ "$SHOULD_BUILD_IOS" = true ] && [ -f "$ios_config_file" ]; then
        has_ios=true

        # Extract values from GoogleService-Info.plist
        ios_api_key=$(grep -A 1 '<key>API_KEY</key>' "$ios_config_file" | grep '<string>' | sed 's/.*<string>\(.*\)<\/string>.*/\1/')
        ios_app_id=$(grep -A 1 '<key>GOOGLE_APP_ID</key>' "$ios_config_file" | grep '<string>' | sed 's/.*<string>\(.*\)<\/string>.*/\1/')
        ios_messaging_sender_id=$(grep -A 1 '<key>GCM_SENDER_ID</key>' "$ios_config_file" | grep '<string>' | sed 's/.*<string>\(.*\)<\/string>.*/\1/')
        ios_project_id=$(grep -A 1 '<key>PROJECT_ID</key>' "$ios_config_file" | grep '<string>' | sed 's/.*<string>\(.*\)<\/string>.*/\1/')
        ios_storage_bucket=$(grep -A 1 '<key>STORAGE_BUCKET</key>' "$ios_config_file" | grep '<string>' | sed 's/.*<string>\(.*\)<\/string>.*/\1/')
        ios_bundle_id=$(grep -A 1 '<key>BUNDLE_ID</key>' "$ios_config_file" | grep '<string>' | sed 's/.*<string>\(.*\)<\/string>.*/\1/')

        log "INFO" "✅ Extracted iOS Firebase configuration"
    fi

    # Ensure at least one platform is configured
    if [ "$has_android" = false ] && [ "$has_ios" = false ]; then
        log "ERROR" "No Firebase configuration found for any platform"
        return 1
    fi

    # Generate lib/firebase_options.dart
    cat > lib/firebase_options.dart << 'EOF_HEADER'
// File generated by FlutterFire CLI.
// ignore_for_file: type=lint
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
    show defaultTargetPlatform, kIsWeb, TargetPlatform;

/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
///   options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
  static FirebaseOptions get currentPlatform {
    if (kIsWeb) {
      throw UnsupportedError(
        'DefaultFirebaseOptions have not been configured for web - '
        'you can reconfigure this by running the FlutterFire CLI again.',
      );
    }
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
EOF_HEADER

    if [ "$has_android" = true ]; then
        echo "        return android;" >> lib/firebase_options.dart
    else
        cat >> lib/firebase_options.dart << 'EOF_ANDROID_UNSUPPORTED'
        throw UnsupportedError(
          'DefaultFirebaseOptions have not been configured for android - '
          'you can reconfigure this by running the FlutterFire CLI again.',
        );
EOF_ANDROID_UNSUPPORTED
    fi

    echo "      case TargetPlatform.iOS:" >> lib/firebase_options.dart

    if [ "$has_ios" = true ]; then
        echo "        return ios;" >> lib/firebase_options.dart
    else
        cat >> lib/firebase_options.dart << 'EOF_IOS_UNSUPPORTED'
        throw UnsupportedError(
          'DefaultFirebaseOptions have not been configured for ios - '
          'you can reconfigure this by running the FlutterFire CLI again.',
        );
EOF_IOS_UNSUPPORTED
    fi

    cat >> lib/firebase_options.dart << 'EOF_MIDDLE'
      case TargetPlatform.macOS:
        throw UnsupportedError(
          'DefaultFirebaseOptions have not been configured for macos - '
          'you can reconfigure this by running the FlutterFire CLI again.',
        );
      case TargetPlatform.windows:
        throw UnsupportedError(
          'DefaultFirebaseOptions have not been configured for windows - '
          'you can reconfigure this by running the FlutterFire CLI again.',
        );
      case TargetPlatform.linux:
        throw UnsupportedError(
          'DefaultFirebaseOptions have not been configured for linux - '
          'you can reconfigure this by running the FlutterFire CLI again.',
        );
      default:
        throw UnsupportedError(
          'DefaultFirebaseOptions are not supported for this platform.',
        );
    }
  }

EOF_MIDDLE

    # Add Android configuration if available
    if [ "$has_android" = true ]; then
        cat >> lib/firebase_options.dart << EOF
  static const FirebaseOptions android = FirebaseOptions(
    apiKey: '$android_api_key',
    appId: '$android_app_id',
    messagingSenderId: '$android_messaging_sender_id',
    projectId: '$android_project_id',
    storageBucket: '$android_storage_bucket',
  );

EOF
    fi

    # Add iOS configuration if available
    if [ "$has_ios" = true ]; then
        cat >> lib/firebase_options.dart << EOF
  static const FirebaseOptions ios = FirebaseOptions(
    apiKey: '$ios_api_key',
    appId: '$ios_app_id',
    messagingSenderId: '$ios_messaging_sender_id',
    projectId: '$ios_project_id',
    storageBucket: '$ios_storage_bucket',
    iosBundleId: '$ios_bundle_id',
  );

EOF
    fi

    # Close the class
    echo "}" >> lib/firebase_options.dart

    log "INFO" "✅ lib/firebase_options.dart generated successfully"

    if [ "$has_android" = true ]; then
        log "INFO" "  Android Project ID: $android_project_id"
    fi

    if [ "$has_ios" = true ]; then
        log "INFO" "  iOS Project ID: $ios_project_id"
    fi

    return 0
}

update_firebase() {
    log "INFO" "Updating Firebase configuration..."

    # Validate that required Firebase config files exist for the selected platforms
    if [ "$SHOULD_BUILD_ANDROID" = true ]; then
        if [ ! -f "android/app/google-services.json" ]; then
            log "ERROR" "Android Firebase config not found: android/app/google-services.json"
            log "ERROR" "Required for Android build with push notifications"
            exit 1
        fi
        log "INFO" "✅ Android Firebase config found"
    fi

    if [ "$SHOULD_BUILD_IOS" = true ]; then
        if [ ! -f "ios/Runner/GoogleService-Info.plist" ]; then
            log "ERROR" "iOS Firebase config not found: ios/Runner/GoogleService-Info.plist"
            log "ERROR" "Required for iOS build with push notifications"
            exit 1
        fi
        log "INFO" "✅ iOS Firebase config found"
    fi

    # Generate lib/firebase_options.dart from platform-specific config files
    if ! generate_firebase_options_dart; then
        log "ERROR" "Failed to generate lib/firebase_options.dart"
        exit 1
    fi

    # Update has_firebase in lib/app_build_constant.dart to true
    sed -i '' "s|const hasFirebase = false;|const hasFirebase = true;|" lib/app_build_constant.dart
    log "INFO" "✅ Updated hasFirebase flag to true"

    log "INFO" "✅ Firebase configuration updated successfully!"
}

# ======================================
# MAIN SCRIPT EXECUTION
# ======================================

# Main script execution
main() {
    # print path
    log "INFO" "Current directory: $(pwd)"
    log "INFO" "Current user: $(whoami)"
    # cli command for open this folder in android studio
    log "INFO" "Android Studio: open -a \"Android Studio\" $(pwd)"

    setup_error_handling
    setup_environment
    parse_args "$@"
    validate_args

    # Update app name using rename_app package
    $env_dart run rename_app:main all="$APP_NAME"
    $env_dart run flutter_launcher_icons:main

    # Update app configuration
    update_app_config

    # if has_push_notification is false, clean up firebase files
    if [ "$HAS_PUSH_NOTIFICATION" = false ]; then
        remove_firebase
    else
        log "INFO" "Has push notification is true, updating firebase files..."
        update_firebase
    fi

    if [ "$HAS_GOOGLE_LOGIN" = false ]; then
        remove_google_login
    else
        log "INFO" "Has google login is true, updating google login configuration..."
        update_google_login "$GOOGLE_WEB_CLIENT_ID" "$GOOGLE_IOS_CLIENT_ID"
    fi


    # Build for Android if specified
    if [ "$SHOULD_BUILD_ANDROID" = true ]; then
        update_package_name "$PACKAGE_NAME"
        build_android
    else
        log "WARN" "⚠️ Skipping Android build..."
    fi

    # Build for iOS if specified
    if [ "$SHOULD_BUILD_IOS" = true ]; then
        # delete_apple_certificates "$APP_IDENTIFIER" "$KEY_ID" "$ISSUER_ID" "$KEY_FILEPATH"  # Moved to Fastfile cleanup_apple_signing_artifacts (runs in CI too)
        delete_keychain "$APP_IDENTIFIER"
        update_package_name "$APP_IDENTIFIER"
        build_ios
    else
        log "WARN" "⚠️ Skipping iOS build..."
    fi
}

# Execute main function with all arguments
main "$@"