#!/bin/bash

echo "🎵 Cordova Audio Recorder Plugin - Reinstall and Test Script"
echo "=========================================================="

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

# Function to print colored output
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 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

# Copy debug test file
print_status "Copying debug test file..."
cp "$PLUGIN_PATH/debug-audio-session.html" www/ 2>/dev/null || true

if [ -f "www/debug-audio-session.html" ]; then
    print_success "Debug test file copied to www/debug-audio-session.html"
else
    print_warning "Could not copy debug test file"
fi

print_status "Installation completed!"
echo ""
print_status "Next steps:"
echo "1. Open your project in Xcode"
echo "2. Run the app on a device or simulator"
echo "3. Check the Xcode console for detailed debug messages"
echo "4. Navigate to debug-audio-session.html in your app to test the plugin"
echo ""
print_status "Expected debug messages in Xcode console:"
echo "✅ AVAudioSession class found: ..."
echo "✅ Audio session obtained: ..."
echo "✅ Audio session category set successfully"
echo "✅ Audio session activated successfully"
echo "✅ Direct allocation successful: ..."
echo "✅ Recorder created: ..."
echo ""
print_warning "If you see '❌' messages, please share the console output for debugging"
