#!/bin/bash
echo "Cleaning up max log n contracts"
rm -rf src/contracts/autogenerated/ultra_keccak_zk_honk_max_log_n

echo "Generating max log n contracts"
python hydra/garaga/starknet/honk_contract_generator/generator_honk.py --max-log-n

cd src/contracts
echo "----------------------------------------"
echo "Checking bytecode length"

# Maximum allowed bytecode length
MAX_BYTECODE_LENGTH=81290  # Adjust this value as needed

# Function to get bytecode length
get_bytecode_length() {
    local contract_dir=$1
    local bytecode_length=0

    cd "$contract_dir" || return 1
    # Redirect scarb build output to /dev/null to avoid mixing with our output
    scarb build > /dev/null 2>&1

    # Find the compiled contract class JSON file
    compiled_file=$(find ./target/dev -name '*.compiled_contract_class.json' -print -quit)
    if [[ -f "$compiled_file" ]]; then
        bytecode_length=$(jq '.bytecode | length' "$compiled_file")
    else
        echo "Error: Compiled contract class JSON not found in $contract_dir" >&2
        cd ../
        return 1
    fi

    cd ../
    echo "$bytecode_length"
    return 0
}

# Function to print bytecode length
print_bytecode_length() {
    local contract_dir=$1
    local length=$2
    echo -e "\e[32mBytecode length [$contract_dir] = $length (max: $MAX_BYTECODE_LENGTH)\e[0m"
    echo "----------------------------------------"
}

# List of contract directories
contracts=(
    "autogenerated/ultra_keccak_zk_honk_max_log_n"
)

# Check each contract
results=()
for contract in "${contracts[@]}"; do
    length=$(get_bytecode_length "$contract")
    if [ $? -eq 0 ]; then
        print_bytecode_length "$contract" "$length"
        results+=("$length")
    else
        echo "Error checking bytecode length for $contract" >&2
        exit 1
    fi
done

# Check if all bytecode lengths are below the limit
all_below_limit=true
for length in "${results[@]}"; do
    if [ "$length" -gt "$MAX_BYTECODE_LENGTH" ]; then
        all_below_limit=false
        break
    fi
done

rm -rf autogenerated/ultra_keccak_zk_honk_max_log_n


# Return true/false based on the check
if [ "$all_below_limit" = true ]; then
    echo "true"
    exit 0
else
    echo "false"
    exit 1
fi
