#!/bin/bash
# Register a test Vita on the local blockchain
# Usage: ./register-test-vita.sh <address>
#
# Example: ./register-test-vita.sh Nhfg3TbpwogLvDGVvAvqyThbsHgoSUKwtn

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CHAIN_DIR="$(dirname "$SCRIPT_DIR")"
TUTUS_CLI="$CHAIN_DIR/bin/tutus.exe"
WALLET="$CHAIN_DIR/.docker/wallets/wallet1.json"
WALLET_CONFIG="/tmp/wallet-config.yaml"
RPC_ENDPOINT="${RPC_ENDPOINT:-http://localhost:10332}"

# Vita contract hash
VITA_HASH="0xde437f043fdfb8f9c8241acb82d0791dd4b3217d"

if [ -z "$1" ]; then
    echo "Usage: $0 <address>"
    echo "Example: $0 Nhfg3TbpwogLvDGVvAvqyThbsHgoSUKwtn"
    exit 1
fi

ADDRESS="$1"

# Convert address to script hash
echo "Converting address to script hash..."
SCRIPT_HASH=$("$TUTUS_CLI" util convert "$ADDRESS" 2>/dev/null | grep "Address to LE ScriptHash" | awk '{print $NF}')

if [ -z "$SCRIPT_HASH" ]; then
    echo "Error: Could not convert address to script hash"
    exit 1
fi

echo "Address: $ADDRESS"
echo "Script Hash: $SCRIPT_HASH"

# Generate test data
PERSON_HASH=$(echo -n "test-person-$ADDRESS-$(date +%Y%m%d)" | sha256sum | cut -d' ' -f1)
RECOVERY_HASH="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
BIRTH_TS="631152000000"  # Jan 1, 1990 in ms

# Create wallet config
cat > "$WALLET_CONFIG" << EOF
Path: $WALLET
Password: one
EOF

echo ""
echo "Registering Vita on blockchain..."

# Invoke the contract
TX_HASH=$("$TUTUS_CLI" contract invokefunction \
  -r "$RPC_ENDPOINT" \
  --wallet-config "$WALLET_CONFIG" \
  -a Nhfg3TbpwogLvDGVvAvqyThbsHgoSUKwtn \
  --force \
  --await \
  "$VITA_HASH" \
  register \
  "Hash160:$SCRIPT_HASH" \
  "ByteArray:$PERSON_HASH" \
  "Boolean:false" \
  "ByteArray:$RECOVERY_HASH" \
  "Integer:$BIRTH_TS" \
  -- "$SCRIPT_HASH:CalledByEntry" 2>&1 | head -1)

echo ""
echo "=== VITA REGISTERED ==="
echo "Transaction: $TX_HASH"
echo "Address: $ADDRESS"
echo ""
echo "Verify with:"
echo "  curl -s -X POST $RPC_ENDPOINT -H 'Content-Type: application/json' \\"
echo "    -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"invokefunction\",\"params\":[\"$VITA_HASH\",\"exists\",[{\"type\":\"Hash160\",\"value\":\"$SCRIPT_HASH\"}]]}'"

# Cleanup
rm -f "$WALLET_CONFIG"
