#!/usr/bin/env bash

set -e

# Slither static analysis for Solidity contracts
# This script runs Slither on all Solidity contracts in the project

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
CONTRACTS_DIR="$PROJECT_ROOT/contracts"
OUTPUT_DIR="$PROJECT_ROOT/reports/slither"


log_success "Running Slither static analysis..."

# Check if Slither is installed
if ! command -v slither &> /dev/null; then
    log_warn "Slither not found. Installing..."
    pip install slither-analyzer
fi

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Run Slither on contracts
log_warn "Analyzing contracts in $CONTRACTS_DIR..."

cd "$PROJECT_ROOT"

# Run Slither with JSON output
slither . \
    --json "$OUTPUT_DIR/slither-report.json" \
    --exclude-dependencies \
    --filter-paths "node_modules,lib" \
    || true

# Run Slither with human-readable output
slither . \
    --exclude-dependencies \
    --filter-paths "node_modules,lib" \
    > "$OUTPUT_DIR/slither-report.txt" \
    || true

# Check for high-severity issues
if [ -f "$OUTPUT_DIR/slither-report.json" ]; then
    HIGH_SEVERITY=$(jq '[.results.detectors[] | select(.impact == "High")] | length' "$OUTPUT_DIR/slither-report.json" 2>/dev/null || echo "0")
    
    if [ "$HIGH_SEVERITY" -gt 0 ]; then
        log_error "⚠️  Found $HIGH_SEVERITY high-severity issues"
        echo "Review report: $OUTPUT_DIR/slither-report.json"
        exit 1
    else
        log_success "✓ No high-severity issues found"
    fi
fi

log_success "Slither analysis complete"
echo "Reports saved to: $OUTPUT_DIR"

