#!/usr/bin/env bash
# =============================================================================
# init-env.sh
#
# Initializes the .env file from the testnet preset and auto-generates
# the operator wallet address.
#
# Usage:
#   ./scripts/init-env.sh
#
# Safe to re-run — skips if .env already exists.
# =============================================================================

set -euo pipefail
cd "$(dirname "$0")/.."

# ANSI colors
BOLD='\033[1m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
MAGENTA='\033[1;35m'
WHITE='\033[1;37m'
DIM='\033[2m'
RESET='\033[0m'
BG_YELLOW='\033[43m'

# Box width (inner content = 60 chars)
B="${GREEN}║${RESET}"

if [ -f .env ]; then
    echo -e "${CYAN}[init-env]${RESET} Existing .env found — regenerating..."
fi

echo -e "${CYAN}[init-env]${RESET} Creating .env from testnet preset..."
cp .env.testnet .env

# Generate JWT signing key for the Guardian proxy
JWT_KEY=$(openssl rand -hex 32)
sed -i.bak "s/^GUARDIAN_JWT_SIGNING_KEY_HEX=.*/GUARDIAN_JWT_SIGNING_KEY_HEX=${JWT_KEY}/" .env

WALLET_ADDR=""

# Get the operator wallet address
if command -v iota &> /dev/null; then
    echo -e "${CYAN}[init-env]${RESET} Switching IOTA CLI to testnet..."
    iota client switch --env testnet 2>/dev/null || true

    WALLET_ADDR=$(iota client active-address 2>/dev/null || echo "")
    if [ -n "$WALLET_ADDR" ]; then
        sed -i.bak "s/^GUARDIAN_PAYMENT_RECIPIENT=.*/GUARDIAN_PAYMENT_RECIPIENT=${WALLET_ADDR}/" .env

        echo -e "${CYAN}[init-env]${RESET} Funding wallet from testnet faucet..."
        iota client faucet 2>&1 | sed 's/^/  /' || echo -e "  ${YELLOW}Faucet request failed — run manually: iota client faucet${RESET}"
    fi
else
    echo -e "${YELLOW}[init-env]${RESET} IOTA CLI not found — install it first (see README)"
fi

# Clean up sed backup files
rm -f .env.bak

# Box helper: prints a line padded to exactly W visible chars between ║ and ║
W=70
line() {
    local text="$1"
    # Strip ANSI codes to measure visible length
    local visible
    visible=$(echo -e "$text" | sed 's/\x1b\[[0-9;]*m//g')
    local len=${#visible}
    local pad=$((W - len))
    if [ $pad -lt 0 ]; then pad=0; fi
    printf "${GREEN}║${RESET}%b%*s${GREEN}║${RESET}\n" "$text" "$pad" ""
}

TOP="${GREEN}╔$(printf '═%.0s' $(seq 1 $W))╗${RESET}"
MID="${GREEN}╠$(printf '═%.0s' $(seq 1 $W))╣${RESET}"
BOT="${GREEN}╚$(printf '═%.0s' $(seq 1 $W))╝${RESET}"

if [ -z "${WIZARD_MODE:-}" ]; then
    # Standalone mode — show full summary box
    echo ""
    echo -e "$TOP"
    line ""
    line "  ${WHITE}${BOLD}.env created successfully${RESET}  ${DIM}(IOTA Testnet)${RESET}"
    line ""
    echo -e "$MID"

    if [ -n "$WALLET_ADDR" ]; then
        line ""
        line "  ${BOLD}Your wallet address:${RESET}"
        line ""
        line "  ${MAGENTA}${BOLD}${WALLET_ADDR}${RESET}"
        line ""
        line "  ${BG_YELLOW}${WHITE}${BOLD} ACTION REQUIRED ${RESET}"
        line ""
        line "  After starting services, open the WordPress admin panel:"
        line "  ${CYAN}http://localhost:8090/wp-admin/${RESET}  ${DIM}(admin / admin)${RESET}"
        line ""
        line "  Navigate to ${WHITE}${BOLD}IOTA Guardian > Settings${RESET} and paste your"
        line "  wallet address in the ${WHITE}${BOLD}Recipient Address${RESET} field."
        line ""
    else
        line ""
        line "  ${YELLOW}IOTA CLI not found or no active address.${RESET}"
        line "  Install the CLI (README), then run:"
        line "    ${DIM}iota client active-address${RESET}"
        line "  and paste it in WP Admin > IOTA Guardian > Settings"
        line ""
    fi

    echo -e "$MID"
    line ""
    line "  ${BOLD}Next steps:${RESET}"
    line "    1. Deploy identity:  ${DIM}./scripts/deploy-identity-pkg.sh${RESET}"
    line "    2. Fund wallets:     ${DIM}./scripts/fund-services.sh${RESET}"
    line ""
    echo -e "$BOT"
fi
