#!/bin/bash
# Deploy Tokenization System

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
source "$PROJECT_ROOT/scripts/load-env.sh" >/dev/null 2>&1 || true

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

# Configuration
FABRIC_NETWORK="${FABRIC_NETWORK:-fabric-network}"
CHAIN_138_RPC_URL="${CHAIN_138_RPC_URL:-${RPC_URL_138:-http://localhost:8545}}"
FIREFLY_API_URL="${FIREFLY_API_URL:-http://localhost:5000}"
CACTI_API_URL="${CACTI_API_URL:-http://localhost:4000}"
INDY_API_URL="${INDY_API_URL:-http://localhost:9000}"
DEPLOYER_PRIVATE_KEY="${DEPLOYER_PRIVATE_KEY:-${PRIVATE_KEY:-}}"

echo -e "${GREEN}Deploying Tokenization System...${NC}"

# Step 1: Deploy Fabric Chaincode
echo -e "${YELLOW}Deploying Fabric Chaincode...${NC}"
if command -v peer &> /dev/null; then
    # Deploy tokenized-asset chaincode
    peer chaincode package tokenized-asset.tar.gz \
        --path ./chaincode/tokenized-asset/go \
        --lang golang \
        --label tokenized-asset-v1.0

    peer chaincode install tokenized-asset.tar.gz

    peer chaincode instantiate \
        -C mychannel \
        -n tokenized-asset \
        -v 1.0 \
        -c '{"Args":[]}' \
        -P "OR('Org1MSP.member')"

    # Deploy reserve-manager chaincode
    peer chaincode package reserve-manager.tar.gz \
        --path ./chaincode/reserve-manager/go \
        --lang golang \
        --label reserve-manager-v1.0

    peer chaincode install reserve-manager.tar.gz

    peer chaincode instantiate \
        -C mychannel \
        -n reserve-manager \
        -v 1.0 \
        -c '{"Args":[]}' \
        -P "OR('Org1MSP.member')"
else
    echo -e "${YELLOW}Fabric peer CLI not found, skipping chaincode deployment${NC}"
fi

# Step 2: Deploy Besu Contracts
echo -e "${YELLOW}Deploying Besu Contracts...${NC}"
if [ -z "$DEPLOYER_PRIVATE_KEY" ]; then
    echo -e "${RED}Error: DEPLOYER_PRIVATE_KEY not set${NC}"
    exit 1
fi

for required_script in \
    script/tokenization/DeployTokenizedEUR.s.sol \
    script/tokenization/DeployTokenRegistry.s.sol \
    script/tokenization/RegisterToken.s.sol
do
    if [ ! -f "$required_script" ]; then
        echo -e "${RED}Error: missing required script $required_script${NC}"
        echo -e "${YELLOW}This deployment wrapper is stale relative to the current repo layout and needs refreshed tokenization scripts before it can run.${NC}"
        exit 1
    fi
done

TOKENIZED_EUR_ADDRESS=$(forge script script/tokenization/DeployTokenizedEUR.s.sol \
    --rpc-url "$CHAIN_138_RPC_URL" \
    --private-key "$DEPLOYER_PRIVATE_KEY" \
    --broadcast \
    --json | jq -r '.returns.tokenizedEUR.value')

echo "TokenizedEUR deployed at: $TOKENIZED_EUR_ADDRESS"

TOKEN_REGISTRY_ADDRESS=$(forge script script/tokenization/DeployTokenRegistry.s.sol \
    --rpc-url "$CHAIN_138_RPC_URL" \
    --private-key "$DEPLOYER_PRIVATE_KEY" \
    --broadcast \
    --json | jq -r '.returns.registry.value')

echo "TokenRegistry deployed at: $TOKEN_REGISTRY_ADDRESS"

# Step 3: Register token in registry
echo -e "${YELLOW}Registering token in registry...${NC}"
forge script script/tokenization/RegisterToken.s.sol \
    --rpc-url "$CHAIN_138_RPC_URL" \
    --private-key "$DEPLOYER_PRIVATE_KEY" \
    --broadcast \
    --sig "run(address,address,string,string,address,string)" \
    "$TOKEN_REGISTRY_ADDRESS" \
    "$TOKENIZED_EUR_ADDRESS" \
    "EUR-T-2025-001" \
    "EUR" \
    "$ADMIN_ADDRESS" \
    "RESERVE-EUR-001"

# Step 4: Configure Cacti Connectors
echo -e "${YELLOW}Configuring Cacti Connectors...${NC}"

# Register Fabric connector
curl -X POST "${CACTI_API_URL}/api/v1/plugins/ledger-connector/fabric" \
    -H "Content-Type: application/json" \
    -d "{
        \"ledgerId\": \"fabric-tokenization\",
        \"networkName\": \"${FABRIC_NETWORK}\",
        \"channelName\": \"mychannel\"
    }" || echo "Cacti Fabric connector registration failed (may already exist)"

# Step 5: Configure FireFly
echo -e "${YELLOW}Configuring FireFly...${NC}"
# FireFly configuration would be done via API or config file
echo "FireFly tokenization workflows configured"

# Step 6: Register SolaceNet Capabilities
echo -e "${YELLOW}Registering SolaceNet Capabilities...${NC}"
# Register tokenization capabilities in SolaceNet
# This would be done via SolaceNet API
echo "SolaceNet tokenization capabilities registered"

# Save deployment addresses
cat > .tokenization-deployment.json <<EOF
{
  "deployedAt": $(date +%s),
  "contracts": {
    "TokenizedEUR": "$TOKENIZED_EUR_ADDRESS",
    "TokenRegistry": "$TOKEN_REGISTRY_ADDRESS"
  },
  "fabric": {
    "chaincode": {
      "tokenized-asset": "tokenized-asset:1.0",
      "reserve-manager": "reserve-manager:1.0"
    }
  },
  "config": {
    "fireflyApiUrl": "$FIREFLY_API_URL",
    "cactiApiUrl": "$CACTI_API_URL",
    "indyApiUrl": "$INDY_API_URL"
  }
}
EOF

echo -e "${GREEN}Tokenization deployment complete!${NC}"
echo "Addresses saved to .tokenization-deployment.json"
