#!/bin/bash

# Test script for Powerpipe integration with Container Image Scanner
# This script demonstrates the complete workflow from scanning to visualization

set -e

echo "🔍 Container Image Scanner - Powerpipe Integration Test"
echo "======================================================"

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

# Configuration
WORKSPACE_DIR="./test-powerpipe-workspace"
SCAN_RESULTS="./test-scan-results.json"
TEST_PORT="9034"

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

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

# Check prerequisites
check_prerequisites() {
    print_status "Checking prerequisites..."
    
    # Check if CIS is built
    if [ ! -f "./dist/cli.js" ]; then
        print_warning "Container Image Scanner not built. Building now..."
        npm run build
    fi
    
    # Check Node.js version
    NODE_VERSION=$(node --version | cut -d'v' -f2 | cut -d'.' -f1)
    if [ "$NODE_VERSION" -lt 16 ]; then
        print_error "Node.js 16+ required. Current version: $(node --version)"
        exit 1
    fi
    
    print_success "Prerequisites check completed"
}

# Generate sample scan results for testing
generate_sample_data() {
    print_status "Generating sample scan results..."
    
    cat > "$SCAN_RESULTS" << 'EOF'
{
  "scanId": "test-scan-001",
  "timestamp": "2024-08-15T21:46:38.555Z",
  "clusters": [
    {
      "account": "123456789012",
      "region": "us-east-1",
      "name": "production-cluster-1",
      "status": "ACTIVE",
      "version": "1.28",
      "bitnamiImageCount": 2
    },
    {
      "account": "123456789012",
      "region": "us-west-2",
      "name": "staging-cluster-1",
      "status": "ACTIVE",
      "version": "1.27",
      "bitnamiImageCount": 2
    }
  ],
  "images": [
    {
      "account": "123456789012",
      "accountName": "production",
      "region": "us-east-1",
      "cluster": "production-cluster-1",
      "namespace": "database",
      "workload": "postgresql-deployment",
      "workloadType": "deployment",
      "container": "postgresql",
      "image": "bitnami/postgresql",
      "tag": "15.4.0",
      "isLatest": false,
      "riskLevel": "HIGH",
      "category": "database",
      "ecrAlternative": "public.ecr.aws/bitnami/postgresql",
      "replicas": 1,
      "lastScanned": "2024-06-15T10:30:00Z",
      "pullPolicy": "IfNotPresent",
      "resources": {
        "requests": { "cpu": "100m", "memory": "256Mi" },
        "limits": { "cpu": "500m", "memory": "512Mi" }
      }
    },
    {
      "account": "123456789012",
      "accountName": "production",
      "region": "us-east-1",
      "cluster": "production-cluster-1",
      "namespace": "cache",
      "workload": "redis-deployment",
      "workloadType": "deployment",
      "container": "redis",
      "image": "bitnami/redis",
      "tag": "7.2.1",
      "isLatest": false,
      "riskLevel": "MEDIUM",
      "category": "cache",
      "ecrAlternative": "public.ecr.aws/bitnami/redis",
      "replicas": 1,
      "lastScanned": "2024-07-20T14:15:00Z",
      "pullPolicy": "Always"
    },
    {
      "account": "123456789012",
      "accountName": "production",
      "region": "us-east-1",
      "cluster": "production-cluster-1",
      "namespace": "web",
      "workload": "nginx-deployment",
      "workloadType": "deployment",
      "container": "nginx",
      "image": "nginx",
      "tag": "latest",
      "isLatest": true,
      "riskLevel": "CRITICAL",
      "category": "web-server",
      "ecrAlternative": "public.ecr.aws/nginx/nginx",
      "replicas": 3,
      "lastScanned": "2024-01-10T08:00:00Z",
      "pullPolicy": "IfNotPresent"
    },
    {
      "account": "123456789012",
      "accountName": "staging",
      "region": "us-west-2",
      "cluster": "staging-cluster-1",
      "namespace": "database",
      "workload": "mysql-statefulset",
      "workloadType": "statefulset",
      "container": "mysql",
      "image": "bitnami/mysql",
      "tag": "8.0.34",
      "isLatest": false,
      "riskLevel": "HIGH",
      "category": "database",
      "ecrAlternative": "public.ecr.aws/bitnami/mysql",
      "replicas": 1,
      "lastScanned": "2024-08-01T12:00:00Z",
      "pullPolicy": "Always"
    },
    {
      "account": "123456789012",
      "accountName": "staging",
      "region": "us-west-2",
      "cluster": "staging-cluster-1",
      "namespace": "web",
      "workload": "apache-deployment",
      "workloadType": "deployment",
      "container": "apache",
      "image": "bitnami/apache",
      "tag": "2.4.57",
      "isLatest": false,
      "riskLevel": "MEDIUM",
      "category": "web-server",
      "ecrAlternative": "public.ecr.aws/bitnami/apache",
      "replicas": 2,
      "lastScanned": "2024-07-15T16:30:00Z",
      "pullPolicy": "IfNotPresent"
    },
    {
      "account": "123456789012",
      "accountName": "staging",
      "region": "us-west-2",
      "cluster": "staging-cluster-1",
      "namespace": "legacy",
      "workload": "postgres-pod",
      "workloadType": "pod",
      "container": "postgres",
      "image": "postgres",
      "tag": "13",
      "isLatest": false,
      "riskLevel": "CRITICAL",
      "category": "database",
      "ecrAlternative": "public.ecr.aws/docker/library/postgres",
      "replicas": 1,
      "lastScanned": "2023-12-01T10:00:00Z",
      "pullPolicy": null
    }
  ],
  "summary": {
    "totalImages": 6,
    "criticalRisk": 2,
    "highRisk": 2,
    "mediumRisk": 2,
    "lowRisk": 0,
    "categorizedImages": {
      "database": 3,
      "web-server": 2,
      "cache": 1
    },
    "topRiskClusters": [
      {
        "cluster": "production-cluster-1",
        "account": "123456789012",
        "region": "us-east-1",
        "bitnamiCount": 2,
        "criticalCount": 1
      },
      {
        "cluster": "staging-cluster-1",
        "account": "123456789012",
        "region": "us-west-2",
        "bitnamiCount": 2,
        "criticalCount": 1
      }
    ]
  }
}
EOF
    
    print_success "Sample scan results generated: $SCAN_RESULTS"
}

# Test basic query functionality
test_query_command() {
    print_status "Testing query command functionality..."
    
    # Test basic query
    print_status "Running basic query test..."
    node ./dist/cli.js query -i "$SCAN_RESULTS" --format table --limit 3
    
    # Test search functionality
    print_status "Testing search functionality..."
    node ./dist/cli.js query -i "$SCAN_RESULTS" --search bitnami --format json
    
    # Test filtering
    print_status "Testing filter functionality..."
    node ./dist/cli.js query -i "$SCAN_RESULTS" --filter "riskLevel equals CRITICAL" --format table
    
    print_success "Query command tests completed"
}

# Test explore command
test_explore_command() {
    print_status "Testing explore command functionality..."
    
    # Test cluster filtering
    node ./dist/cli.js explore -i "$SCAN_RESULTS" --cluster production
    
    # Test risk filtering  
    node ./dist/cli.js explore -i "$SCAN_RESULTS" --risk CRITICAL
    
    # Test namespace filtering
    node ./dist/cli.js explore -i "$SCAN_RESULTS" --namespace database
    
    print_success "Explore command tests completed"
}

# Test Powerpipe integration
test_powerpipe_integration() {
    print_status "Testing Powerpipe integration..."
    
    # Check if Powerpipe is installed
    if ! command -v powerpipe &> /dev/null; then
        print_warning "Powerpipe not installed. Testing installation check..."
        
        # Test the installation check in our code
        timeout 10s node ./dist/cli.js powerpipe -i "$SCAN_RESULTS" -w "$WORKSPACE_DIR" || true
        
        print_warning "Powerpipe installation would be required for full functionality"
        return 0
    fi
    
    # Test workspace creation and data export
    print_status "Testing workspace creation and data export..."
    
    # Export data in different formats
    node ./dist/cli.js powerpipe -i "$SCAN_RESULTS" -w "$WORKSPACE_DIR" --export json
    node ./dist/cli.js powerpipe -i "$SCAN_RESULTS" -w "$WORKSPACE_DIR" --export csv
    node ./dist/cli.js powerpipe -i "$SCAN_RESULTS" -w "$WORKSPACE_DIR" --export sql
    
    # Check if files were created
    if [ -f "$WORKSPACE_DIR/container_data.json" ]; then
        print_success "JSON export created successfully"
    fi
    
    if [ -f "$WORKSPACE_DIR/container_data.csv" ]; then
        print_success "CSV export created successfully"
    fi
    
    if [ -f "$WORKSPACE_DIR/container_data.sql" ]; then
        print_success "SQL export created successfully"
    fi
    
    # Test custom dashboard generation
    print_status "Testing custom dashboard generation..."
    node ./dist/cli.js powerpipe -i "$SCAN_RESULTS" -w "$WORKSPACE_DIR" --dashboard test-dashboard
    
    if [ -f "$WORKSPACE_DIR/test-dashboard.pp" ]; then
        print_success "Custom dashboard created successfully"
    fi
    
    print_success "Powerpipe integration tests completed"
}

# Test migration planning
test_migration_planning() {
    print_status "Testing migration planning functionality..."
    
    # Generate migration plan
    node ./dist/cli.js migrate -i "$SCAN_RESULTS" -o ./test-migration-plan
    
    if [ -d "./test-migration-plan" ]; then
        print_success "Migration plan generated successfully"
        ls -la ./test-migration-plan/
    fi
}

# Cleanup function
cleanup() {
    print_status "Cleaning up test files..."
    
    rm -f "$SCAN_RESULTS"
    rm -rf "$WORKSPACE_DIR"
    rm -rf "./test-migration-plan"
    
    print_success "Cleanup completed"
}

# Main test execution
main() {
    echo
    print_status "Starting Container Image Scanner Powerpipe Integration Tests"
    echo
    
    # Setup
    check_prerequisites
    generate_sample_data
    
    # Run tests
    test_query_command
    echo
    test_explore_command
    echo
    test_powerpipe_integration
    echo
    test_migration_planning
    echo
    
    # Cleanup
    cleanup
    
    echo
    print_success "All tests completed successfully! 🎉"
    echo
    print_status "To manually test Powerpipe dashboards:"
    print_status "1. Generate real scan data: cis analyze --org-scan -o results.json"
    print_status "2. Start Powerpipe: cis powerpipe -i results.json"
    print_status "3. Open browser: http://localhost:9033"
    echo
}

# Handle script interruption
trap cleanup EXIT

# Run main function
main "$@"
