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

RPC_URL="http://127.0.0.1:8545"
ACCOUNT="0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"
PRIVATE_KEY="0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
WETH="0x4200000000000000000000000000000000000006"
SWAP_ROUTER="0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4"
KRK="0xe527ddac2592faa45884a0b78e4d377a5d3df8cc"  # From bootstrap logs

# Get Stake contract address dynamically from KRK token
PERIPHERY=$(cast call --rpc-url "$RPC_URL" "$KRK" "peripheryContracts()(address,address)")
STAKE=$(echo "$PERIPHERY" | tail -1)

echo "[1/7] Checking initial KRK balance..."
INITIAL_BALANCE=$(cast call --rpc-url "$RPC_URL" "$KRK" "balanceOf(address)(uint256)" "$ACCOUNT" | awk '{print $1}')
echo "Initial KRK balance: $INITIAL_BALANCE"

echo "[2/7] Wrapping 0.05 ETH to WETH..."
cast send --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" \
  "$WETH" "deposit()" --value 0.05ether

echo "[3/7] Approving swap router..."
cast send --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" \
  "$WETH" "approve(address,uint256)" "$SWAP_ROUTER" 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff

echo "[4/7] Executing swap (0.05 ETH -> KRK)..."
cast send --legacy --gas-limit 300000 --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" \
  "$SWAP_ROUTER" "exactInputSingle((address,address,uint24,address,uint256,uint256,uint160))" \
  "($WETH,$KRK,10000,$ACCOUNT,50000000000000000,0,0)"

echo "[5/7] Checking final KRK balance..."
FINAL_BALANCE=$(cast call --rpc-url "$RPC_URL" "$KRK" "balanceOf(address)(uint256)" "$ACCOUNT" | awk '{print $1}')
echo "Final KRK balance: $FINAL_BALANCE"

# Convert to human readable (divide by 10^18)
FINAL_KRK=$(python3 -c "print(f'{$FINAL_BALANCE / 1e18:.4f}')")
echo "Final KRK balance: $FINAL_KRK KRK"

if [ "$FINAL_BALANCE" -le "$INITIAL_BALANCE" ]; then
  echo "❌ FAILED: No KRK tokens received"
  exit 1
fi

RECEIVED=$(python3 -c "print(f'{($FINAL_BALANCE - $INITIAL_BALANCE) / 1e18:.4f}')")
echo "✅ SUCCESS! Received $RECEIVED KRK tokens from swap"

# Calculate 1/5 of received tokens for staking
STAKE_AMOUNT=$(python3 -c "print(int(($FINAL_BALANCE - $INITIAL_BALANCE) / 5))")
echo ""
echo "[6/7] Staking 1/5 of received KRK ($STAKE_AMOUNT wei)..."

# Approve Stake contract to spend KRK
echo "  → Approving Stake contract..."
cast send --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" \
  "$KRK" "approve(address,uint256)" "$STAKE" "$STAKE_AMOUNT"

# Stake with tax rate index 5 (18% annual tax), no positions to snatch
echo "  → Creating staking position (18% tax rate)..."
TX_OUTPUT=$(cast send --legacy --gas-limit 500000 --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" \
  "$STAKE" "snatch(uint256,address,uint32,uint256[])" \
  "$STAKE_AMOUNT" "$ACCOUNT" "5" "[]")

TX_HASH=$(echo "$TX_OUTPUT" | grep "^transactionHash" | awk '{print $2}')
echo "  → Staking transaction: $TX_HASH"

echo "[7/7] Verifying staking position created..."
# Get the PositionCreated event topic from the transaction receipt
# The position ID is the first indexed parameter (topic[1])
RECEIPT_JSON=$(cast receipt --rpc-url "$RPC_URL" "$TX_HASH" --json)
POSITION_ID_HEX=$(echo "$RECEIPT_JSON" | python3 -c "import sys, json; logs = json.load(sys.stdin)['logs']; print([l for l in logs if len(l['topics']) > 1 and '8f7598451bc034be2bd3fe6e2f06af052c2dc238bb90bc6fb426754f04301462' in l['topics'][0]][0]['topics'][1] if any('8f7598451bc034be2bd3fe6e2f06af052c2dc238bb90bc6fb426754f04301462' in l['topics'][0] for l in logs) else '')" 2>/dev/null || echo "")

if [ -n "$POSITION_ID_HEX" ]; then
  POSITION_ID=$(python3 -c "print(int('$POSITION_ID_HEX', 16))")
  STAKE_KRK=$(python3 -c "print(f'{$STAKE_AMOUNT / 1e18:.4f}')")
  echo "✅ SUCCESS! Staking position created with ID: $POSITION_ID"
  echo ""
  echo "Summary:"
  echo "  - Swapped: 0.05 ETH → $RECEIVED KRK"
  echo "  - Staked: $STAKE_KRK KRK (1/5 of received)"
  echo "  - Position ID: $POSITION_ID"
  echo "  - Tax Rate: 18% annual"
  exit 0
else
  echo "⚠️  WARNING: Could not extract position ID from receipt"
  echo "But staking transaction succeeded: $TX_HASH"
  echo ""
  echo "Summary:"
  echo "  - Swapped: 0.05 ETH → $RECEIVED KRK"
  echo "  - Staked: 1/5 of received KRK"
  echo "  - Transaction: $TX_HASH"
  exit 0
fi
