#!/usr/bin/env bash

# Consolidated Cost Calculator
# Replaces: calculate-accurate-costs.sh, calculate-accurate-deployment-costs.sh,
#           calculate-conservative-costs.sh, calculate-contract-deployment-costs.sh,
#           calculate-gas-fees.sh, update-all-cost-estimates.sh, update-cost-estimates.sh,
#           finalize-cost-estimates.sh, get-accurate-gas-price.sh, get-conservative-gas-price.sh,
#           get-mainnet-gas-prices.sh, get-real-gas-prices.sh, test-etherscan-gas-api.sh
#
# Usage:
#   calculate-costs-consolidated.sh [--source TYPE] [--eth-price USD] [--gas TYPE] [--format OUTPUT]
#   Sources: auto, rpc, infura, default, conservative
#   Gas types: deployment, configuration, total, custom

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
load_env --file "$SCRIPT_DIR/../../.env" ${ENV_PROFILE:+--profile "$ENV_PROFILE"}
SCRIPT_NAME="calculate-costs-consolidated.sh"
SCRIPT_DESC="Calculate deployment costs using costs.sh (supports JSON and text outputs)"
SCRIPT_USAGE="${SCRIPT_NAME} [--source auto|infura|conservative] [--format text|json] [--help]"
SCRIPT_OPTIONS="--source <name>     Gas price source (default: auto)\n--format <fmt>     Output format (text|json)\n--help             Show help"
SCRIPT_REQUIREMENTS="bc, costs.sh library, optional network access for gas feeds"
handle_help "${1:-}"

DRY_RUN="${DRY_RUN:-0}"
net_call() {
  if [ "$DRY_RUN" = "1" ]; then
    echo "[DRY RUN] simulate network call: $*"; echo ""; return 0
  fi
  "$@"
}
source "$SCRIPT_DIR/../lib/deployment/costs.sh"

# Defaults
GAS_SOURCE="${GAS_SOURCE:-auto}"
ETH_PRICE_USD="${ETH_PRICE_USD:-$(get_eth_price)}"
GAS_TYPE="${GAS_TYPE:-total}"
CUSTOM_GAS="${CUSTOM_GAS:-}"
OUTPUT_FORMAT="${OUTPUT_FORMAT:-table}"

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --source)
            GAS_SOURCE="$2"
            shift 2
            ;;
        --eth-price)
            ETH_PRICE_USD="$2"
            shift 2
            ;;
        --gas)
            GAS_TYPE="$2"
            shift 2
            ;;
        --custom-gas)
            CUSTOM_GAS="$2"
            shift 2
            ;;
        --format)
            OUTPUT_FORMAT="$2"
            shift 2
            ;;
        --help)
            cat << EOF
Consolidated Cost Calculator

Usage: $0 [OPTIONS]

Options:
  --source TYPE        Gas price source (auto|rpc|infura|default|conservative)
                      Default: auto
  --eth-price USD      ETH price in USD
                      Default: \$ETH_PRICE_USD or 2500
  --gas TYPE           Gas calculation type (deployment|configuration|total|custom)
                      Default: total
  --custom-gas N       Custom gas amount (requires --gas custom)
  --format FORMAT      Output format (table|json|csv)
                      Default: table
  --help               Show this help message

Examples:
  $0                                    # Calculate total costs with auto gas price
  $0 --source conservative              # Use conservative gas estimate
  $0 --gas deployment                   # Only deployment gas
  $0 --gas custom --custom-gas 500000   # Custom gas amount
  $0 --format json                      # JSON output
EOF
            exit 0
            ;;
        *)
            log_error "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Get gas price
log_info "Fetching gas price from $GAS_SOURCE source..."
RESULT=$(net_call get_gas_price "$GAS_SOURCE")
gas_price_wei=$(echo "$RESULT" | cut -d'|' -f1)
gas_price_gwei=$(echo "$RESULT" | cut -d'|' -f2)
source_name=$(echo "$RESULT" | cut -d'|' -f3)

log_success "Gas price: $gas_price_gwei gwei (from $source_name)"
echo ""

# Determine gas amounts
case "$GAS_TYPE" in
    deployment)
        total_gas=$((DEFAULT_CCIPWETH9_BRIDGE_GAS + DEFAULT_CCIPWETH10_BRIDGE_GAS))
        items=(
            "CCIPWETH9Bridge:$DEFAULT_CCIPWETH9_BRIDGE_GAS"
            "CCIPWETH10Bridge:$DEFAULT_CCIPWETH10_BRIDGE_GAS"
        )
        ;;
    configuration)
        total_gas=$DEFAULT_CONFIGURATION_GAS
        items=("Configuration:$DEFAULT_CONFIGURATION_GAS")
        ;;
    total)
        total_gas=$((DEFAULT_CCIPWETH9_BRIDGE_GAS + DEFAULT_CCIPWETH10_BRIDGE_GAS + DEFAULT_CONFIGURATION_GAS))
        items=(
            "CCIPWETH9Bridge:$DEFAULT_CCIPWETH9_BRIDGE_GAS"
            "CCIPWETH10Bridge:$DEFAULT_CCIPWETH10_BRIDGE_GAS"
            "Configuration:$DEFAULT_CONFIGURATION_GAS"
        )
        ;;
    custom)
        if [ -z "$CUSTOM_GAS" ]; then
            log_error "Custom gas amount required when using --gas custom"
            exit 1
        fi
        total_gas=$CUSTOM_GAS
        items=("Custom:$CUSTOM_GAS")
        ;;
    *)
        log_error "Invalid gas type: $GAS_TYPE"
        exit 1
        ;;
esac

# Calculate costs
log_section "COST CALCULATIONS"

if [ "$OUTPUT_FORMAT" = "table" ]; then
    echo "Gas Price: $gas_price_gwei gwei"
    echo "ETH Price: \$$ETH_PRICE_USD/ETH"
    echo ""
    printf "%-30s %18s %18s\n" "Item" "ETH" "USD"
    echo "$(printf '─%.0s' {1..66})"
    
    total_cost_eth=0
    for item_info in "${items[@]}"; do
        item_name="${item_info%%:*}"
        item_gas="${item_info##*:}"
        cost_eth=$(calculate_cost_eth "$item_gas" "$gas_price_wei")
        cost_usd=$(calculate_cost_usd "$cost_eth" "$ETH_PRICE_USD")
        total_cost_eth=$(echo "scale=10; $total_cost_eth + $cost_eth" | bc)
        format_cost_output "$item_name" "$cost_eth" "$cost_usd"
    done
    
    echo "$(printf '─%.0s' {1..66})"
    total_cost_usd=$(calculate_cost_usd "$total_cost_eth" "$ETH_PRICE_USD")
    printf "%-30s %18.8f ETH  $%15.2f\n" "${GREEN}Total${NC}" "$total_cost_eth" "$total_cost_usd"
    echo ""
    
    # Recommended buffer
    recommended_eth=$(echo "scale=8; $total_cost_eth * 2" | bc)
    recommended_usd=$(calculate_cost_usd "$recommended_eth" "$ETH_PRICE_USD")
    log_warn "Recommended Buffer: $recommended_eth ETH (\$$recommended_usd)"
    
elif [ "$OUTPUT_FORMAT" = "json" ]; then
    json_output="{"
    json_output+="\"gas_price_gwei\":\"$gas_price_gwei\","
    json_output+="\"gas_price_wei\":\"$gas_price_wei\","
    json_output+="\"source\":\"$source_name\","
    json_output+="\"eth_price_usd\":\"$ETH_PRICE_USD\","
    json_output+="\"items\":["
    
    first=true
    for item_info in "${items[@]}"; do
        [ "$first" = false ] && json_output+=","
        first=false
        item_name="${item_info%%:*}"
        item_gas="${item_info##*:}"
        cost_eth=$(calculate_cost_eth "$item_gas" "$gas_price_wei")
        cost_usd=$(calculate_cost_usd "$cost_eth" "$ETH_PRICE_USD")
        json_output+="{\"name\":\"$item_name\",\"gas\":$item_gas,\"cost_eth\":\"$cost_eth\",\"cost_usd\":\"$cost_usd\"}"
    done
    
    json_output+="],"
    total_cost_eth=$(calculate_cost_eth "$total_gas" "$gas_price_wei")
    total_cost_usd=$(calculate_cost_usd "$total_cost_eth" "$ETH_PRICE_USD")
    json_output+="\"total_gas\":$total_gas,"
    json_output+="\"total_cost_eth\":\"$total_cost_eth\","
    json_output+="\"total_cost_usd\":\"$total_cost_usd\""
    json_output+="}"
    
    echo "$json_output" | jq '.' 2>/dev/null || echo "$json_output"
    
elif [ "$OUTPUT_FORMAT" = "csv" ]; then
    echo "Item,Gas,Cost_ETH,Cost_USD"
    for item_info in "${items[@]}"; do
        item_name="${item_info%%:*}"
        item_gas="${item_info##*:}"
        cost_eth=$(calculate_cost_eth "$item_gas" "$gas_price_wei")
        cost_usd=$(calculate_cost_usd "$cost_eth" "$ETH_PRICE_USD")
        echo "$item_name,$item_gas,$cost_eth,$cost_usd"
    done
    total_cost_eth=$(calculate_cost_eth "$total_gas" "$gas_price_wei")
    total_cost_usd=$(calculate_cost_usd "$total_cost_eth" "$ETH_PRICE_USD")
    echo "Total,$total_gas,$total_cost_eth,$total_cost_usd"
fi

