#!/usr/bin/env bash
# Unified development harness for painted
# Usage: ./dev <command> [options]
#
# Commands are discovered from scripts/*.sh
# Add a new command by creating scripts/<name>.sh with:
#   # DESC: One-line description
set -euo pipefail

cd "$(dirname "$0")"

SCRIPTS_DIR="scripts"

# Colors (disabled if not a terminal)
if [ -t 1 ]; then
    BOLD=$'\033[1m'
    NC=$'\033[0m'
else
    BOLD='' NC=''
fi

# Discover available commands (exclude lib/, _*.sh)
discover_commands() {
    for script in "$SCRIPTS_DIR"/*.sh; do
        [ -f "$script" ] || continue
        local name=$(basename "$script" .sh)
        [[ "$name" == _* ]] && continue
        echo "$name"
    done
}

# Get description from script's DESC comment
get_description() {
    local script="$SCRIPTS_DIR/$1.sh"
    grep -m1 "^# DESC:" "$script" 2>/dev/null | sed 's/^# DESC: //' || echo ""
}

usage() {
    echo -e "${BOLD}painted development harness${NC}"
    echo ""
    echo -e "${BOLD}Usage:${NC} ./dev <command> [options]"
    echo ""
    echo -e "${BOLD}Commands:${NC}"
    for cmd in $(discover_commands | sort); do
        local desc=$(get_description "$cmd")
        printf "  %-14s %s\n" "$cmd" "$desc"
    done
    echo ""
    echo "Run './dev <command> --help' for command-specific options."
}

# Main dispatch
cmd="${1:-help}"
shift || true

case "$cmd" in
    help|--help|-h)
        usage
        ;;
    *)
        script="$SCRIPTS_DIR/$cmd.sh"
        if [ -f "$script" ]; then
            exec bash "$script" "$@"
        else
            echo "Unknown command: $cmd"
            echo "Run './dev help' for usage"
            exit 1
        fi
        ;;
esac
