#!/usr/bin/env bash
# Fix Hardhat dependency resolution

set -e

cd "$(dirname "$0")/../.."

echo "=== Fixing Hardhat Dependencies ==="

# Check if package.json exists
if [ ! -f "package.json" ]; then
    echo "❌ package.json not found"
    exit 1
fi

# Install OpenZeppelin v5.0.2
echo "Installing @openzeppelin/contracts@5.0.2..."
npm install @openzeppelin/contracts@5.0.2 --save-dev

# Install Chainlink CCIP contracts
echo "Installing @chainlink/contracts-ccip..."
npm install @chainlink/contracts-ccip --save-dev

# Clean Hardhat cache
echo "Cleaning Hardhat cache..."
npx hardhat clean || true

# Try to compile
echo "Attempting to compile..."
if npx hardhat compile 2>&1 | grep -q "Error"; then
    echo "⚠️  Compilation errors detected, trying alternative approach..."
    
    # Try with --force
    npm install --legacy-peer-deps --force
    
    # Try compiling again
    npx hardhat clean
    npx hardhat compile || {
        echo "❌ Compilation still failing"
        echo "Trying yarn as alternative..."
        if command -v yarn &> /dev/null; then
            yarn install
            yarn hardhat compile || echo "❌ Yarn compilation also failed"
        fi
    }
fi

echo "✅ Dependency fix complete"
