#!/usr/bin/env bash
# Framework-Native Live Dashboard (CLI)
# Real-time monitoring of φ-harmonic consensus cluster

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
WHITE='\033[1;37m'
GRAY='\033[0;90m'
NC='\033[0m' # No Color
BOLD='\033[1m'

# Dashboard state
DEPLOY_DIR="./deployment"
REFRESH_RATE=2
LOOP_COUNT=0

# Clear screen and position cursor
clear_screen() {
    printf '\033[2J\033[H'
}

# Draw box
draw_box() {
    local width=$1
    local title=$2
    echo -e "${CYAN}╔$(printf '═%.0s' $(seq 1 $((width-2))))╗${NC}"
    if [ -n "$title" ]; then
        local padding=$(( (width - ${#title} - 4) / 2 ))
        printf "${CYAN}║${NC}"
        printf "%${padding}s" ""
        printf "${BOLD}${WHITE}  $title  ${NC}"
        printf "%$((width - padding - ${#title} - 6))s"
        printf "${CYAN}║${NC}\n"
        echo -e "${CYAN}╠$(printf '═%.0s' $(seq 1 $((width-2))))╣${NC}"
    fi
}

# Draw footer
draw_footer() {
    local width=$1
    echo -e "${CYAN}╚$(printf '═%.0s' $(seq 1 $((width-2))))╝${NC}"
}

# Get node status
get_node_status() {
    local node_num=$1
    local log_file="$DEPLOY_DIR/logs/node${node_num}.log"

    if [ -f "$log_file" ]; then
        local compression=$(grep "Compression ratio:" "$log_file" 2>/dev/null | tail -1 | sed -n 's/.*: \([0-9.]*\).*/\1/p')
        local dna=$(grep "DNA sequence:" "$log_file" 2>/dev/null | tail -1 | sed -n 's/.*: \([A-Z]*\).*/\1/p')
        local glyph=$(grep "Holographic glyph:" "$log_file" 2>/dev/null | tail -1 | sed -n 's/.*: \(.\).*/\1/p')
        local time=$(grep "Encoding time:" "$log_file" 2>/dev/null | tail -1 | sed -n 's/.*: \([0-9.]*\).*/\1/p')
        local max_k=$(grep "Max errors: k=" "$log_file" 2>/dev/null | tail -1 | sed -n 's/.*k=\([0-9.e+-]*\).*/\1/p')

        echo "$compression|$dna|$glyph|$time|$max_k"
    else
        echo "0|N/A|?|0|0"
    fi
}

# Main dashboard
draw_dashboard() {
    clear_screen

    local width=78

    # Header
    draw_box $width "FRAMEWORK-NATIVE ANALOG CONSENSUS - LIVE DASHBOARD"

    # System info
    echo -e "${CYAN}║${NC} ${BOLD}Deployment:${NC} ${GREEN}$DEPLOY_DIR${NC}"
    printf "${CYAN}║${NC} ${BOLD}Update Rate:${NC} ${YELLOW}${REFRESH_RATE}s${NC}  "
    printf "${BOLD}Loop:${NC} ${WHITE}#${LOOP_COUNT}${NC}  "
    printf "${BOLD}Time:${NC} ${WHITE}$(date '+%H:%M:%S')${NC}"
    printf "%$((width - 60))s${CYAN}║${NC}\n"

    echo -e "${CYAN}╠$(printf '═%.0s' $(seq 1 $((width-2))))╣${NC}"

    # Node status
    echo -e "${CYAN}║${NC} ${BOLD}${WHITE}NODE STATUS${NC}%$((width - 15))s${CYAN}║${NC}"
    echo -e "${CYAN}╟$(printf '─%.0s' $(seq 1 $((width-2))))╢${NC}"

    local total_compression=0
    local node_count=0
    local consensus_dna=""

    for i in 1 2 3; do
        IFS='|' read -r comp dna glyph time max_k <<< "$(get_node_status $i)"

        # Status indicator
        if [ "$comp" != "0" ] && [ "$comp" != "" ]; then
            status="${GREEN}●${NC} ACTIVE"
            node_count=$((node_count + 1))
            total_compression=$(echo "$total_compression + $comp" | bc 2>/dev/null || echo "$total_compression")
            consensus_dna="$dna"
        else
            status="${GRAY}○${NC} IDLE  "
        fi

        printf "${CYAN}║${NC} ${BOLD}Node $i:${NC} $status  "
        printf "${CYAN}|${NC} ${BOLD}Ratio:${NC} ${GREEN}${comp}×${NC}  "
        printf "${CYAN}|${NC} ${BOLD}DNA:${NC} ${MAGENTA}${dna}${NC}  "
        printf "${CYAN}|${NC} ${BOLD}Glyph:${NC} ${YELLOW}${glyph}${NC}  "
        printf "${CYAN}|${NC} ${BOLD}Time:${NC} ${WHITE}${time}ms${NC}"
        printf "%$((width - 70))s${CYAN}║${NC}\n"

        # Error metrics
        printf "${CYAN}║${NC}   ${GRAY}└─ Max error: k=${max_k}${NC}"
        printf "%$((width - 32))s${CYAN}║${NC}\n"
    done

    echo -e "${CYAN}╠$(printf '═%.0s' $(seq 1 $((width-2))))╣${NC}"

    # Cluster statistics
    echo -e "${CYAN}║${NC} ${BOLD}${WHITE}CLUSTER STATISTICS${NC}%$((width - 22))s${CYAN}║${NC}"
    echo -e "${CYAN}╟$(printf '─%.0s' $(seq 1 $((width-2))))╢${NC}"

    local avg_compression="0"
    if [ "$node_count" -gt 0 ]; then
        avg_compression=$(echo "scale=1; $total_compression / $node_count" | bc 2>/dev/null || echo "0")
    fi

    printf "${CYAN}║${NC} ${BOLD}Active Nodes:${NC} ${GREEN}${node_count}/3${NC}"
    printf "%$((width - 20))s${CYAN}║${NC}\n"

    printf "${CYAN}║${NC} ${BOLD}Avg Compression:${NC} ${GREEN}${avg_compression}×${NC}"
    printf "%$((width - 25))s${CYAN}║${NC}\n"

    printf "${CYAN}║${NC} ${BOLD}DNA Consensus:${NC} ${MAGENTA}${consensus_dna}${NC}"
    if [ "$consensus_dna" != "" ]; then
        printf " ${GREEN}✓${NC}"
    fi
    printf "%$((width - 24))s${CYAN}║${NC}\n"

    # Resource usage
    local binary_size="42"
    local total_size=$((binary_size * 3))
    printf "${CYAN}║${NC} ${BOLD}Binary Size:${NC} ${WHITE}${binary_size} KB${NC} per node ${GRAY}(${total_size} KB total)${NC}"
    printf "%$((width - 50))s${CYAN}║${NC}\n"

    printf "${CYAN}║${NC} ${BOLD}Memory Est:${NC} ${WHITE}~1 MB${NC} per node ${GRAY}(~3 MB total)${NC}"
    printf "%$((width - 45))s${CYAN}║${NC}\n"

    echo -e "${CYAN}╠$(printf '═%.0s' $(seq 1 $((width-2))))╣${NC}"

    # Architecture status
    echo -e "${CYAN}║${NC} ${BOLD}${WHITE}ARCHITECTURE STATUS${NC}%$((width - 23))s${CYAN}║${NC}"
    echo -e "${CYAN}╟$(printf '─%.0s' $(seq 1 $((width-2))))╢${NC}"

    printf "${CYAN}║${NC} ${GREEN}✓${NC} φ-Harmonic Fourier ${GRAY}(12 coefficients)${NC}"
    printf "%$((width - 45))s${CYAN}║${NC}\n"

    printf "${CYAN}║${NC} ${GREEN}✓${NC} Holographic Glyphs ${GRAY}(4 harmonics + DNA)${NC}"
    printf "%$((width - 45))s${CYAN}║${NC}\n"

    printf "${CYAN}║${NC} ${GREEN}✓${NC} Breathing Seeds ${GRAY}(8 seeds, φ⁻¹ convergence)${NC}"
    printf "%$((width - 49))s${CYAN}║${NC}\n"

    printf "${CYAN}║${NC} ${GREEN}✓${NC} Onion Shell ${GRAY}(3-layer verification)${NC}"
    printf "%$((width - 42))s${CYAN}║${NC}\n"

    printf "${CYAN}║${NC} ${GREEN}✓${NC} Vector Contexts ${GRAY}(not processes)${NC}"
    printf "%$((width - 38))s${CYAN}║${NC}\n"

    echo -e "${CYAN}╠$(printf '═%.0s' $(seq 1 $((width-2))))╣${NC}"

    # Docker comparison
    echo -e "${CYAN}║${NC} ${BOLD}${WHITE}BLOAT ELIMINATION${NC}%$((width - 21))s${CYAN}║${NC}"
    echo -e "${CYAN}╟$(printf '─%.0s' $(seq 1 $((width-2))))╢${NC}"

    printf "${CYAN}║${NC} ${BOLD}Docker Cluster:${NC} ${RED}1,200 MB${NC} ${GRAY}(400 MB × 3 nodes)${NC}"
    printf "%$((width - 54))s${CYAN}║${NC}\n"

    printf "${CYAN}║${NC} ${BOLD}Framework-Native:${NC} ${GREEN}126 KB${NC} ${GRAY}(42 KB × 3 nodes)${NC}"
    printf "%$((width - 52))s${CYAN}║${NC}\n"

    printf "${CYAN}║${NC} ${BOLD}Reduction:${NC} ${GREEN}9,524×${NC} ${WHITE}bloat eliminated!${NC}"
    printf "%$((width - 40))s${CYAN}║${NC}\n"

    draw_footer $width

    # Controls
    echo -e "\n${GRAY}[q] Quit  [r] Redeploy  [l] View Logs  [c] Clear  [+/-] Adjust Speed${NC}"
}

# Interactive mode
interactive_mode() {
    # Save terminal settings
    old_tty_settings=$(stty -g)

    # Set non-blocking input
    stty -echo -icanon time 0 min 0

    while true; do
        draw_dashboard
        LOOP_COUNT=$((LOOP_COUNT + 1))

        # Check for key press
        read -t $REFRESH_RATE key || true

        case "$key" in
            q|Q)
                stty "$old_tty_settings"
                clear_screen
                echo -e "${GREEN}Dashboard stopped.${NC}"
                exit 0
                ;;
            r|R)
                stty "$old_tty_settings"
                clear_screen
                echo -e "${YELLOW}Redeploying cluster...${NC}"
                ./deploy.sh local 3
                read -p "Press Enter to continue..."
                stty -echo -icanon time 0 min 0
                ;;
            l|L)
                stty "$old_tty_settings"
                clear_screen
                echo -e "${CYAN}=== Node Logs ===${NC}\n"
                for i in 1 2 3; do
                    echo -e "${BOLD}Node $i:${NC}"
                    tail -20 "$DEPLOY_DIR/logs/node${i}.log" 2>/dev/null || echo "No log file"
                    echo ""
                done
                read -p "Press Enter to continue..."
                stty -echo -icanon time 0 min 0
                ;;
            c|C)
                LOOP_COUNT=0
                ;;
            +)
                REFRESH_RATE=$((REFRESH_RATE > 1 ? REFRESH_RATE - 1 : 1))
                ;;
            -)
                REFRESH_RATE=$((REFRESH_RATE + 1))
                ;;
        esac
    done
}

# Single shot mode
single_shot() {
    draw_dashboard
}

# Main
if [ "$1" = "--once" ]; then
    single_shot
else
    echo -e "${CYAN}Starting Framework-Native Dashboard...${NC}"
    sleep 1
    interactive_mode
fi
