#!/bin/bash

# Test script for simplified unified backup metrics
# Tests the complete lifecycle with realistic backup scenarios

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
BACKUP_ROOT="$SCRIPT_DIR/test-metrics"
export BACKUP_ROOT

# Load the metrics library
source "$SCRIPT_DIR/lib/unified-backup-metrics.sh"

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

echo -e "${GREEN}=== Testing Simplified Unified Backup Metrics ===${NC}"

# Clean up any previous test
rm -rf "$BACKUP_ROOT"
mkdir -p "$BACKUP_ROOT"

# Test 1: Basic lifecycle
echo -e "\n${YELLOW}Test 1: Basic backup lifecycle${NC}"
metrics_backup_start "test-plex" "Test Plex backup" "$BACKUP_ROOT/plex"
echo "✓ Started backup session"

metrics_update_status "running" "Stopping Plex service"
echo "✓ Updated status to running"

metrics_file_backup_complete "$BACKUP_ROOT/plex/database.db" "1048576" "success"
echo "✓ Tracked database file (1MB)"

metrics_file_backup_complete "$BACKUP_ROOT/plex/metadata.db" "2097152" "success"
echo "✓ Tracked metadata file (2MB)"

metrics_backup_complete "success" "Plex backup completed successfully"
echo "✓ Completed backup session"

# Test 2: Error scenario
echo -e "\n${YELLOW}Test 2: Error scenario${NC}"
metrics_backup_start "test-immich" "Test Immich backup" "$BACKUP_ROOT/immich"
metrics_update_status "running" "Backing up database"
metrics_file_backup_complete "$BACKUP_ROOT/immich/database.sql" "512000" "failed"
metrics_backup_complete "failed" "Database backup failed"
echo "✓ Tested error scenario"

# Test 3: Multiple file tracking
echo -e "\n${YELLOW}Test 3: Multiple file tracking${NC}"
metrics_backup_start "test-media" "Test Media backup" "$BACKUP_ROOT/media"
for i in {1..5}; do
    metrics_file_backup_complete "$BACKUP_ROOT/media/file_$i.txt" "$((i * 1024))" "success"
done
metrics_backup_complete "success" "Media backup completed with 5 files"
echo "✓ Tracked multiple files"

# Display results
echo -e "\n${GREEN}=== Test Results ===${NC}"
echo "Generated metrics files:"
find "$BACKUP_ROOT/metrics" -name "*.json" -exec echo "  {}" \;

echo -e "\n${YELLOW}Sample metrics (test-plex):${NC}"
if [ -f "$BACKUP_ROOT/metrics/test-plex_status.json" ]; then
    cat "$BACKUP_ROOT/metrics/test-plex_status.json" | jq '.' 2>/dev/null || cat "$BACKUP_ROOT/metrics/test-plex_status.json"
else
    echo "❌ No metrics file found"
fi

echo -e "\n${YELLOW}All service statuses:${NC}"
for service in test-plex test-immich test-media; do
    status=$(metrics_get_status "$service")
    echo "  $service: $status"
done

echo -e "\n${GREEN}=== Metrics Integration Test Complete ===${NC}"

# Test web app integration
echo -e "\n${YELLOW}Testing web app data format...${NC}"
cat > "$BACKUP_ROOT/test_web_format.py" << 'EOF'
#!/usr/bin/env python3
import json
import os
import sys

def test_web_format():
    metrics_dir = sys.argv[1] + "/metrics"
    if not os.path.exists(metrics_dir):
        print("❌ Metrics directory not found")
        return False
    
    services = {}
    for filename in os.listdir(metrics_dir):
        if filename.endswith('_status.json'):
            service_name = filename.replace('_status.json', '')
            filepath = os.path.join(metrics_dir, filename)
            try:
                with open(filepath, 'r') as f:
                    status = json.load(f)
                services[service_name] = {
                    'current_status': status.get('status', 'unknown'),
                    'last_run': status.get('end_time'),
                    'files_processed': status.get('files_processed', 0),
                    'total_size': status.get('total_size_bytes', 0),
                    'duration': status.get('duration_seconds', 0)
                }
                print(f"✓ {service_name}: {status.get('status')} ({status.get('files_processed', 0)} files)")
            except Exception as e:
                print(f"❌ Error reading {service_name}: {e}")
                return False
    
    print(f"✓ Successfully parsed {len(services)} services for web interface")
    return True

if __name__ == "__main__":
    test_web_format()
EOF

python3 "$BACKUP_ROOT/test_web_format.py" "$BACKUP_ROOT"

echo -e "\n${GREEN}All tests completed!${NC}"
