#!/bin/bash

# Comprehensive Test Suite for Daily Notification Plugin v2
# Tests all P0 production-grade features
# Author: Matthew Raymer
# Date: 2025-10-14

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

# Test configuration
APP_PACKAGE="org.timesafari.dailynotification"
APP_ACTIVITY="org.timesafari.dailynotification.MainActivity"
TEST_TIMEOUT=30
NOTIFICATION_DELAY=5 # 5 minutes for testing

# Test results tracking
TESTS_PASSED=0
TESTS_FAILED=0
TESTS_TOTAL=0

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

log_success() {
    echo -e "${GREEN}[PASS]${NC} $1"
    ((TESTS_PASSED++))
}

log_error() {
    echo -e "${RED}[FAIL]${NC} $1"
    ((TESTS_FAILED++))
}

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

# Test execution function
run_test() {
    local test_name="$1"
    local test_command="$2"
    local expected_result="$3"
    
    ((TESTS_TOTAL++))
    log_info "Running: $test_name"
    
    if eval "$test_command"; then
        log_success "$test_name - $expected_result"
        return 0
    else
        log_error "$test_name - Expected: $expected_result"
        return 1
    fi
}

# Check if device is connected
check_device() {
    log_info "Checking device connection..."
    if ! adb devices | grep -q "device$"; then
        log_error "No Android device connected"
        exit 1
    fi
    log_success "Device connected"
}

# Check if app is installed
check_app_installed() {
    log_info "Checking if app is installed..."
    if ! adb shell pm list packages | grep -q "$APP_PACKAGE"; then
        log_error "App not installed: $APP_PACKAGE"
        exit 1
    fi
    log_success "App installed: $APP_PACKAGE"
}

# Test 2.1: Channel Management
test_channel_management() {
    log_info "=== Test 2.1: Channel Management ==="
    
    # Check if channel exists
    run_test "Channel Exists" \
        "adb shell 'dumpsys notification | grep -q daily_default'" \
        "Channel daily_default exists"
    
    # Check channel importance
    run_test "Channel Importance" \
        "adb shell 'dumpsys notification | grep -A5 daily_default | grep -q mImportance=4'" \
        "Channel has proper importance level"
    
    # Check channel features
    run_test "Channel Sound" \
        "adb shell 'dumpsys notification | grep -A5 daily_default | grep -q mSound='" \
        "Channel has sound enabled"
    
    run_test "Channel Lights" \
        "adb shell 'dumpsys notification | grep -A5 daily_default | grep -q mLights=true'" \
        "Channel has lights enabled"
    
    run_test "Channel Vibration" \
        "adb shell 'dumpsys notification | grep -A5 daily_default | grep -q mVibrationEnabled=true'" \
        "Channel has vibration enabled"
}

# Test 2.2: PendingIntent & Exact Alarms
test_pendingintent_exact_alarms() {
    log_info "=== Test 2.2: PendingIntent & Exact Alarms ==="
    
    # Check exact alarm permission
    run_test "Exact Alarm Permission" \
        "adb shell 'dumpsys alarm | grep -q SCHEDULE_EXACT_ALARM.*10192'" \
        "App has exact alarm permission"
    
    # Check scheduled alarms
    run_test "Alarms Scheduled" \
        "adb shell 'dumpsys alarm | grep timesafari | wc -l | grep -q [0-9]'" \
        "Alarms are scheduled"
    
    # Check alarm type
    run_test "RTC_WAKEUP Alarms" \
        "adb shell 'dumpsys alarm | grep timesafari | grep -q RTC_WAKEUP'" \
        "Alarms use RTC_WAKEUP type"
    
    # Check exact timing
    run_test "Exact Timing" \
        "adb shell 'dumpsys alarm | grep timesafari -A2 | grep -q window=0'" \
        "Alarms use exact timing (window=0)"
    
    # Check PendingIntent records
    run_test "PendingIntent Records" \
        "adb shell 'dumpsys alarm | grep timesafari | grep -q PendingIntent'" \
        "PendingIntent records exist"
}

# Test 3.1: JIT Freshness Re-check
test_jit_freshness() {
    log_info "=== Test 3.1: JIT Freshness Re-check ==="
    
    # Start monitoring logs
    log_info "Starting log monitoring for JIT freshness..."
    
    # Launch app to trigger JIT check
    adb shell am start -n "$APP_PACKAGE/$APP_ACTIVITY" > /dev/null 2>&1
    sleep 2
    
    # Check for JIT freshness logs
    run_test "JIT Freshness Check" \
        "adb logcat -d | grep -q 'Content is fresh.*skipping JIT refresh'" \
        "JIT freshness check is working"
    
    # Check for TTL enforcer logs
    run_test "TTL Enforcer" \
        "adb logcat -d | grep -q 'DailyNotificationTTLEnforcer'" \
        "TTL enforcer is active"
}

# Test 4.1: Recovery Coexistence
test_recovery_coexistence() {
    log_info "=== Test 4.1: Recovery Coexistence ==="
    
    # Check RecoveryManager logs
    run_test "RecoveryManager Active" \
        "adb logcat -d | grep -q 'RecoveryManager'" \
        "RecoveryManager is active"
    
    # Check app startup recovery
    run_test "App Startup Recovery" \
        "adb logcat -d | grep -q 'APP_STARTUP'" \
        "App startup recovery is working"
    
    # Check alarm count after recovery
    local alarm_count=$(adb shell 'dumpsys alarm | grep timesafari | wc -l')
    run_test "Alarms After Recovery" \
        "test $alarm_count -gt 0" \
        "Alarms exist after recovery ($alarm_count alarms)"
}

# Test notification scheduling
test_notification_scheduling() {
    log_info "=== Test: Notification Scheduling ==="
    
    # Launch app
    adb shell am start -n "$APP_PACKAGE/$APP_ACTIVITY" > /dev/null 2>&1
    sleep 2
    
    # Check if we can schedule a notification
    run_test "Notification Scheduling" \
        "adb shell 'dumpsys alarm | grep timesafari | wc -l | grep -q [0-9]'" \
        "Notifications can be scheduled"
    
    # Get next notification time
    local next_notification=$(adb shell "dumpsys alarm | grep 'timesafari.*NOTIFICATION' -A2 | grep 'origWhen=' | head -1 | sed 's/.*origWhen=//' | sed 's/ window.*//'")
    log_info "Next notification scheduled for: $next_notification"
}

# Test comprehensive status
test_comprehensive_status() {
    log_info "=== Test: Comprehensive Status ==="
    
    # Launch app and check status
    adb shell am start -n "$APP_PACKAGE/$APP_ACTIVITY" > /dev/null 2>&1
    sleep 2
    
    # Check if app is running
    run_test "App Running" \
        "adb shell 'ps | grep -q $APP_PACKAGE'" \
        "App is running"
    
    # Check notification permissions
    run_test "Notification Permissions" \
        "adb shell 'dumpsys package $APP_PACKAGE | grep -q POST_NOTIFICATIONS'" \
        "App has notification permissions"
}

# Main test execution
main() {
    echo "=========================================="
    echo "Daily Notification Plugin - Comprehensive Test Suite v2"
    echo "=========================================="
    echo "Testing all P0 production-grade features"
    echo "Date: $(date)"
    echo "=========================================="
    
    # Pre-flight checks
    check_device
    check_app_installed
    
    # Run all tests
    test_channel_management
    test_pendingintent_exact_alarms
    test_jit_freshness
    test_recovery_coexistence
    test_notification_scheduling
    test_comprehensive_status
    
    # Test results summary
    echo "=========================================="
    echo "TEST RESULTS SUMMARY"
    echo "=========================================="
    echo "Total Tests: $TESTS_TOTAL"
    echo -e "Passed: ${GREEN}$TESTS_PASSED${NC}"
    echo -e "Failed: ${RED}$TESTS_FAILED${NC}"
    
    if [ $TESTS_FAILED -eq 0 ]; then
        echo -e "${GREEN}ALL TESTS PASSED! 🎉${NC}"
        echo "P0 features are working correctly"
        exit 0
    else
        echo -e "${RED}SOME TESTS FAILED${NC}"
        echo "Please review failed tests and fix issues"
        exit 1
    fi
}

# Run main function
main "$@"
