#!/bin/bash
# Test Dangerous Pi custom image
# Run this script after flashing and booting the image

set -e

# Configuration
PI_HOST="${1:-10.3.141.1}"  # Default to AP mode IP
PI_USER="dt"
API_PORT="8000"

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

echo "========================================"
echo "Dangerous Pi Image Test Suite"
echo "========================================"
echo "Target: $PI_USER@$PI_HOST"
echo ""

# Function to run test
run_test() {
    local test_name="$1"
    local command="$2"

    echo -n "Testing $test_name... "

    if eval "$command" &>/dev/null; then
        echo -e "${GREEN}✓ PASS${NC}"
        return 0
    else
        echo -e "${RED}✗ FAIL${NC}"
        return 1
    fi
}

# Test 1: SSH Connectivity
echo "=== Connectivity Tests ==="
run_test "SSH connectivity" \
    "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no $PI_USER@$PI_HOST 'echo ok'"

# Test 2: User exists
run_test "User 'pi' exists" \
    "ssh -o ConnectTimeout=5 $PI_USER@$PI_HOST 'id pi'"

# Test 3: Dangerous Pi directory
run_test "Dangerous Pi installed at /opt" \
    "ssh $PI_USER@$PI_HOST '[ -d /opt/dangerous-pi ]'"

# Test 4: Required files
echo ""
echo "=== File Structure Tests ==="
run_test "Backend code exists" \
    "ssh $PI_USER@$PI_HOST '[ -d /opt/dangerous-pi/app/backend ]'"

run_test "Systemd service file" \
    "ssh $PI_USER@$PI_HOST '[ -f /etc/systemd/system/dangerous-pi.service ]'"

run_test "Environment file" \
    "ssh $PI_USER@$PI_HOST '[ -f /opt/dangerous-pi/.env ]'"

run_test "Scripts executable" \
    "ssh $PI_USER@$PI_HOST '[ -x /opt/dangerous-pi/scripts/resolve-port-conflict.sh ]'"

# Test 5: Service Status
echo ""
echo "=== Service Tests ==="
run_test "Service is enabled" \
    "ssh $PI_USER@$PI_HOST 'systemctl is-enabled dangerous-pi.service'"

run_test "Service is running" \
    "ssh $PI_USER@$PI_HOST 'systemctl is-active dangerous-pi.service'"

# Test 6: Hardware Access
echo ""
echo "=== Hardware Access Tests ==="
run_test "User in 'i2c' group" \
    "ssh $PI_USER@$PI_HOST 'groups pi | grep -q i2c'"

run_test "User in 'dialout' group" \
    "ssh $PI_USER@$PI_HOST 'groups pi | grep -q dialout'"

run_test "User in 'gpio' group" \
    "ssh $PI_USER@$PI_HOST 'groups pi | grep -q gpio'"

run_test "User in 'bluetooth' group" \
    "ssh $PI_USER@$PI_HOST 'groups pi | grep -q bluetooth'"

run_test "I2C interface enabled" \
    "ssh $PI_USER@$PI_HOST 'grep -q \"^dtparam=i2c_arm=on\" /boot/config.txt'"

run_test "I2C device available" \
    "ssh $PI_USER@$PI_HOST '[ -e /dev/i2c-1 ]'"

# Test 7: Python Dependencies
echo ""
echo "=== Python Dependencies Tests ==="
run_test "FastAPI installed" \
    "ssh $PI_USER@$PI_HOST 'python3 -c \"import fastapi\"'"

run_test "Uvicorn installed" \
    "ssh $PI_USER@$PI_HOST 'python3 -c \"import uvicorn\"'"

run_test "aiosqlite installed" \
    "ssh $PI_USER@$PI_HOST 'python3 -c \"import aiosqlite\"'"

run_test "psutil installed" \
    "ssh $PI_USER@$PI_HOST 'python3 -c \"import psutil\"'"

run_test "smbus2 installed" \
    "ssh $PI_USER@$PI_HOST 'python3 -c \"import smbus2\"'"

# Test 8: API Endpoints (if service is running)
echo ""
echo "=== API Endpoint Tests ==="

if ssh $PI_USER@$PI_HOST "systemctl is-active dangerous-pi.service" &>/dev/null; then
    # Wait for service to be fully up
    sleep 3

    run_test "Health endpoint" \
        "curl -f -s http://$PI_HOST:$API_PORT/api/health"

    run_test "System info endpoint" \
        "curl -f -s http://$PI_HOST:$API_PORT/api/system/info"

    run_test "PM3 status endpoint" \
        "curl -f -s http://$PI_HOST:$API_PORT/api/pm3/status"

    run_test "WiFi status endpoint" \
        "curl -f -s http://$PI_HOST:$API_PORT/api/wifi/status"

    run_test "Plugin list endpoint" \
        "curl -f -s http://$PI_HOST:$API_PORT/api/plugins/list"
else
    echo -e "${YELLOW}Service not running, skipping API tests${NC}"
fi

# Test 9: Disk Space
echo ""
echo "=== System Health Tests ==="
DISK_USAGE=$(ssh $PI_USER@$PI_HOST "df / | tail -1 | awk '{print \$5}' | sed 's/%//'")
if [ "$DISK_USAGE" -lt 80 ]; then
    echo -e "Disk usage: ${GREEN}$DISK_USAGE%${NC} ✓"
else
    echo -e "Disk usage: ${RED}$DISK_USAGE%${NC} (Warning: >80%)"
fi

# Test 10: Service Logs
echo ""
echo "=== Service Logs (last 10 lines) ==="
ssh $PI_USER@$PI_HOST "sudo journalctl -u dangerous-pi.service -n 10 --no-pager" || true

echo ""
echo "========================================"
echo "Test Suite Complete"
echo "========================================"
