#!/usr/bin/env bash

set -e

# Mythril dynamic analysis for Solidity contracts
# This script runs Mythril 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/mythril"


log_success "Running Mythril dynamic analysis..."

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

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Run Mythril on each contract file
log_warn "Analyzing contracts in $CONTRACTS_DIR..."

cd "$PROJECT_ROOT"

# Find all Solidity files
SOL_FILES=$(find contracts -name "*.sol" -type f)

if [ -z "$SOL_FILES" ]; then
    log_warn "No Solidity files found"
    exit 0
fi

HIGH_SEVERITY_COUNT=0

for file in $SOL_FILES; do
    log_warn "Analyzing $file..."
    
    # Run Mythril with JSON output
    myth analyze "$file" \
        --solv 0.8.19 \
        --execution-timeout 300 \
        --max-depth 12 \
        --json \
        > "$OUTPUT_DIR/$(basename $file .sol).json" \
        2>&1 || true
    
    # Run Mythril with human-readable output
    myth analyze "$file" \
        --solv 0.8.19 \
        --execution-timeout 300 \
        --max-depth 12 \
        > "$OUTPUT_DIR/$(basename $file .sol).txt" \
        2>&1 || true
    
    # Check for high-severity issues
    if [ -f "$OUTPUT_DIR/$(basename $file .sol).json" ]; then
        SEVERITY=$(jq -r '.issues[]?.severity' "$OUTPUT_DIR/$(basename $file .sol).json" 2>/dev/null | grep -c "High" || echo "0")
        if [ "$SEVERITY" -gt 0 ]; then
            HIGH_SEVERITY_COUNT=$((HIGH_SEVERITY_COUNT + SEVERITY))
        fi
    fi
done

if [ "$HIGH_SEVERITY_COUNT" -gt 0 ]; then
    log_error "⚠️  Found $HIGH_SEVERITY_COUNT high-severity issues"
    echo "Review reports in: $OUTPUT_DIR"
    exit 1
else
    log_success "✓ No high-severity issues found"
fi

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

