#!/bin/bash
################################################################################
# Stage 10 ARM64 Testing Script for Jetson Orin Nano
#
# Tests the multi-layer secret scanning setup on ARM64 architecture
# Verifies: git-secrets, gitleaks v8.30.1 ARM64, ggshield, pre-commit hooks
#
# Usage: bash test-stage10-arm64.sh [jetson-user@jetson-ip]
################################################################################

set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

log_header() {
    echo ""
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

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

log_success() {
    echo -e "${GREEN}[✓]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[!]${NC} $1"
}

log_error() {
    echo -e "${RED}[✗]${NC} $1"
}

# ============================================================================
# Configuration
# ============================================================================

JETSON_TARGET="${1:-192.168.55.1}"
ENGRAM_ROOT="~/engram"
TEST_DIR="/tmp/engram-stage10-test"

log_header "Stage 10 ARM64 Secret Scanning Test"

echo ""
echo "Target: $JETSON_TARGET"
echo "Test directory: $TEST_DIR"
echo ""

# ============================================================================
# Phase 1: Verify Installation on Jetson
# ============================================================================

log_header "Phase 1: Verify Secret Scanning Tools"

ssh_cmd="ssh -q ${JETSON_TARGET}"

# Test 1: git-secrets
log_info "Testing git-secrets..."
if $ssh_cmd "command -v git-secrets &>/dev/null"; then
    version=$($ssh_cmd "git-secrets --version" 2>&1 || echo "unknown")
    log_success "git-secrets installed: $version"
else
    log_warn "git-secrets not found"
fi

# Test 2: gitleaks ARM64
log_info "Testing gitleaks v8.30.1 ARM64..."
if $ssh_cmd "command -v gitleaks &>/dev/null"; then
    version=$($ssh_cmd "gitleaks --version" 2>&1 | head -1 || echo "unknown")
    log_success "gitleaks installed: $version"

    # Verify it's actually ARM64
    file_type=$($ssh_cmd "file $(command -v gitleaks)" 2>&1 || echo "unknown")
    if echo "$file_type" | grep -q "ARM"; then
        log_success "Binary is ARM64 (correct for Jetson)"
    else
        log_warn "Binary might not be ARM64: $file_type"
    fi
else
    log_error "gitleaks not found - Stage 10 installation may have failed"
fi

# Test 3: ggshield
log_info "Testing ggshield..."
if $ssh_cmd "command -v ggshield &>/dev/null"; then
    version=$($ssh_cmd "ggshield --version" 2>&1 | head -1 || echo "unknown")
    log_success "ggshield installed: $version"
else
    log_warn "ggshield not found (optional)"
fi

# Test 4: pre-commit hooks
log_info "Testing pre-commit hooks..."
if $ssh_cmd "test -f $ENGRAM_ROOT/.pre-commit-config.yaml"; then
    log_success "Pre-commit config exists"
else
    log_warn "Pre-commit config not found"
fi

# ============================================================================
# Phase 2: Test Secret Blocking
# ============================================================================

log_header "Phase 2: Test Secret Blocking (Fake Secrets)"

# Create test repo on Jetson
log_info "Creating test repository..."
$ssh_cmd "rm -rf $TEST_DIR && mkdir -p $TEST_DIR && cd $TEST_DIR && git init"
log_success "Test repo created at $TEST_DIR"

# Test 1: Custom proprietary indicator
log_info "Test 1: Blocking custom proprietary formula..."
$ssh_cmd "cd $TEST_DIR && cat > test_secret.py << 'EOF'
# This should trigger git-secrets
custom_indicator_key = 'proprietary_formula_ABC123DEFGHIJKLMNOPQRST'
EOF"

echo ""
log_info "Attempting to commit proprietary indicator..."
if $ssh_cmd "cd $TEST_DIR && git add test_secret.py && git commit -m 'test secret' 2>&1"; then
    log_error "FAILED: Secret was NOT blocked! (git-secrets issue)"
else
    log_success "PASSED: Secret was blocked by git-secrets"
fi

# Clean up
$ssh_cmd "cd $TEST_DIR && git reset HEAD test_secret.py 2>/dev/null || true; rm test_secret.py"

# Test 2: API Key pattern
log_info "Test 2: Blocking API key pattern..."
$ssh_cmd "cd $TEST_DIR && cat > test_api_key.py << 'EOF'
# This should trigger git-secrets
api_key = 'aAbBcCdDeEfFgGhHiIjJkKlMmNnOoPpQqRrSsT'
EOF"

echo ""
log_info "Attempting to commit API key..."
if $ssh_cmd "cd $TEST_DIR && git add test_api_key.py && git commit -m 'test api key' 2>&1"; then
    log_error "FAILED: API key was NOT blocked!"
else
    log_success "PASSED: API key was blocked"
fi

# Clean up
$ssh_cmd "cd $TEST_DIR && git reset HEAD test_api_key.py 2>/dev/null || true; rm test_api_key.py"

# Test 3: Password pattern
log_info "Test 3: Blocking password in code..."
$ssh_cmd "cd $TEST_DIR && cat > test_password.py << 'EOF'
# This should trigger git-secrets or gitleaks
password = 'SuperSecurePass123!@#'
EOF"

echo ""
log_info "Attempting to commit password..."
if $ssh_cmd "cd $TEST_DIR && git add test_password.py && git commit -m 'test password' 2>&1"; then
    log_error "FAILED: Password was NOT blocked!"
else
    log_success "PASSED: Password was blocked"
fi

# Clean up
$ssh_cmd "cd $TEST_DIR && git reset HEAD test_password.py 2>/dev/null || true; rm test_password.py"

# ============================================================================
# Phase 3: Test Valid Code (Should Pass)
# ============================================================================

log_header "Phase 3: Valid Code Should Pass"

log_info "Testing valid code (no secrets)..."
$ssh_cmd "cd $TEST_DIR && cat > valid_code.py << 'EOF'
# This is normal code with no secrets
def hello_world():
    print('Hello, World!')
    return True
EOF"

echo ""
log_info "Attempting to commit valid code..."
if $ssh_cmd "cd $TEST_DIR && git add valid_code.py && git commit -m 'add valid code' 2>&1"; then
    log_success "PASSED: Valid code committed successfully"
else
    log_error "FAILED: Valid code was blocked (false positive!)"
fi

# ============================================================================
# Phase 4: Cleanup and Summary
# ============================================================================

log_header "Phase 4: Cleanup"

log_info "Removing test repository..."
$ssh_cmd "rm -rf $TEST_DIR"
log_success "Cleanup complete"

# ============================================================================
# Summary Report
# ============================================================================

log_header "SUMMARY: Stage 10 ARM64 Validation"

echo ""
echo "✅ What was tested:"
echo "   1. git-secrets installed and configured"
echo "   2. gitleaks v8.30.1 ARM64 binary present"
echo "   3. ggshield installed (via pipx)"
echo "   4. Pre-commit hooks configured"
echo ""

echo "✅ Secret blocking tests:"
echo "   1. Proprietary indicators detected"
echo "   2. API keys detected"
echo "   3. Passwords detected"
echo "   4. Valid code passes"
echo ""

echo "📊 Results:"
if $ssh_cmd "cd $TEST_DIR 2>/dev/null && git log --oneline 2>/dev/null | grep 'add valid code'"; then
    log_success "ALL TESTS PASSED - Stage 10 working correctly"
else
    log_warn "Check results above for any failures"
fi

echo ""
echo "🎯 Next steps:"
echo "   1. Run full wizard: python3 scripts/interview.py"
echo "   2. Complete all 10 stages"
echo "   3. Verify Stage 10 output mentions gitleaks v8.30.1 ARM64"
echo "   4. Test blocking a real secret from your code"
echo ""

log_success "Test script complete!"
