#!/bin/bash

# MCPChain Demo Script (without chain start)

set -e

CHAIN_ID="mcpchain"
DENOM="umcp"
HOME_DIR="$HOME/.mcpchain"
BIN="mcpchaind"
KEYRING_BACKEND="test"
AMOUNT="1000000000${DENOM}"
STAKE="500000000${DENOM}"
FEES="1000${DENOM}"
SERVER_DESCRIPTION="Echo Server"
SERVER_ENDPOINT="http://localhost:8080/echo"
SERVER_SCHEMA="schemahash123"

echo "Cleaning previous state"
rm -rf "$HOME_DIR"

echo "Init chain"
$BIN init validator --chain-id $CHAIN_ID

echo "Add 2 keys"
$BIN keys add user1 --keyring-backend $KEYRING_BACKEND
$BIN keys add user2 --keyring-backend $KEYRING_BACKEND

echo "Add genesis accounts"
$BIN genesis add-genesis-account $($BIN keys show user1 -a --keyring-backend $KEYRING_BACKEND) $AMOUNT
$BIN genesis add-genesis-account $($BIN keys show user2 -a --keyring-backend $KEYRING_BACKEND) $AMOUNT

echo "Replace staking denom"
sed -i '' 's/"stake"/"'$DENOM'"/g' "$HOME_DIR/config/genesis.json"

echo "Create gentx"
$BIN genesis gentx user1 $STAKE --chain-id $CHAIN_ID --keyring-backend $KEYRING_BACKEND

echo "Collect gentx and validate"
$BIN genesis collect-gentxs
$BIN genesis validate

echo "Register MCP server by user1"
$BIN tx toolregistry register-server \
  $($BIN keys show user1 -a --keyring-backend $KEYRING_BACKEND) \
  "$SERVER_DESCRIPTION" \
  "$SERVER_ENDPOINT" \
  "$SERVER_SCHEMA" \
  "$STAKE" \
  --from user1 \
  --keyring-backend $KEYRING_BACKEND \
  --chain-id $CHAIN_ID \
  --fees $FEES \
  -y

echo "Simulate call from user2 → user1's MCP server"
echo "Assume: This step done via mcp-client, logs interaction on-chain and user1 earns tokens"

echo "Transfer fee from user2 to user1 to simulate gain"
$BIN tx bank send \
  $($BIN keys show user2 -a --keyring-backend $KEYRING_BACKEND) \
  $($BIN keys show user1 -a --keyring-backend $KEYRING_BACKEND) \
  "10000${DENOM}" \
  --chain-id $CHAIN_ID \
  --fees $FEES \
  --keyring-backend $KEYRING_BACKEND \
  -y

echo "Done! Check balances:"
$BIN query bank balances $($BIN keys show user1 -a --keyring-backend $KEYRING_BACKEND)
$BIN query bank balances $($BIN keys show user2 -a --keyring-backend $KEYRING_BACKEND)
