#!/bin/bash
# DailyNotification Plugin Test Script
# Usage: ./daily-notification-test.sh

set -e

# Configuration
APP_PACKAGE="org.timesafari.dailynotification"
APP_ACTIVITY=".MainActivity"
TEST_TIMEOUT=120  # 2 minutes
LOG_TAG="DailyNotification"

# 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() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# Function to check if app is running
check_app_running() {
    adb shell "ps | grep $APP_PACKAGE" > /dev/null 2>&1
}

# Function to wait for app to be ready
wait_for_app() {
    print_status $YELLOW "⏳ Waiting for app to be ready..."
    sleep 3
}

# Function to schedule notification (manual step)
schedule_notification() {
    print_status $BLUE "📅 Scheduling test notification..."
    print_status $YELLOW "⚠️  Manual step: Schedule notification in app UI"
    print_status $YELLOW "   - Tap 'Test Notification' button"
    print_status $YELLOW "   - Wait for 'Notification scheduled' message"
    read -p "Press Enter when notification is scheduled..."
}

# Function to check notification in logs
check_notification_logs() {
    local timeout=$1
    local start_time=$(date +%s)
    
    print_status $BLUE "👀 Monitoring logs for notification delivery..."
    
    while [ $(($(date +%s) - start_time)) -lt $timeout ]; do
        if adb logcat -d | grep -q "Notification displayed successfully"; then
            print_status $GREEN "✅ Notification displayed successfully"
            return 0
        fi
        sleep 5
    done
    
    print_status $RED "❌ Notification not found in logs"
    return 1
}

# Function to run ADB command and check result
run_adb_command() {
    local command=$1
    local description=$2
    
    print_status $BLUE "🔧 $description"
    if adb $command; then
        print_status $GREEN "✅ $description - Success"
        return 0
    else
        print_status $RED "❌ $description - Failed"
        return 1
    fi
}

# Main test function
main() {
    print_status $BLUE "🧪 Starting DailyNotification Plugin Tests"
    print_status $BLUE "=========================================="
    
    # Check ADB connection
    if ! adb devices | grep -q "device$"; then
        print_status $RED "❌ No Android device connected via ADB"
        exit 1
    fi
    
    print_status $GREEN "✅ ADB device connected"
    
    # Test 1: App Launch
    print_status $BLUE "🚀 Test 1: App Launch"
    if run_adb_command "shell am start -n $APP_PACKAGE/$APP_ACTIVITY" "Launching app"; then
        wait_for_app
        if check_app_running; then
            print_status $GREEN "✅ App launched and running"
        else
            print_status $RED "❌ App failed to start"
            exit 1
        fi
    else
        exit 1
    fi
    
    # Test 2: Background Test
    print_status $BLUE "🔄 Test 2: Background Notification Test"
    schedule_notification
    
    print_status $BLUE "📱 Sending app to background..."
    if run_adb_command "shell input keyevent KEYCODE_HOME" "Send to background"; then
        sleep 2
        if check_app_running; then
            print_status $GREEN "✅ App running in background"
        else
            print_status $RED "❌ App not running in background"
            exit 1
        fi
    else
        exit 1
    fi
    
    # Test 3: Wait for notification
    print_status $BLUE "⏰ Test 3: Waiting for notification ($TEST_TIMEOUT seconds)..."
    print_status $YELLOW "👀 Watch for notification in system panel"
    
    if check_notification_logs $TEST_TIMEOUT; then
        print_status $GREEN "✅ Notification test passed"
    else
        print_status $RED "❌ Notification test failed or timed out"
    fi
    
    # Test 4: Force Stop Test
    print_status $BLUE "🛑 Test 4: Force Stop Test (Expected Failure)"
    schedule_notification
    
    print_status $BLUE "💀 Force stopping app..."
    if run_adb_command "shell am force-stop $APP_PACKAGE" "Force stop app"; then
        sleep 2
        if check_app_running; then
            print_status $RED "❌ App still running after force stop"
            exit 1
        else
            print_status $GREEN "✅ App successfully force stopped"
        fi
    else
        exit 1
    fi
    
    print_status $BLUE "⏰ Waiting for notification (should NOT appear)..."
    sleep 60
    
    if adb logcat -d | grep -q "Notification displayed successfully"; then
        print_status $RED "❌ Notification appeared after force stop (unexpected)"
    else
        print_status $GREEN "✅ No notification after force stop (expected)"
    fi
    
    # Test 5: Permission Check
    print_status $BLUE "🔐 Test 5: Permission Status Check"
    run_adb_command "shell \"dumpsys notification | grep -A5 -B5 $APP_PACKAGE\"" "Check notification settings"
    
    # Test 6: Alarm Status Check
    print_status $BLUE "⏰ Test 6: Alarm Status Check"
    run_adb_command "shell \"dumpsys alarm | grep $APP_PACKAGE\"" "Check scheduled alarms"
    
    print_status $GREEN "🎉 All tests completed!"
    print_status $BLUE "📊 Check the results above for any failures"
}

# Help function
show_help() {
    echo "DailyNotification Plugin Test Script"
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  -h, --help     Show this help message"
    echo "  -v, --verbose  Enable verbose output"
    echo "  -t, --timeout  Set test timeout in seconds (default: 120)"
    echo ""
    echo "Examples:"
    echo "  $0                    # Run all tests"
    echo "  $0 -t 60             # Run with 60 second timeout"
    echo "  $0 -v                # Run with verbose output"
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        -v|--verbose)
            set -x
            shift
            ;;
        -t|--timeout)
            TEST_TIMEOUT="$2"
            shift 2
            ;;
        *)
            print_status $RED "Unknown option: $1"
            show_help
            exit 1
            ;;
    esac
done

# Run main function
main
