#!/usr/bin/env bash
set -euo pipefail

# sql-run: Execute SQL files against Rosy's MariaDB
# Can be used as a shebang: #!/home/rosy/bin/sql-run --show-script --color=always

SCRIPT_NAME="$(basename "$0")"
SHOW_SCRIPT=false
COLOR="auto"

usage() {
    cat <<EOF
Usage: $SCRIPT_NAME [options] <script.sql>
       #!/path/to/$SCRIPT_NAME [options]  (as shebang)

Run a SQL script against the practice database.

Options:
  --show-script     Print the script (with syntax highlighting) before running
  --color=<when>    Colorize the script output: always, never, auto (default: auto)
  --help            Show this help message

Examples:
  $SCRIPT_NAME query.sql
  $SCRIPT_NAME --show-script --color=always query.sql
EOF
    exit "${1:-0}"
}

die() {
    echo "error: $*" >&2
    exit 1
}

# Check if we should use color
should_color() {
    case "$COLOR" in
        always) return 0 ;;
        never)  return 1 ;;
        auto)   [[ -t 1 ]] ;;  # color if stdout is a tty
    esac
}

# Print script with optional syntax highlighting (strips shebang if present)
print_script() {
    local script="$1"
    local content

    # Strip shebang line if present
    if head -1 "$script" | grep -q '^#!'; then
        content=$(tail -n +2 "$script")
    else
        content=$(cat "$script")
    fi

    if should_color && command -v pygmentize &>/dev/null; then
        echo "$content" | pygmentize -l sql
    else
        echo "$content"
    fi

    # Separator between script and output
    echo
    echo "---"
    echo
}

main() {
    local script=""

    # Handle Linux shebang limitation: all args after interpreter come as one string
    # e.g., "#!/path/to/sql-run --show-script --color=always" passes "--show-script --color=always" as $1
    if [[ $# -ge 1 && "$1" == *" "* && "$1" == --* ]]; then
        # shellcheck disable=SC2086
        set -- $1 "${@:2}"
    fi

    # Parse arguments
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --show-script)
                SHOW_SCRIPT=true
                shift
                ;;
            --color=*)
                COLOR="${1#--color=}"
                [[ "$COLOR" =~ ^(always|never|auto)$ ]] || die "invalid --color value: $COLOR"
                shift
                ;;
            --color)
                [[ $# -ge 2 ]] || die "--color requires a value"
                COLOR="$2"
                [[ "$COLOR" =~ ^(always|never|auto)$ ]] || die "invalid --color value: $COLOR"
                shift 2
                ;;
            --help|-h)
                usage 0
                ;;
            -*)
                die "unknown option: $1"
                ;;
            *)
                [[ -z "$script" ]] || die "multiple scripts specified"
                script="$1"
                shift
                ;;
        esac
    done

    [[ -n "$script" ]] || die "no script specified"
    [[ -f "$script" ]] || die "script not found: $script"

    # Show script if requested
    if [[ "$SHOW_SCRIPT" == true ]]; then
        print_script "$script"
    fi

    # Run the script
    # Strip shebang line if present before piping to mariadb
    if head -1 "$script" | grep -q '^#!'; then
        tail -n +2 "$script" | /home/rosy/bin/mariadb practice 2>&1 || true
    else
        /home/rosy/bin/mariadb practice < "$script" 2>&1 || true
    fi
}

main "$@"
