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

# SQL wrapper for block-run
# Uses cumulative execution since SQL doesn't maintain state between runs
#
# This wrapper is invoked BY the mariadb/mysql binary, but since those
# don't execute scripts directly, we handle it specially.
#
# Usage: mariadb this-wrapper -- block1 block2 ...

BLOCKS=()
TMPFILE=""

# Colors
CYAN=$'\e[36m'
RED=$'\e[31m'
DIM=$'\e[2m'
RESET=$'\e[0m'

usage() {
    cat <<EOF
Usage: $(basename "$0") -- <block1> [block2] ...

SQL wrapper for block-run. Executes SQL blocks sequentially,
maintaining state between blocks via cumulative execution.

This script is not meant to be called directly.
EOF
    exit "${1:-0}"
}

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

highlight_sql() {
    if command -v pygmentize &>/dev/null; then
        pygmentize -l sql
    else
        cat
    fi
}

separator() {
    echo "${DIM}─────────────────────────────────────────${RESET}"
}

is_comment_only() {
    local block="$1"
    local stripped
    stripped=$(echo "$block" | grep -v '^[[:space:]]*--' | grep -v '^[[:space:]]*$' || true)
    [[ -z "$stripped" ]]
}

main() {
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --help|-h)
                usage 0
                ;;
            --)
                shift
                BLOCKS=("$@")
                break
                ;;
            *)
                shift
                ;;
        esac
    done

    [[ ${#BLOCKS[@]} -gt 0 ]] || die "no blocks provided"

    local db_cmd
    if [[ -x "$HOME/bin/mariadb" ]]; then
        db_cmd="$HOME/bin/mariadb"
    elif command -v mariadb &>/dev/null; then
        db_cmd="mariadb"
    elif command -v mysql &>/dev/null; then
        db_cmd="mysql"
    else
        die "no mariadb/mysql command found"
    fi

    TMPFILE=$(mktemp)
    trap 'rm -f "$TMPFILE"' EXIT

    local block_num=0
    local cumulative_sql=""

    for block in "${BLOCKS[@]}"; do
        ((++block_num))

        if is_comment_only "$block"; then
            echo "${CYAN}-- Block $block_num (comments only)${RESET}"
            echo "$block" | highlight_sql
            separator
            echo
            continue
        fi

        echo "${CYAN}-- Block $block_num${RESET}"
        echo "$block" | highlight_sql
        separator

        local marker="__MARKER_${block_num}__"

        {
            echo "$cumulative_sql"
            echo "SELECT '$marker' AS '';"
            echo "$block"
        } > "$TMPFILE"

        local full_output exit_code=0
        full_output=$("$db_cmd" practice < "$TMPFILE" 2>&1) || exit_code=$?

        local output
        output=$(echo "$full_output" | sed -n "/${marker}/,\$p" | tail -n +2)

        if [[ -n "$output" ]]; then
            echo "$output"
        fi

        if [[ $exit_code -ne 0 ]]; then
            echo "${RED}(exit code: $exit_code)${RESET}"
        fi

        echo

        cumulative_sql+="$block"$'\n'
    done
}

main "$@"
