#!/bin/bash
#
# NebiDE Real-Time Debug (RTD) Viewer
# Allows viewing NebiDE debug logs in real-time

# Default log directory
LOG_DIR="$HOME/.cache/nebide-wayland"

# Color codes for prettier output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
GRAY='\033[0;37m'
BOLD='\033[1m'
RESET='\033[0m'

print_usage() {
    echo -e "${BOLD}NebiDE Real-Time Debug Viewer${RESET}"
    echo "Usage: $(basename "$0") [OPTIONS] [LOG_FILE]"
    echo
    echo "Options:"
    echo "  -h, --help          Show this help message"
    echo "  -n, --no-color      Disable colorized output"
    echo "  -f, --follow        Keep following the log (default)"
    echo "  -l, --latest        Use the latest log file (default if no file specified)"
    echo "  -a, --all           Show the entire log file (default is last 50 lines)"
    echo "  -g, --grep PATTERN  Only show lines matching PATTERN"
    echo
    echo "Example:"
    echo "  $(basename "$0") --grep error"
    echo "  $(basename "$0") /path/to/custom/log/file"
}

# Parse command line options
USE_COLOR=true
FOLLOW=true
SHOW_ALL=false
GREP_PATTERN=""
LOG_FILE=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        -h|--help)
            print_usage
            exit 0
            ;;
        -n|--no-color)
            USE_COLOR=false
            shift
            ;;
        -f|--follow)
            FOLLOW=true
            shift
            ;;
        -l|--latest)
            LOG_FILE="$LOG_DIR/latest.log"
            shift
            ;;
        -a|--all)
            SHOW_ALL=true
            shift
            ;;
        -g|--grep)
            if [[ -z "$2" || "$2" == -* ]]; then
                echo -e "${RED}Error: Missing argument for $1${RESET}"
                exit 1
            fi
            GREP_PATTERN="$2"
            shift 2
            ;;
        -*)
            echo -e "${RED}Error: Unknown option: $1${RESET}"
            print_usage
            exit 1
            ;;
        *)
            LOG_FILE="$1"
            shift
            ;;
    esac
done

# Determine the log file to use
if [[ -z "$LOG_FILE" ]]; then
    # Check for environment variable first
    if [[ -n "$NEBIDE_DEBUG_LOG_FILE" ]]; then
        LOG_FILE="$NEBIDE_DEBUG_LOG_FILE"
    else
        # Use latest log file
        LOG_FILE="$LOG_DIR/latest.log"
    fi
fi

# Verify log file exists
if [[ ! -f "$LOG_FILE" && ! -L "$LOG_FILE" ]]; then
    echo -e "${RED}Error: Log file not found: $LOG_FILE${RESET}"
    
    # If it's not the latest.log, try looking in the log directory
    if [[ "$LOG_FILE" != "$LOG_DIR/latest.log" && -d "$LOG_DIR" ]]; then
        LATEST=$(ls -t "$LOG_DIR"/debug_* 2>/dev/null | head -n1)
        if [[ -n "$LATEST" ]]; then
            echo -e "${YELLOW}Latest log file found: $LATEST${RESET}"
            echo -e "Run: ${BOLD}$(basename "$0") \"$LATEST\"${RESET}"
        else
            echo -e "${YELLOW}No debug log files found in $LOG_DIR${RESET}"
            echo -e "Run NebiDE in debug mode first using: ${BOLD}nebide-wayland-debug${RESET}"
        fi
    else
        echo -e "${YELLOW}Debug log directory not found or empty: $LOG_DIR${RESET}"
        echo -e "Run NebiDE in debug mode first using: ${BOLD}nebide-wayland-debug${RESET}"
    fi
    exit 1
fi

echo -e "${BOLD}Viewing NebiDE debug log: ${BLUE}$LOG_FILE${RESET}"

# Build the command
CMD="cat"
if $FOLLOW; then
    CMD="tail -f"
fi

if ! $SHOW_ALL; then
    if [[ "$CMD" == "cat" ]]; then
        CMD="tail -n 50"
    else
        CMD="tail -n 50 -f"
    fi
fi

# Add color highlighting for better readability
if $USE_COLOR; then
    if [[ -n "$GREP_PATTERN" ]]; then
        $CMD "$LOG_FILE" | grep --color=always -i "$GREP_PATTERN" | \
        grep --color=always -E "$GREP_PATTERN|Error|Warning|Failed|Success|^===[^=]*===|$"
    else
        $CMD "$LOG_FILE" | \
        grep --color=always -E "Error|Warning|Failed|Success|^===[^=]*===|$" | \
        sed -E "s/Error|Failed|fatal|critical/\\${RED}&\\${RESET}/gi" | \
        sed -E "s/Warning|warn/\\${YELLOW}&\\${RESET}/gi" | \
        sed -E "s/Success|successfully/\\${GREEN}&\\${RESET}/gi" | \
        sed -E "s/^(===.*===)/\\${BOLD}\\${BLUE}&\\${RESET}/" | \
        sed -E "s/(Starting.*)/\\${BOLD}\\${GREEN}&\\${RESET}/"
    fi
else
    if [[ -n "$GREP_PATTERN" ]]; then
        $CMD "$LOG_FILE" | grep -i "$GREP_PATTERN"
    else
        $CMD "$LOG_FILE"
    fi
fi

# Exit gracefully on Ctrl+C
exit 0
