#!/bin/bash

# Determine scripts directory based on installation type
if [ -d "$(dirname "${BASH_SOURCE[0]}")/scripts" ]; then
    # Development/local installation
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    SCRIPTS_DIR="$SCRIPT_DIR/scripts"
else
    # Package installation
    SCRIPTS_DIR="/usr/share/rpi-power-hat/scripts"
fi

# Dynamically discover available scripts and their descriptions
discover_scripts() {
    declare -A script_descriptions
    local scripts=()
    
    # Find all executable files in scripts directory (excluding readme.md and other non-script files)
    if [ -d "$SCRIPTS_DIR" ]; then
        while IFS= read -r -d '' script_path; do
            local script_name=$(basename "$script_path")
            
            # Skip readme and other non-script files
            if [[ "$script_name" == "readme.md" ]] || [[ "$script_name" == *.sh ]] || [[ ! -x "$script_path" ]]; then
                continue
            fi
            
            # Extract description from line 3 (standardized comment line)
            local description=""
            if [ -f "$script_path" ]; then
                description=$(sed -n '3p' "$script_path" | sed 's/^#[[:space:]]*//' | sed 's/^[[:space:]]*//' | sed 's/[[:space:]]*$//')
                
                # If description is empty, provide default
                if [[ -z "$description" || "$description" =~ ^[[:space:]]*$ ]]; then
                    description="No description available"
                fi
            else
                description="Script file not found"
            fi
            
            scripts+=("$script_name")
            script_descriptions["$script_name"]="$description"
        done < <(find "$SCRIPTS_DIR" -maxdepth 1 -type f -print0 2>/dev/null | sort -z)
    fi
    
    # Export arrays for use in other functions
    AVAILABLE_SCRIPTS=("${scripts[@]}")
    declare -gA SCRIPT_DESCRIPTIONS
    for script in "${scripts[@]}"; do
        SCRIPT_DESCRIPTIONS["$script"]="${script_descriptions[$script]}"
    done
}

print_usage() {
    echo "rpi-power-hat utility suite"
    echo "Usage: rpi-power-hat <script> [arguments...]"
    echo
    echo "Available scripts:"
    
    # Dynamically discover scripts and show them with descriptions
    discover_scripts
    
    for script in "${AVAILABLE_SCRIPTS[@]}"; do
        printf "  %-15s - %s\n" "$script" "${SCRIPT_DESCRIPTIONS[$script]}"
    done
    
    echo
    echo "Examples:"
    echo "  rpi-power-hat log-current B2 10         # Log current for port B2 for 10 seconds"
    echo "  rpi-power-hat get all                   # Get power status for all ports"
    echo "  rpi-power-hat set B1 1                  # Turn on power for port B1"
    echo "  rpi-power-hat mass-storage B2 5         # Boot port B2 device as Pi 5 gadget"
    echo
    echo "For help with individual scripts, run:"
    echo "  rpi-power-hat <script> -h"
    echo "  rpi-power-hat <script> --help"
}

print_scripts() {
    echo "Available scripts:"
    discover_scripts
    
    for script in "${AVAILABLE_SCRIPTS[@]}"; do
        if [ -x "$SCRIPTS_DIR/$script" ]; then
            printf "  %-15s - %s\n" "$script" "${SCRIPT_DESCRIPTIONS[$script]}"
        else
            echo "  $script (missing or not executable)"
        fi
    done
}

# Check if no arguments provided
if [ $# -eq 0 ]; then
    print_usage
    exit 1
fi

# Handle help flags
if [ "$1" = "-h" ] || [ "$1" = "--help" ] || [ "$1" = "help" ]; then
    print_usage
    exit 0
fi

# Handle list command
if [ "$1" = "list" ] || [ "$1" = "ls" ]; then
    print_scripts
    exit 0
fi

# Get the script name and remaining arguments
SCRIPT_NAME="$1"
shift

# Dynamically discover available scripts for validation
discover_scripts

# Check if script exists in available scripts
script_found=false
for script in "${AVAILABLE_SCRIPTS[@]}"; do
    if [ "$script" = "$SCRIPT_NAME" ]; then
        script_found=true
        break
    fi
done

if [ "$script_found" = false ]; then
    echo "Error: Unknown script '$SCRIPT_NAME'" >&2
    echo
    echo "Available scripts:"
    for script in "${AVAILABLE_SCRIPTS[@]}"; do
        echo "  $script"
    done
    echo
    echo "Use 'rpi-power-hat help' for more information."
    exit 1
fi

# Build the full path to the script
SCRIPT_PATH="$SCRIPTS_DIR/$SCRIPT_NAME"

# Check if script file exists and is executable
if [ ! -f "$SCRIPT_PATH" ]; then
    echo "Error: Script file '$SCRIPT_PATH' not found" >&2
    exit 1
fi

if [ ! -x "$SCRIPT_PATH" ]; then
    echo "Error: Script file '$SCRIPT_PATH' is not executable" >&2
    echo "Try: chmod +x '$SCRIPT_PATH'" >&2
    exit 1
fi

# Execute the script with the provided arguments
exec "$SCRIPT_PATH" "$@"