#!/bin/bash
# Complete System Configuration Script
# This script completes all remaining configuration steps after deployment

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     Complete System Configuration - ChainID 138            ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""

# Load environment
cd "$PROJECT_ROOT"
source "$PROJECT_ROOT/scripts/load-env.sh" >/dev/null 2>&1 || true

# Check prerequisites
if [ -z "$PRIVATE_KEY" ]; then
    echo -e "${RED}Error: PRIVATE_KEY environment variable not set${NC}"
    exit 1
fi

export PRIVATE_KEY
export RPC_URL=${RPC_URL:-${RPC_URL_138:-"http://192.168.11.250:8545"}}

DEPLOYER=$(cast wallet address $PRIVATE_KEY)
US_JURISDICTION=$(cast keccak "US")

echo -e "${GREEN}Configuration:${NC}"
echo "  Deployer: $DEPLOYER"
echo "  RPC URL: $RPC_URL"
echo ""

# Step 1: Run Configure.s.sol
echo -e "${YELLOW}Step 1: Running Configure.s.sol...${NC}"
forge script script/emoney/Configure.s.sol:ConfigureScript \
  --rpc-url "$RPC_URL" \
  --broadcast \
  --via-ir \
  --legacy \
  --gas-price 30000000000 \
  -vv 2>&1 | tee /tmp/configure.log | tail -20

echo ""

# Step 2: Configure PolicyManager
echo -e "${YELLOW}Step 2: Configuring PolicyManager for tokens...${NC}"

echo "  Setting bridge address for CompliantUSDT..."
cast send "$POLICY_MANAGER" \
  "setBridge(address,address)" \
  "$COMPLIANT_USDT_ADDRESS" \
  "$BRIDGE_VAULT" \
  --rpc-url "$RPC_URL" \
  --private-key "$PRIVATE_KEY" \
  --legacy \
  --gas-price 30000000000 > /dev/null 2>&1 && echo "    ✅ Success" || echo "    ⚠️  Check if already set"

echo "  Setting bridge address for CompliantUSDC..."
cast send "$POLICY_MANAGER" \
  "setBridge(address,address)" \
  "$COMPLIANT_USDC_ADDRESS" \
  "$BRIDGE_VAULT" \
  --rpc-url "$RPC_URL" \
  --private-key "$PRIVATE_KEY" \
  --legacy \
  --gas-price 30000000000 > /dev/null 2>&1 && echo "    ✅ Success" || echo "    ⚠️  Check if already set"

echo "  Setting lien mode (encumbered) for CompliantUSDT..."
cast send "$POLICY_MANAGER" \
  "setLienMode(address,uint8)" \
  "$COMPLIANT_USDT_ADDRESS" \
  2 \
  --rpc-url "$RPC_URL" \
  --private-key "$PRIVATE_KEY" \
  --legacy \
  --gas-price 30000000000 > /dev/null 2>&1 && echo "    ✅ Success" || echo "    ⚠️  Check if already set"

echo "  Setting lien mode (encumbered) for CompliantUSDC..."
cast send "$POLICY_MANAGER" \
  "setLienMode(address,uint8)" \
  "$COMPLIANT_USDC_ADDRESS" \
  2 \
  --rpc-url "$RPC_URL" \
  --private-key "$PRIVATE_KEY" \
  --legacy \
  --gas-price 30000000000 > /dev/null 2>&1 && echo "    ✅ Success" || echo "    ⚠️  Check if already set"

echo ""

# Step 3: Configure FeeCollector
echo -e "${YELLOW}Step 3: Configuring FeeCollector...${NC}"

echo "  Adding fee recipient for CompliantUSDT (100% to deployer)..."
cast send "$FEE_COLLECTOR_ADDRESS" \
  "addFeeRecipient(address,address,uint256)" \
  "$COMPLIANT_USDT_ADDRESS" \
  "$DEPLOYER" \
  10000 \
  --rpc-url "$RPC_URL" \
  --private-key "$PRIVATE_KEY" \
  --legacy \
  --gas-price 30000000000 > /dev/null 2>&1 && echo "    ✅ Success" || echo "    ⚠️  May already exist"

echo "  Adding fee recipient for CompliantUSDC (100% to deployer)..."
cast send "$FEE_COLLECTOR_ADDRESS" \
  "addFeeRecipient(address,address,uint256)" \
  "$COMPLIANT_USDC_ADDRESS" \
  "$DEPLOYER" \
  10000 \
  --rpc-url "$RPC_URL" \
  --private-key "$PRIVATE_KEY" \
  --legacy \
  --gas-price 30000000000 > /dev/null 2>&1 && echo "    ✅ Success" || echo "    ⚠️  May already exist"

echo ""

# Step 4: Set Compliance Status
echo -e "${YELLOW}Step 4: Setting compliance status for tokens...${NC}"

echo "  Setting CompliantUSDT as compliant..."
cast send "$COMPLIANCE_REGISTRY_ADDRESS" \
  "setCompliance(address,bool,uint8,bytes32)" \
  "$COMPLIANT_USDT_ADDRESS" \
  true \
  1 \
  "$US_JURISDICTION" \
  --rpc-url "$RPC_URL" \
  --private-key "$PRIVATE_KEY" \
  --legacy \
  --gas-price 30000000000 > /dev/null 2>&1 && echo "    ✅ Success" || echo "    ⚠️  Check if already set"

echo "  Setting CompliantUSDC as compliant..."
cast send "$COMPLIANCE_REGISTRY_ADDRESS" \
  "setCompliance(address,bool,uint8,bytes32)" \
  "$COMPLIANT_USDC_ADDRESS" \
  true \
  1 \
  "$US_JURISDICTION" \
  --rpc-url "$RPC_URL" \
  --private-key "$PRIVATE_KEY" \
  --legacy \
  --gas-price 30000000000 > /dev/null 2>&1 && echo "    ✅ Success" || echo "    ⚠️  Check if already set"

echo ""

# Step 5: Verification
echo -e "${YELLOW}Step 5: Verifying configuration...${NC}"

echo "  PolicyManager bridge for USDT:"
BRIDGE_USDT=$(cast call "$POLICY_MANAGER" "bridge(address)" "$COMPLIANT_USDT_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null)
if [ "$BRIDGE_USDT" = "$BRIDGE_VAULT" ]; then
    echo "    ✅ Correct: $BRIDGE_USDT"
else
    echo "    ⚠️  Expected: $BRIDGE_VAULT, Got: $BRIDGE_USDT"
fi

echo "  PolicyManager lien mode for USDT:"
LIEN_MODE=$(cast call "$POLICY_MANAGER" "lienMode(address)" "$COMPLIANT_USDT_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null | cast --to-dec)
if [ "$LIEN_MODE" = "2" ]; then
    echo "    ✅ Correct: 2 (encumbered)"
else
    echo "    ⚠️  Expected: 2, Got: $LIEN_MODE"
fi

echo "  CompliantUSDT is allowed:"
IS_ALLOWED=$(cast call "$COMPLIANCE_REGISTRY_ADDRESS" "isAllowed(address)" "$COMPLIANT_USDT_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null | cast --to-dec)
if [ "$IS_ALLOWED" = "1" ]; then
    echo "    ✅ Yes"
else
    echo "    ⚠️  No"
fi

echo ""

# Step 6: Run Integration Tests
echo -e "${YELLOW}Step 6: Running integration tests...${NC}"
forge test --via-ir --match-contract Integration 2>&1 | grep -E "(PASS|FAIL|tests passed|tests failed)" | tail -5

echo ""

echo -e "${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║     Configuration Complete!                                 ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo "Next steps:"
echo "  1. Verify contracts on explorer: https://explorer.d-bis.org"
echo "  2. Review test results above"
echo "  3. Set up monitoring and alerting"
echo "  4. Configure multisig governance (production)"
