#!/bin/bash

# Build Script for ZenTap
# Builds APK and AAB files in debug and release modes

set -e  # Exit on any error

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

# Build output directory
BUILD_DIR="build/outputs"

# App information
APP_NAME="ZenTap"
PACKAGE_NAME="com.fsociety.zentap"

echo -e "${BLUE}$APP_NAME Build Script${NC}"
echo "======================="

# Function to check if Flutter is installed
check_flutter() {
    if ! command -v flutter &> /dev/null; then
        echo -e "${RED}Error: Flutter is not installed or not in PATH${NC}"
        echo "Please install Flutter: https://flutter.dev/docs/get-started/install"
        exit 1
    fi
    
    echo -e "${GREEN}✓ Flutter found: $(flutter --version --machine | grep -o '"flutterVersion":"[^"]*' | cut -d'"' -f4)${NC}"
}

# Function to check Flutter doctor
check_flutter_doctor() {
    echo -e "${YELLOW}Running Flutter doctor...${NC}"
    flutter doctor --android-licenses > /dev/null 2>&1 || true
    
    # Check if Android toolchain is available
    if ! flutter doctor | grep -q "Android toolchain"; then
        echo -e "${RED}Warning: Android toolchain not properly configured${NC}"
        echo "Run 'flutter doctor' to see detailed issues"
    else
        echo -e "${GREEN}✓ Android toolchain available${NC}"
    fi
}

# Function to clean build
clean_build() {
    echo -e "${YELLOW}Cleaning previous builds...${NC}"
    flutter clean
    flutter pub get
    echo -e "${GREEN}✓ Build cleaned${NC}"
}

# Function to build APK
build_apk() {
    local mode=$1
    echo -e "${BLUE}Building $mode APK...${NC}"
    
    if [ "$mode" = "debug" ]; then
        flutter build apk --debug
        local apk_path="build/app/outputs/flutter-apk/app-debug.apk"
        local output_name="${APP_NAME}_debug_$(date +%Y%m%d_%H%M%S).apk"
    else
        flutter build apk --release
        local apk_path="build/app/outputs/flutter-apk/app-release.apk"
        local output_name="${APP_NAME}_release_$(date +%Y%m%d_%H%M%S).apk"
    fi
    
    if [ -f "$apk_path" ]; then
        # Create output directory if it doesn't exist
        mkdir -p "$BUILD_DIR/apk"
        
        # Copy APK to output directory with timestamp
        cp "$apk_path" "$BUILD_DIR/apk/$output_name"
        
        # Get file size
        local size=$(du -h "$apk_path" | cut -f1)
        
        echo -e "${GREEN}✓ $mode APK built successfully${NC}"
        echo -e "${PURPLE}  File: $BUILD_DIR/apk/$output_name${NC}"
        echo -e "${PURPLE}  Size: $size${NC}"
        
        return 0
    else
        echo -e "${RED}✗ Failed to build $mode APK${NC}"
        return 1
    fi
}

# Function to build AAB (Android App Bundle)
build_aab() {
    local mode=$1
    echo -e "${BLUE}Building $mode AAB...${NC}"
    
    if [ "$mode" = "debug" ]; then
        flutter build appbundle --debug
        local aab_path="build/app/outputs/bundle/debug/app-debug.aab"
        local output_name="${APP_NAME}_debug_$(date +%Y%m%d_%H%M%S).aab"
    else
        flutter build appbundle --release
        local aab_path="build/app/outputs/bundle/release/app-release.aab"
        local output_name="${APP_NAME}_release_$(date +%Y%m%d_%H%M%S).aab"
    fi
    
    if [ -f "$aab_path" ]; then
        # Create output directory if it doesn't exist
        mkdir -p "$BUILD_DIR/bundle"
        
        # Copy AAB to output directory with timestamp
        cp "$aab_path" "$BUILD_DIR/bundle/$output_name"
        
        # Get file size
        local size=$(du -h "$aab_path" | cut -f1)
        
        echo -e "${GREEN}✓ $mode AAB built successfully${NC}"
        echo -e "${PURPLE}  File: $BUILD_DIR/bundle/$output_name${NC}"
        echo -e "${PURPLE}  Size: $size${NC}"
        
        return 0
    else
        echo -e "${RED}✗ Failed to build $mode AAB${NC}"
        return 1
    fi
}

# Function to show usage
show_usage() {
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  -h, --help          Show this help message"
    echo "  -c, --clean         Clean build before building"
    echo "  -d, --debug         Build debug versions only"
    echo "  -r, --release       Build release versions only"
    echo "  --apk-only          Build APK files only"
    echo "  --aab-only          Build AAB files only"
    echo "  --all               Build all variants (default)"
    echo ""
    echo "Examples:"
    echo "  $0                  # Build all variants"
    echo "  $0 --debug          # Build debug APK and AAB"
    echo "  $0 --release --apk-only  # Build release APK only"
    echo "  $0 --clean --all    # Clean and build all variants"
}

# Parse command line arguments
BUILD_DEBUG=true
BUILD_RELEASE=true
BUILD_APK=true
BUILD_AAB=true
CLEAN_BUILD=false

while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_usage
            exit 0
            ;;
        -c|--clean)
            CLEAN_BUILD=true
            shift
            ;;
        -d|--debug)
            BUILD_DEBUG=true
            BUILD_RELEASE=false
            shift
            ;;
        -r|--release)
            BUILD_DEBUG=false
            BUILD_RELEASE=true
            shift
            ;;
        --apk-only)
            BUILD_APK=true
            BUILD_AAB=false
            shift
            ;;
        --aab-only)
            BUILD_APK=false
            BUILD_AAB=true
            shift
            ;;
        --all)
            BUILD_DEBUG=true
            BUILD_RELEASE=true
            BUILD_APK=true
            BUILD_AAB=true
            shift
            ;;
        *)
            echo -e "${RED}Unknown option: $1${NC}"
            show_usage
            exit 1
            ;;
    esac
done

# Main execution
echo -e "${YELLOW}Build Configuration:${NC}"
echo "  Debug: $BUILD_DEBUG"
echo "  Release: $BUILD_RELEASE"
echo "  APK: $BUILD_APK"
echo "  AAB: $BUILD_AAB"
echo "  Clean: $CLEAN_BUILD"
echo ""

# Check prerequisites
check_flutter
check_flutter_doctor

# Clean if requested
if [ "$CLEAN_BUILD" = true ]; then
    clean_build
    echo ""
fi

# Build variants
BUILD_SUCCESS=true

if [ "$BUILD_DEBUG" = true ]; then
    if [ "$BUILD_APK" = true ]; then
        build_apk "debug" || BUILD_SUCCESS=false
        echo ""
    fi
    
    if [ "$BUILD_AAB" = true ]; then
        build_aab "debug" || BUILD_SUCCESS=false
        echo ""
    fi
fi

if [ "$BUILD_RELEASE" = true ]; then
    if [ "$BUILD_APK" = true ]; then
        build_apk "release" || BUILD_SUCCESS=false
        echo ""
    fi
    
    if [ "$BUILD_AAB" = true ]; then
        build_aab "release" || BUILD_SUCCESS=false
        echo ""
    fi
fi

# Summary
echo -e "${BLUE}Build Summary${NC}"
echo "============="

if [ "$BUILD_SUCCESS" = true ]; then
    echo -e "${GREEN}✓ All builds completed successfully!${NC}"
    
    echo -e "${YELLOW}Output files location:${NC}"
    if [ -d "$BUILD_DIR" ]; then
        find "$BUILD_DIR" -name "*.apk" -o -name "*.aab" | while read -r file; do
            size=$(du -h "$file" | cut -f1)
            echo -e "${PURPLE}  $file ($size)${NC}"
        done
    fi
    
    echo ""
    echo -e "${BLUE}Installation Instructions:${NC}"
    echo "  APK: adb install <apk_file>"
    echo "  AAB: Upload to Google Play Console"
    
else
    echo -e "${RED}✗ Some builds failed. Check the output above for details.${NC}"
    exit 1
fi