#!/usr/bin/env bash
set -euo pipefail

FOUNDRY_IMAGE="${FOUNDRY_IMAGE:-ghcr.io/foundry-rs/foundry:latest}"

usage() {
    cat <<'EOF'
Usage: ./jeannie blockchain-wallet {instructions|new|address|sign-message MESSAGE}

instructions          Print wallet lab guidance.
new                   Generate a new development wallet.
address               Print the address for PRIVATE_KEY.
sign-message MESSAGE  Sign a dev message with PRIVATE_KEY.

Set PRIVATE_KEY only with an Anvil/dev private key. Never use a real wallet key.
EOF
}

run_cast() {
    if command -v cast >/dev/null 2>&1; then
        cast "$@"
        return
    fi

    if ! command -v docker >/dev/null 2>&1; then
        echo "cast or docker is required for blockchain-wallet." >&2
        exit 1
    fi

    docker run --rm \
        -e "PRIVATE_KEY=${PRIVATE_KEY:-}" \
        "$FOUNDRY_IMAGE" \
        cast "$@"
}

require_private_key() {
    if [ -z "${PRIVATE_KEY:-}" ]; then
        echo "Set PRIVATE_KEY to an Anvil/dev private key first." >&2
        exit 1
    fi
}

case "${1:-instructions}" in
    instructions)
        cat <<'EOF'
Wallet lab rules:
  - Use only Anvil or disposable development keys.
  - Never paste a real seed phrase or funded private key into this repo or shell.
  - Prefer environment variables for short-lived dev keys.
  - Treat signatures as authorization; verify what you are signing.

Examples:
  ./jeannie blockchain-wallet new
  export PRIVATE_KEY=0x...
  ./jeannie blockchain-wallet address
  ./jeannie blockchain-wallet sign-message "homelab devnet login"

Pair this with:
  ./jeannie blockchain-devnet up
  ./jeannie blockchain-devnet rpc
EOF
        ;;
    new)
        run_cast wallet new
        ;;
    address)
        require_private_key
        run_cast wallet address "$PRIVATE_KEY"
        ;;
    sign-message)
        require_private_key
        shift
        if [ "$#" -eq 0 ]; then
            echo "sign-message requires a message." >&2
            exit 1
        fi
        run_cast wallet sign --private-key "$PRIVATE_KEY" "$*"
        ;;
    -h|--help|help)
        usage
        ;;
    *)
        usage >&2
        exit 1
        ;;
esac
