#!/bin/bash

# Exit on error
set -e

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

# Logging functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

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

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# Check prerequisites
check_prerequisites() {
    log_step "Checking prerequisites..."
    
    if ! command -v node &> /dev/null; then
        log_error "Node.js is not installed. Please install Node.js first."
        exit 1
    fi
    
    if ! command -v npm &> /dev/null; then
        log_error "npm is not installed. Please install npm first."
        exit 1
    fi
    
    if ! command -v npx &> /dev/null; then
        log_error "npx is not installed. Please install npx first."
        exit 1
    fi
    
    log_info "Prerequisites check passed"
}

# Get absolute paths
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
REPO_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )"
TEST_APP_DIR="$REPO_ROOT/test-apps/ios-test-app"
ANDROID_TEST_APP_DIR="$REPO_ROOT/test-apps/android-test-app"

# Main setup function
setup_ios_test_app() {
    log_info "Setting up iOS test app..."
    
    cd "$REPO_ROOT"
    
    # Check if Android test app exists (for reference)
    if [ ! -d "$ANDROID_TEST_APP_DIR" ]; then
        log_warn "Android test app not found at $ANDROID_TEST_APP_DIR"
        log_warn "Will create iOS test app from scratch"
    fi
    
    # Create test-apps directory if it doesn't exist
    mkdir -p "$REPO_ROOT/test-apps"
    
    # Check if iOS test app already exists
    if [ -d "$TEST_APP_DIR" ]; then
        log_warn "iOS test app already exists at $TEST_APP_DIR"
        read -p "Do you want to recreate it? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            log_info "Skipping iOS test app creation"
            return 0
        fi
        log_info "Removing existing iOS test app..."
        rm -rf "$TEST_APP_DIR"
    fi
    
    log_step "Creating iOS test app directory..."
    mkdir -p "$TEST_APP_DIR"
    cd "$TEST_APP_DIR"
    
    log_step "Initializing Capacitor iOS app..."
    
    # Create a minimal Capacitor iOS app structure
    # Note: This creates a basic structure. Full setup requires Capacitor CLI.
    
    log_info "Creating basic app structure..."
    
    # Create App directory
    mkdir -p "App/App"
    mkdir -p "App/App/Public"
    
    # Copy HTML from Android test app
    if [ -f "$ANDROID_TEST_APP_DIR/app/src/main/assets/public/index.html" ]; then
        log_step "Copying HTML from Android test app..."
        cp "$ANDROID_TEST_APP_DIR/app/src/main/assets/public/index.html" "App/App/Public/index.html"
        log_info "HTML copied successfully"
    else
        log_warn "Android test app HTML not found, creating minimal HTML..."
        create_minimal_html
    fi
    
    # Create capacitor.config.json
    log_step "Creating capacitor.config.json..."
    cat > "capacitor.config.json" << 'EOF'
{
  "appId": "org.timesafari.dailynotification.test",
  "appName": "DailyNotification Test App",
  "webDir": "App/App/Public",
  "server": {
    "iosScheme": "capacitor"
  },
  "plugins": {
    "DailyNotification": {
      "enabled": true
    }
  }
}
EOF
    
    # Create package.json
    log_step "Creating package.json..."
    cat > "package.json" << 'EOF'
{
  "name": "ios-test-app",
  "version": "1.0.0",
  "description": "iOS test app for DailyNotification plugin",
  "scripts": {
    "sync": "npx cap sync ios",
    "open": "npx cap open ios"
  },
  "dependencies": {
    "@capacitor/core": "^5.0.0",
    "@capacitor/ios": "^5.0.0"
  }
}
EOF
    
    log_info "Basic structure created"
    log_warn ""
    log_warn "⚠️  IMPORTANT: This script creates a basic structure only."
    log_warn "You need to run Capacitor CLI to create the full iOS project:"
    log_warn ""
    log_warn "  cd test-apps/ios-test-app"
    log_warn "  npm install"
    log_warn "  npx cap add ios"
    log_warn "  npx cap sync ios"
    log_warn ""
    log_warn "Then configure Info.plist with BGTask identifiers (see doc/test-app-ios/IOS_TEST_APP_REQUIREMENTS.md)"
    log_warn ""
    
    log_info "✅ Basic iOS test app structure created at $TEST_APP_DIR"
}

# Create minimal HTML if Android HTML not available
create_minimal_html() {
    cat > "App/App/Public/index.html" << 'EOF'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0">
    <title>DailyNotification Plugin Test</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: white;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            text-align: center;
        }
        .button {
            background: rgba(255, 255, 255, 0.2);
            border: 2px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 15px 30px;
            margin: 10px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
        }
        .status {
            margin-top: 30px;
            padding: 20px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 10px;
            font-family: monospace;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔔 DailyNotification Plugin Test</h1>
        <button class="button" onclick="testPlugin()">Test Plugin</button>
        <button class="button" onclick="scheduleNotification()">Schedule Notification</button>
        <div id="status" class="status">Ready to test...</div>
    </div>
    <script>
        window.DailyNotification = window.Capacitor?.Plugins?.DailyNotification;
        
        function testPlugin() {
            const status = document.getElementById('status');
            if (window.DailyNotification) {
                status.innerHTML = 'Plugin is loaded and ready!';
                status.style.background = 'rgba(0, 255, 0, 0.3)';
            } else {
                status.innerHTML = 'Plugin not available';
                status.style.background = 'rgba(255, 0, 0, 0.3)';
            }
        }
        
        function scheduleNotification() {
            const status = document.getElementById('status');
            if (!window.DailyNotification) {
                status.innerHTML = 'Plugin not available';
                return;
            }
            const now = new Date();
            const time = new Date(now.getTime() + 600000);
            const timeString = time.getHours().toString().padStart(2, '0') + ':' + 
                              time.getMinutes().toString().padStart(2, '0');
            window.DailyNotification.scheduleDailyNotification({
                time: timeString,
                title: 'Test Notification',
                body: 'This is a test notification'
            }).then(() => {
                status.innerHTML = 'Notification scheduled for ' + timeString;
                status.style.background = 'rgba(0, 255, 0, 0.3)';
            }).catch(error => {
                status.innerHTML = 'Error: ' + error.message;
                status.style.background = 'rgba(255, 0, 0, 0.3)';
            });
        }
    </script>
</body>
</html>
EOF
}

# Main execution
main() {
    log_info "iOS Test App Setup Script"
    log_info ""
    
    check_prerequisites
    setup_ios_test_app
    
    log_info ""
    log_info "✅ Setup complete!"
    log_info ""
    log_info "Next steps:"
    log_info "1. cd test-apps/ios-test-app"
    log_info "2. npm install"
    log_info "3. npx cap add ios"
    log_info "4. Configure Info.plist (see doc/test-app-ios/IOS_TEST_APP_REQUIREMENTS.md)"
    log_info "5. npx cap sync ios"
    log_info "6. ./scripts/build-ios-test-app.sh --simulator"
}

main "$@"

