#!/bin/bash

# Complete Deployment and Integration Script
# This script deploys all new contracts and performs integration steps

set -e

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

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

echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     Complete Deployment and Integration Script              ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""

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

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

# Set defaults
RPC_URL=${RPC_URL:-${RPC_URL_138:-"http://192.168.11.250:8545"}}
GAS_PRICE=${GAS_PRICE:-20000000000}
DEPLOYER=$(cast wallet address $PRIVATE_KEY 2>/dev/null || echo "")
COMPLIANCE_ADMIN=${COMPLIANCE_ADMIN:-$DEPLOYER}

echo -e "${GREEN}Configuration:${NC}"
echo "  RPC URL: $RPC_URL"
echo "  Deployer: $DEPLOYER"
echo "  Compliance Admin: $COMPLIANCE_ADMIN"
echo "  Gas Price: $GAS_PRICE"
echo ""

# Verify RPC connection
echo -e "${YELLOW}Verifying RPC connection...${NC}"
BLOCK_NUMBER=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
if [ "$BLOCK_NUMBER" = "0" ]; then
    echo -e "${RED}Error: Cannot connect to RPC${NC}"
    exit 1
fi
echo -e "${GREEN}✅ Connected - Block: $BLOCK_NUMBER${NC}"
echo ""

# Verify balance
echo -e "${YELLOW}Checking deployer balance...${NC}"
BALANCE=$(cast balance "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
BALANCE_ETH=$(echo "scale=4; $BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
if (( $(echo "$BALANCE_ETH < 0.1" | bc -l 2>/dev/null || echo 1) )); then
    echo -e "${YELLOW}⚠️  Warning: Low balance ($BALANCE_ETH ETH). Recommended: 0.1+ ETH${NC}"
else
    echo -e "${GREEN}✅ Balance: $BALANCE_ETH ETH${NC}"
fi
echo ""

# ============================================
# PHASE 2: DEPLOYMENT
# ============================================

echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     Phase 2: Deployment                                      ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""

# Step 1: Deploy ComplianceRegistry
echo -e "${YELLOW}Step 1: Deploying ComplianceRegistry...${NC}"
forge script script/DeployComplianceRegistry.s.sol:DeployComplianceRegistry \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --legacy \
    --gas-price "$GAS_PRICE" \
    --via-ir \
    -vv 2>&1 | tee /tmp/compliance-registry-deploy.log

COMPLIANCE_REGISTRY=$(grep "ComplianceRegistry deployed at:" /tmp/compliance-registry-deploy.log | tail -1 | awk '{print $NF}' | tr -d ':')
if [ -z "$COMPLIANCE_REGISTRY" ] || [ "$COMPLIANCE_REGISTRY" = "null" ]; then
    echo -e "${RED}Error: Failed to extract ComplianceRegistry address${NC}"
    exit 1
fi

echo -e "${GREEN}✅ ComplianceRegistry deployed at: $COMPLIANCE_REGISTRY${NC}"
echo "COMPLIANCE_REGISTRY_ADDRESS=$COMPLIANCE_REGISTRY" >> .env
echo ""

# Step 2: Deploy CompliantUSDT
echo -e "${YELLOW}Step 2: Deploying CompliantUSDT...${NC}"
export COMPLIANCE_ADMIN
forge script script/DeployCompliantUSDT.s.sol:DeployCompliantUSDT \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --legacy \
    --gas-price "$GAS_PRICE" \
    --via-ir \
    -vv 2>&1 | tee /tmp/compliant-usdt-deploy.log

COMPLIANT_USDT=$(grep "CompliantUSDT deployed at:" /tmp/compliant-usdt-deploy.log | tail -1 | awk '{print $NF}' | tr -d ':')
if [ -z "$COMPLIANT_USDT" ] || [ "$COMPLIANT_USDT" = "null" ]; then
    echo -e "${RED}Error: Failed to extract CompliantUSDT address${NC}"
    exit 1
fi

echo -e "${GREEN}✅ CompliantUSDT deployed at: $COMPLIANT_USDT${NC}"
echo "COMPLIANT_USDT_ADDRESS=$COMPLIANT_USDT" >> .env
echo ""

# Step 3: Deploy CompliantUSDC
echo -e "${YELLOW}Step 3: Deploying CompliantUSDC...${NC}"
forge script script/DeployCompliantUSDC.s.sol:DeployCompliantUSDC \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --legacy \
    --gas-price "$GAS_PRICE" \
    --via-ir \
    -vv 2>&1 | tee /tmp/compliant-usdc-deploy.log

COMPLIANT_USDC=$(grep "CompliantUSDC deployed at:" /tmp/compliant-usdc-deploy.log | tail -1 | awk '{print $NF}' | tr -d ':')
if [ -z "$COMPLIANT_USDC" ] || [ "$COMPLIANT_USDC" = "null" ]; then
    echo -e "${RED}Error: Failed to extract CompliantUSDC address${NC}"
    exit 1
fi

echo -e "${GREEN}✅ CompliantUSDC deployed at: $COMPLIANT_USDC${NC}"
echo "COMPLIANT_USDC_ADDRESS=$COMPLIANT_USDC" >> .env
echo ""

# Step 4: Deploy TokenRegistry
echo -e "${YELLOW}Step 4: Deploying TokenRegistry...${NC}"
forge script script/DeployTokenRegistry.s.sol:DeployTokenRegistry \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --legacy \
    --gas-price "$GAS_PRICE" \
    --via-ir \
    -vv 2>&1 | tee /tmp/token-registry-deploy.log

TOKEN_REGISTRY=$(grep "TokenRegistry deployed at:" /tmp/token-registry-deploy.log | tail -1 | awk '{print $NF}' | tr -d ':')
if [ -z "$TOKEN_REGISTRY" ] || [ "$TOKEN_REGISTRY" = "null" ]; then
    echo -e "${RED}Error: Failed to extract TokenRegistry address${NC}"
    exit 1
fi

echo -e "${GREEN}✅ TokenRegistry deployed at: $TOKEN_REGISTRY${NC}"
echo "TOKEN_REGISTRY_ADDRESS=$TOKEN_REGISTRY" >> .env
echo ""

# Step 5: Deploy FeeCollector
echo -e "${YELLOW}Step 5: Deploying FeeCollector...${NC}"
forge script script/DeployFeeCollector.s.sol:DeployFeeCollector \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --legacy \
    --gas-price "$GAS_PRICE" \
    --via-ir \
    -vv 2>&1 | tee /tmp/fee-collector-deploy.log

FEE_COLLECTOR=$(grep "FeeCollector deployed at:" /tmp/fee-collector-deploy.log | tail -1 | awk '{print $NF}' | tr -d ':')
if [ -z "$FEE_COLLECTOR" ] || [ "$FEE_COLLECTOR" = "null" ]; then
    echo -e "${RED}Error: Failed to extract FeeCollector address${NC}"
    exit 1
fi

echo -e "${GREEN}✅ FeeCollector deployed at: $FEE_COLLECTOR${NC}"
echo "FEE_COLLECTOR_ADDRESS=$FEE_COLLECTOR" >> .env
echo ""

# ============================================
# PHASE 3: INTEGRATION
# ============================================

echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     Phase 3: Integration                                     ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""

# Step 6: Register CompliantUSDT in ComplianceRegistry
echo -e "${YELLOW}Step 6: Registering CompliantUSDT in ComplianceRegistry...${NC}"
cast send "$COMPLIANCE_REGISTRY" \
    "registerContract(address)" \
    "$COMPLIANT_USDT" \
    --rpc-url "$RPC_URL" \
    --private-key "$PRIVATE_KEY" \
    --legacy \
    --gas-price "$GAS_PRICE" 2>&1 | tee /tmp/register-usdt.log || echo -e "${YELLOW}⚠️  Warning: Registration may have failed${NC}"

# Verify registration
REGISTERED=$(cast call "$COMPLIANCE_REGISTRY" "isContractRegistered(address)" "$COMPLIANT_USDT" --rpc-url "$RPC_URL" 2>/dev/null || echo "false")
if [ "$REGISTERED" = "true" ]; then
    echo -e "${GREEN}✅ CompliantUSDT registered successfully${NC}"
else
    echo -e "${YELLOW}⚠️  CompliantUSDT registration status: $REGISTERED${NC}"
fi
echo ""

# Step 7: Register CompliantUSDC in ComplianceRegistry
echo -e "${YELLOW}Step 7: Registering CompliantUSDC in ComplianceRegistry...${NC}"
cast send "$COMPLIANCE_REGISTRY" \
    "registerContract(address)" \
    "$COMPLIANT_USDC" \
    --rpc-url "$RPC_URL" \
    --private-key "$PRIVATE_KEY" \
    --legacy \
    --gas-price "$GAS_PRICE" 2>&1 | tee /tmp/register-usdc.log || echo -e "${YELLOW}⚠️  Warning: Registration may have failed${NC}"

# Verify registration
REGISTERED=$(cast call "$COMPLIANCE_REGISTRY" "isContractRegistered(address)" "$COMPLIANT_USDC" --rpc-url "$RPC_URL" 2>/dev/null || echo "false")
if [ "$REGISTERED" = "true" ]; then
    echo -e "${GREEN}✅ CompliantUSDC registered successfully${NC}"
else
    echo -e "${YELLOW}⚠️  CompliantUSDC registration status: $REGISTERED${NC}"
fi
echo ""

# Step 8: Register CompliantUSDT in TokenRegistry
echo -e "${YELLOW}Step 8: Registering CompliantUSDT in TokenRegistry...${NC}"
cast send "$TOKEN_REGISTRY" \
    "registerToken(address,string,string,uint8,bool,address)" \
    "$COMPLIANT_USDT" \
    "Tether USD (Compliant)" \
    "cUSDT" \
    6 \
    false \
    0x0000000000000000000000000000000000000000 \
    --rpc-url "$RPC_URL" \
    --private-key "$PRIVATE_KEY" \
    --legacy \
    --gas-price "$GAS_PRICE" 2>&1 | tee /tmp/register-usdt-token.log || echo -e "${YELLOW}⚠️  Warning: Token registration may have failed${NC}"

# Verify registration
REGISTERED=$(cast call "$TOKEN_REGISTRY" "isTokenRegistered(address)" "$COMPLIANT_USDT" --rpc-url "$RPC_URL" 2>/dev/null || echo "false")
if [ "$REGISTERED" = "true" ]; then
    echo -e "${GREEN}✅ CompliantUSDT registered in TokenRegistry${NC}"
else
    echo -e "${YELLOW}⚠️  CompliantUSDT token registration status: $REGISTERED${NC}"
fi
echo ""

# Step 9: Register CompliantUSDC in TokenRegistry
echo -e "${YELLOW}Step 9: Registering CompliantUSDC in TokenRegistry...${NC}"
cast send "$TOKEN_REGISTRY" \
    "registerToken(address,string,string,uint8,bool,address)" \
    "$COMPLIANT_USDC" \
    "USD Coin (Compliant)" \
    "cUSDC" \
    6 \
    false \
    0x0000000000000000000000000000000000000000 \
    --rpc-url "$RPC_URL" \
    --private-key "$PRIVATE_KEY" \
    --legacy \
    --gas-price "$GAS_PRICE" 2>&1 | tee /tmp/register-usdc-token.log || echo -e "${YELLOW}⚠️  Warning: Token registration may have failed${NC}"

# Verify registration
REGISTERED=$(cast call "$TOKEN_REGISTRY" "isTokenRegistered(address)" "$COMPLIANT_USDC" --rpc-url "$RPC_URL" 2>/dev/null || echo "false")
if [ "$REGISTERED" = "true" ]; then
    echo -e "${GREEN}✅ CompliantUSDC registered in TokenRegistry${NC}"
else
    echo -e "${YELLOW}⚠️  CompliantUSDC token registration status: $REGISTERED${NC}"
fi
echo ""

# ============================================
# PHASE 4: VERIFICATION
# ============================================

echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     Phase 4: Verification                                    ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""

# Verify all contracts have code
echo -e "${YELLOW}Verifying contract code on-chain...${NC}"

verify_contract() {
    local name=$1
    local address=$2
    local code=$(cast code "$address" --rpc-url "$RPC_URL" 2>/dev/null | wc -c)
    if [ "$code" -gt 100 ]; then
        echo -e "${GREEN}✅ $name: Code size $code bytes${NC}"
        return 0
    else
        echo -e "${RED}❌ $name: Code size only $code bytes (may not be deployed)${NC}"
        return 1
    fi
}

verify_contract "ComplianceRegistry" "$COMPLIANCE_REGISTRY"
verify_contract "CompliantUSDT" "$COMPLIANT_USDT"
verify_contract "CompliantUSDC" "$COMPLIANT_USDC"
verify_contract "TokenRegistry" "$TOKEN_REGISTRY"
verify_contract "FeeCollector" "$FEE_COLLECTOR"
echo ""

# ============================================
# SUMMARY
# ============================================

echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     Deployment and Integration Complete!                    ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${GREEN}Deployed Contracts:${NC}"
echo "  ComplianceRegistry: $COMPLIANCE_REGISTRY"
echo "  CompliantUSDT:      $COMPLIANT_USDT"
echo "  CompliantUSDC:      $COMPLIANT_USDC"
echo "  TokenRegistry:      $TOKEN_REGISTRY"
echo "  FeeCollector:       $FEE_COLLECTOR"
echo ""
echo -e "${GREEN}Next Steps:${NC}"
echo "  1. Verify contracts on block explorer"
echo "  2. Update service .env files with new addresses"
echo "  3. Configure FeeCollector recipients (if needed)"
echo "  4. Test end-to-end functionality"
echo ""
echo -e "${GREEN}All addresses saved to .env file${NC}"
echo ""
