#!/bin/bash

echo "🎵 Quick Audio Recorder Plugin Reinstall"
echo "========================================"

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

print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if we're in a Cordova project
if [ ! -f "config.xml" ]; then
    print_error "This script must be run from a Cordova project root directory"
    print_error "Please navigate to your Cordova project and run this script"
    exit 1
fi

print_status "Found Cordova project: $(pwd)"

# Get the plugin path
PLUGIN_PATH="/Users/mccapplelaptop/Documents/PLUGINS/cordova-plugin-audio-recorder"

if [ ! -d "$PLUGIN_PATH" ]; then
    print_error "Plugin not found at: $PLUGIN_PATH"
    exit 1
fi

print_status "Plugin found at: $PLUGIN_PATH"

# Remove existing plugin
print_status "Removing existing audio recorder plugin..."
cordova plugin remove cordova-plugin-audio-recorder 2>/dev/null || true

# Clean iOS platform
print_status "Cleaning iOS platform..."
cordova clean ios

# Add the plugin
print_status "Adding updated audio recorder plugin..."
cordova plugin add "$PLUGIN_PATH"

if [ $? -eq 0 ]; then
    print_success "Plugin added successfully"
else
    print_error "Failed to add plugin"
    exit 1
fi

# Build iOS
print_status "Building iOS project..."
cordova build ios

if [ $? -eq 0 ]; then
    print_success "iOS build completed successfully"
else
    print_error "iOS build failed"
    exit 1
fi

print_status "Installation completed!"
echo ""
print_status "Next steps:"
echo "1. Open your project in Xcode"
echo "2. Run the app on a REAL iOS device (not simulator)"
echo "3. Check the Xcode console for detailed debug messages"
echo "4. Look for these success messages:"
echo "   ✅ AVAudioSession class found: ..."
echo "   ✅ Audio session obtained: ..."
echo "   ✅ Audio session category set successfully"
echo "   ✅ Audio session activated successfully"
echo "   Using AAC format with file: ..."
echo "   ✅ Direct allocation successful: ..."
echo "   ✅ Recorder created: ..."
echo ""
print_warning "If you still see 'Failed to create audio recorder' error,"
print_warning "please share the complete console output for debugging"
