#!/bin/bash

# Backup TUI Launcher Script
# Provides consistent access to the backup TUI application

set -e

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TUI_DIR="$SCRIPT_DIR/tui"
BINARY_NAME="backup-tui"
BINARY_PATH="$TUI_DIR/$BINARY_NAME"

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Print colored output
print_color() {
    local color="$1"
    local message="$2"
    case "$color" in
        "green")  printf "${GREEN}%s${NC}\n" "$message" ;;
        "yellow") printf "${YELLOW}%s${NC}\n" "$message" ;;
        "red")    printf "${RED}%s${NC}\n" "$message" ;;
        *)        printf "%s\n" "$message" ;;
    esac
}

# Check if binary exists
if [[ ! -f "$BINARY_PATH" ]]; then
    print_color "yellow" "🔨 Binary not found. Building $BINARY_NAME..."

    # Try to build using Makefile first, then fallback to build script
    if [[ -f "$TUI_DIR/Makefile" ]] && command -v make &> /dev/null; then
        print_color "yellow" "📋 Using Makefile to build..."
        cd "$TUI_DIR" && make build
    elif [[ -f "$TUI_DIR/build.sh" ]]; then
        print_color "yellow" "🔧 Using build script..."
        cd "$TUI_DIR" && ./build.sh
    else
        print_color "yellow" "🔧 Building directly with go..."
        cd "$TUI_DIR" && go build -o "$BINARY_NAME" main.go
    fi

    if [[ ! -f "$BINARY_PATH" ]]; then
        print_color "red" "❌ Failed to build $BINARY_NAME"
        exit 1
    fi

    print_color "green" "✅ Build completed successfully"
fi

# Make sure binary is executable
chmod +x "$BINARY_PATH"

# Launch the TUI
print_color "green" "🚀 Launching Backup TUI..."
exec "$BINARY_PATH" "$@"
