#!/bin/bash
# Lethean Testnet Health Check
# Run: bash health.sh

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

check() {
    local name="$1"
    local url="$2"
    local code
    code=$(curl -sf -o /dev/null -w "%{http_code}" "$url" 2>/dev/null)
    if [ "$code" = "200" ] || [ "$code" = "307" ] || [ "$code" = "404" ]; then
        printf "  ${GREEN}%-16s${NC} %s ${YELLOW}(HTTP %s)${NC}\n" "$name" "$url" "$code"
    else
        printf "  ${RED}%-16s${NC} %s ${RED}(DOWN)${NC}\n" "$name" "$url"
    fi
}

rpc() {
    local name="$1"
    local url="$2"
    local method="$3"
    local result
    result=$(curl -sf "$url" -d "{\"jsonrpc\":\"2.0\",\"id\":\"0\",\"method\":\"$method\"}" -H 'Content-Type: application/json' 2>/dev/null)
    if [ -n "$result" ]; then
        printf "  ${GREEN}%-16s${NC} %s\n" "$name" "$(echo "$result" | python3 -c "
import sys,json
d=json.load(sys.stdin).get('result',{})
if 'height' in d:
    hf = d.get('is_hardfok_active',[])
    active = sum(1 for h in hf if h)
    print(f'height={d[\"height\"]}, HF0-{active-1} active, status={d.get(\"status\",\"?\")}')
elif 'balance' in d:
    print(f'{d[\"balance\"]/1e12:.4f} LTHN ({d[\"unlocked_balance\"]/1e12:.4f} unlocked)')
else:
    print(json.dumps(d)[:80])
" 2>/dev/null)"
    else
        printf "  ${RED}%-16s${NC} %s ${RED}(DOWN)${NC}\n" "$name" "$url"
    fi
}

echo ""
echo "  Lethean Testnet Health Check"
echo "  $(date)"
echo "  ---"
rpc "Daemon" "http://localhost:${DAEMON_RPC_PORT:-46941}/json_rpc" "getinfo"
rpc "Wallet" "http://localhost:${WALLET_RPC_PORT:-46944}/json_rpc" "getbalance"
check "Explorer" "http://localhost:${EXPLORER_PORT:-3335}/"
check "Trade API" "http://localhost:${TRADE_API_PORT:-3336}/"
check "Trade Web" "http://localhost:${TRADE_FRONTEND_PORT:-3338}/"
check "Pool API" "http://localhost:${POOL_API_PORT:-2117}/stats"
check "LNS" "http://localhost:${LNS_HTTP_PORT:-5553}/"
check "Docs" "http://localhost:${DOCS_PORT:-8099}/"
echo ""
