#!/bin/bash

# Provenance Blockchain Loan Workflow Demo
# This script demonstrates the complete workflow for creating and managing a loan
# using the x/asset, x/ledger, and x/registry modules

set -e  # Exit on any error

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

# Configuration for local instance (make run)
CHAIN_ID="testing"
NODE="http://localhost:26657"
GAS_PRICES="1nhash"
GAS_ADJUSTMENT="1.5"
PIO_HOME="build/run/provenanced"

# Demo addresses (will be created and funded)
ORIGINATOR_ADDR=""
SERVICER_ADDR=""
BORROWER_ADDR=""

# Account names for keyring
ORIGINATOR_NAME="originator"
SERVICER_NAME="servicer"
BORROWER_NAME="borrower"

# Funding amounts
FUNDING_AMOUNT="1000000000000nhash"  # 1000 hash per account

# Asset and loan details
ASSET_CLASS_ID="cre-asset-class"
ASSET_ID="cre-nft-001"
ASSET_ID_2="cre-nft-002"
LEDGER_CLASS_ID="cre-ledger-class"

# Function to print section headers
print_section() {
    echo -e "${YELLOW}$1${NC}"
    echo -e "${YELLOW}$(printf '=%.0s' {1..${#1}})${NC}"
    echo ""
}

# Function to execute and display commands
execute_cmd() {
    local cmd="$1"
    local description="$2"
    
    echo -e "${GREEN}Executing:${NC} $description"
    echo -e "${BLUE}Command:${NC} $cmd"
    echo ""
    
    # Execute the command
    eval "$cmd"
    
    echo -e "${GREEN}✓ Command completed successfully${NC}"
    echo ""
}

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Provenance Loan Workflow Demo${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Step 0: Account Setup and Funding
print_section "Step 0: Account Setup and Funding"

echo "Creating demo accounts..."
execute_cmd \
    "provenanced keys add $ORIGINATOR_NAME --keyring-backend test --home $PIO_HOME" \
    "Create originator account"

execute_cmd \
    "provenanced keys add $SERVICER_NAME --keyring-backend test --home $PIO_HOME" \
    "Create servicer account"

execute_cmd \
    "provenanced keys add $BORROWER_NAME --keyring-backend test --home $PIO_HOME" \
    "Create borrower account"

echo "Getting account addresses..."
ORIGINATOR_ADDR=$(provenanced keys show $ORIGINATOR_NAME -a --keyring-backend test --home $PIO_HOME --testnet)
SERVICER_ADDR=$(provenanced keys show $SERVICER_NAME -a --keyring-backend test --home $PIO_HOME --testnet)
BORROWER_ADDR=$(provenanced keys show $BORROWER_NAME -a --keyring-backend test --home $PIO_HOME --testnet)

echo -e "${GREEN}Originator address:${NC} $ORIGINATOR_ADDR"
echo -e "${GREEN}Servicer address:${NC} $SERVICER_ADDR"
echo -e "${GREEN}Borrower address:${NC} $BORROWER_ADDR"
echo ""

echo "Funding accounts with nhash from validator account..."
execute_cmd \
    "provenanced tx bank send validator $ORIGINATOR_ADDR $FUNDING_AMOUNT --keyring-backend test --home $PIO_HOME --chain-id $CHAIN_ID --node $NODE --gas auto --gas-prices $GAS_PRICES --gas-adjustment $GAS_ADJUSTMENT --yes --testnet | provenanced q wait-tx" \
    "Fund originator account from validator"

execute_cmd \
    "provenanced tx bank send validator $SERVICER_ADDR $FUNDING_AMOUNT --keyring-backend test --home $PIO_HOME --chain-id $CHAIN_ID --node $NODE --gas auto --gas-prices $GAS_PRICES --gas-adjustment $GAS_ADJUSTMENT --yes --testnet | provenanced q wait-tx" \
    "Fund servicer account from validator"

execute_cmd \
    "provenanced tx bank send validator $BORROWER_ADDR $FUNDING_AMOUNT --keyring-backend test --home $PIO_HOME --chain-id $CHAIN_ID --node $NODE --gas auto --gas-prices $GAS_PRICES --gas-adjustment $GAS_ADJUSTMENT --yes --testnet | provenanced q wait-tx" \
    "Fund borrower account from validator"

echo "Checking account balances..."
execute_cmd \
    "provenanced query bank balances $ORIGINATOR_ADDR --node $NODE --home $PIO_HOME --testnet" \
    "Check originator balance"

execute_cmd \
    "provenanced query bank balances $SERVICER_ADDR --node $NODE --home $PIO_HOME --testnet" \
    "Check servicer balance"

execute_cmd \
    "provenanced query bank balances $BORROWER_ADDR --node $NODE --home $PIO_HOME --testnet" \
    "Check borrower balance"

# Step 1: Asset Creation (x/asset)
print_section "Step 1: Asset Creation (x/asset)"

echo "Creating asset class for commercial real estate..."
execute_cmd \
    "provenanced tx asset create-class \"$ASSET_CLASS_ID\" \"Commercial Real Estate\" \"CRE\" \"Commercial real estate properties\" \"https://metadata.example.com/class-metadata.json\" \"def456\" '{\"$schema\": \"http://json-schema.org/draft-07/schema#\", \"type\": \"object\", \"properties\": {\"address\": {\"type\": \"string\", \"description\": \"Property address\"}, \"sqft\": {\"type\": \"integer\", \"description\": \"Square footage\"}, \"value\": {\"type\": \"integer\", \"description\": \"Property value in dollars\"}, \"property_type\": {\"type\": \"string\", \"enum\": [\"office\", \"retail\", \"industrial\", \"multifamily\"]}, \"year_built\": {\"type\": \"integer\", \"description\": \"Year the property was built\"}}, \"required\": [\"address\", \"sqft\", \"value\"]}' \
        --from $ORIGINATOR_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Create asset class for commercial real estate"

echo "Creating the specific property asset #1..."
execute_cmd \
    "provenanced tx asset create-asset \"$ASSET_CLASS_ID\" \"$ASSET_ID\" \"https://metadata.example.com/property-123\" \"abc123\" '{\"address\": \"123 Main St\", \"sqft\": 1000, \"value\": 1000000, \"property_type\": \"home\", \"year_built\": 2001}' \"$ORIGINATOR_ADDR\" \
        --from $ORIGINATOR_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Create the specific property asset"


echo "Creating the specific property asset #2..."   
execute_cmd \
    "provenanced tx asset create-asset \"$ASSET_CLASS_ID\" \"$ASSET_ID_2\" \"https://metadata.example.com/property-456\" \"abc456\" '{\"address\": \"456 Main St\", \"sqft\": 2000, \"value\": 200000, \"property_type\": \"home\", \"year_built\": 2002}' \"$ORIGINATOR_ADDR\" \
        --from $ORIGINATOR_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Create the specific property asset"

# Step 2: Registry Setup (x/registry)
print_section "Step 2: Registry Setup (x/registry)"

echo "Granting servicer role to servicer account..."
execute_cmd \
    "provenanced tx registry grant-role \"$ASSET_CLASS_ID\" \"$ASSET_ID\" \"REGISTRY_ROLE_SERVICER\" \"$SERVICER_ADDR\" \
        --from $ORIGINATOR_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Grant servicer role to servicer account"

echo "Granting borrower role to borrower account..."
execute_cmd \
    "provenanced tx registry grant-role \"$ASSET_CLASS_ID\" \"$ASSET_ID_2\" \"REGISTRY_ROLE_BORROWER\" \"$BORROWER_ADDR\" \
        --from $ORIGINATOR_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Grant borrower role to borrower account"

# echo "Granting borrower role to borrower account..."
# execute_cmd \
#     "provenanced tx registry grant-role \"$ASSET_CLASS_ID\" \"$ASSET_ID\" \"REGISTRY_ROLE_BORROWER\" \"$BORROWER_ADDR\" \
#         --from $ORIGINATOR_NAME \
#         --keyring-backend test \
#         --home $PIO_HOME \
#         --chain-id $CHAIN_ID \
#         --node $NODE \
#         --gas auto \
#         --gas-prices $GAS_PRICES \
#         --gas-adjustment $GAS_ADJUSTMENT \
#         --testnet \
#         --yes | provenanced q wait-tx" \
#     "Grant borrower role to borrower account"

# Step 3: Ledger Creation (x/ledger)
print_section "Step 3: Ledger Creation (x/ledger)"

echo "Creating ledger class for commercial real estate..."
execute_cmd \
    "provenanced tx ledger create-class $LEDGER_CLASS_ID $ASSET_CLASS_ID nhash \
        --from $SERVICER_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Create ledger class for commercial real estate"

echo "Adding status types to ledger class..."
execute_cmd \
    "provenanced tx ledger add-status-type $LEDGER_CLASS_ID 1 IN_REPAYMENT \"In Repayment\" \
        --from $SERVICER_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Add IN_REPAYMENT status type"

echo "Adding entry types to ledger class..."
execute_cmd \
    "provenanced tx ledger add-entry-type $LEDGER_CLASS_ID 1 DISBURSEMENT \"Disbursement\" \
        --from $SERVICER_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Add DISBURSEMENT entry type"

execute_cmd \
    "provenanced tx ledger add-entry-type $LEDGER_CLASS_ID 2 SCHEDULED_PAYMENT \"Scheduled Payment\" \
        --from $SERVICER_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Add SCHEDULED_PAYMENT entry type"

execute_cmd \
    "provenanced tx ledger add-entry-type $LEDGER_CLASS_ID 3 INTEREST_ACCRUAL \"Interest Accrual\" \
        --from $SERVICER_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Add INTEREST_ACCRUAL entry type"

execute_cmd \
    "provenanced tx ledger add-entry-type $LEDGER_CLASS_ID 4 UNSCHEDULED_PAYMENT \"Unscheduled Payment\" \
        --from $SERVICER_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Add UNSCHEDULED_PAYMENT entry type"

execute_cmd \
    "provenanced tx ledger add-entry-type $LEDGER_CLASS_ID 5 FEE \"Fee\" \
        --from $SERVICER_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Add FEE entry type"

echo "Adding bucket types to ledger class..."
execute_cmd \
    "provenanced tx ledger add-bucket-type $LEDGER_CLASS_ID 1 PRINCIPAL \"Principal\" \
        --from $SERVICER_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Add PRINCIPAL bucket type"

execute_cmd \
    "provenanced tx ledger add-bucket-type $LEDGER_CLASS_ID 2 INTEREST \"Interest\" \
        --from $SERVICER_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Add INTEREST bucket type"

execute_cmd \
    "provenanced tx ledger add-bucket-type $LEDGER_CLASS_ID 3 OTHER \"Other\" \
        --from $SERVICER_NAME \
        --keyring-backend test \
        --home $PIO_HOME \
        --chain-id $CHAIN_ID \
        --node $NODE \
        --gas auto \
        --gas-prices $GAS_PRICES \
        --gas-adjustment $GAS_ADJUSTMENT \
        --testnet \
        --yes | provenanced q wait-tx" \
    "Add OTHER bucket type"

# echo "Creating a ledger for the loan..."
# execute_cmd \
#     "provenanced tx ledger create \"$ASSET_CLASS_ID\" \"$ASSET_ID\" \"$LEDGER_CLASS_ID\" 1 \
#         --from $SERVICER_NAME \
#         --keyring-backend test \
#         --home $PIO_HOME \
#         --chain-id $CHAIN_ID \
#         --node $NODE \
#         --gas auto \
#         --gas-prices $GAS_PRICES \
#         --gas-adjustment $GAS_ADJUSTMENT \
#         --testnet \
#         --yes | provenanced q wait-tx" \
#     "Create ledger for the loan with repayment terms"

# # Step 4: Loan Disbursement
# print_section "Step 4: Loan Disbursement"

# echo "Recording the initial loan entries..."
# execute_cmd \
#     "provenanced tx ledger append \"$ASSET_CLASS_ID\" \"$ASSET_ID\" data.json \
#         --from $SERVICER_NAME \
#         --keyring-backend test \
#         --home $PIO_HOME \
#         --chain-id $CHAIN_ID \
#         --node $NODE \
#         --gas auto \
#         --gas-prices $GAS_PRICES \
#         --gas-adjustment $GAS_ADJUSTMENT \
#         --testnet \
#         --yes | provenanced q wait-tx" \
#     "Record initial loan disbursement of $1,500,000"

# # Step 6: Query Examples
# print_section "Step 7: Query Examples"

# echo "Querying the asset..."
# execute_cmd \
#     "provenanced query asset list-assets \"$ORIGINATOR_ADDR\" --node $NODE --home $PIO_HOME --testnet" \
#     "Query specific asset details"

# echo "Querying registry entry..."
# execute_cmd \
#     "provenanced query registry registry \"$ASSET_CLASS_ID\" \"$ASSET_ID\" --node $NODE --home $PIO_HOME --testnet" \
#     "Query registry entry and roles"

# echo "Querying ledger details..."
# execute_cmd \
#     "provenanced query ledger get \"$ASSET_CLASS_ID\" \"$ASSET_ID\" --node $NODE --home $PIO_HOME --testnet" \
#     "Query ledger details"

# echo "Querying ledger entries..."
# execute_cmd \
#     "provenanced query ledger entries \"$ASSET_CLASS_ID\" \"$ASSET_ID\" --node $NODE --home $PIO_HOME --testnet" \
#     "Query all ledger entries"

# # Step 8: Additional Operations
# print_section "Step 8: Additional Operations"

# echo "Granting additional role to borrower..."
# execute_cmd \
#     "provenanced tx registry grant-role \"$ASSET_CLASS_ID\" \"$ASSET_ID\" \"REGISTRY_ROLE_CONTROLLER\" \"$BORROWER_ADDR\" \
#         --from $ORIGINATOR_NAME \
#         --keyring-backend test \
#         --home $PIO_HOME \
#         --chain-id $CHAIN_ID \
#         --node $NODE \
#         --gas auto \
#         --gas-prices $GAS_PRICES \
#         --gas-adjustment $GAS_ADJUSTMENT \
#         --testnet \
#         --yes | provenanced q wait-tx" \
#     "Grant controller role to borrower"

# echo "Recording an borrower payment and fee..."
# execute_cmd \
#     "provenanced tx ledger append \"$ASSET_CLASS_ID\" \"$ASSET_ID\" data2.json \
#         --from $SERVICER_NAME \
#         --keyring-backend test \
#         --home $PIO_HOME \
#         --chain-id $CHAIN_ID \
#         --node $NODE \
#         --gas auto \
#         --gas-prices $GAS_PRICES \
#         --gas-adjustment $GAS_ADJUSTMENT \
#         --testnet \
#         --yes | provenanced q wait-tx" \
#     "Record unscheduled payment of $50,000 (principal only)"

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  Demo Completed Successfully!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "${BLUE}Summary of operations performed:${NC}"
echo "✓ Created and funded demo accounts (originator, servicer, borrower)"
echo "✓ Created ledger class for commercial real estate"
echo "✓ Created asset class for commercial real estate"
echo "✓ Created property asset"
echo "✓ Registered property with roles"
echo "✓ Created ledger for loan tracking"
echo "✓ Recorded loan disbursement"
echo "✓ Recorded monthly payment"
echo "✓ Recorded interest accrual"
echo "✓ Performed various queries"
echo "✓ Demonstrated additional operations"
echo ""
echo -e "${YELLOW}Note:${NC} This script is configured to run against a local Provenance instance started with 'make run'."
echo -e "${YELLOW}Remember:${NC} This script creates test accounts with the 'test' keyring backend in the local instance." 