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

# SQL wrapper for block-run
# Maintains a persistent mariadb/mysql coprocess and feeds blocks to it

BINARY=""
BLOCKS=()
TMPFILE=""  # For cleanup trap

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

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

SQL wrapper for block-run. Executes SQL blocks sequentially,
maintaining state between blocks via a persistent connection.

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

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

# Syntax highlight SQL if pygmentize is available
highlight_sql() {
    if command -v pygmentize &>/dev/null; then
        pygmentize -l sql
    else
        cat
    fi
}

# Print a separator
separator() {
    echo "${DIM}─────────────────────────────────────────${RESET}"
}

main() {
    # Parse arguments
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --binary)
                BINARY="$2"
                shift 2
                ;;
            --help|-h)
                usage 0
                ;;
            --)
                shift
                BLOCKS=("$@")
                break
                ;;
            *)
                die "unexpected argument: $1"
                ;;
        esac
    done

    [[ -n "$BINARY" ]] || die "--binary is required"
    [[ ${#BLOCKS[@]} -gt 0 ]] || die "no blocks provided"

    # Determine the mariadb command to use
    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

    # Process each block
    # Since docker exec buffering makes coprocess tricky, we run each block
    # separately but build up SQL context by re-running previous blocks.
    # For efficiency, we build a cumulative SQL file.
    TMPFILE=$(mktemp)
    trap 'rm -f "$TMPFILE"' EXIT

    local block_num=0
    local cumulative_sql=""

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

        # Skip empty blocks or comment-only blocks
        local stripped
        stripped=$(echo "$block" | grep -v '^[[:space:]]*--' | grep -v '^[[:space:]]*$' || true)
        if [[ -z "$stripped" ]]; then
            # Still show the comments
            echo "${CYAN}-- Block $block_num (comments only)${RESET}"
            echo "$block" | highlight_sql
            separator
            echo
            continue
        fi

        # Show block header and highlighted SQL
        echo "${CYAN}-- Block $block_num${RESET}"
        echo "$block" | highlight_sql
        separator

        # Build cumulative SQL: all previous blocks + current block
        # Previous blocks are wrapped to suppress output (we only want current block's output)
        # For SQL, we can't easily suppress, so we just re-run everything and show only new output

        # Simple approach: run current block with all previous context
        # We add previous blocks, then a marker, then current block
        local marker="__MARKER_${block_num}__"

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

        # Run and extract only output after marker
        local full_output
        full_output=$("$db_cmd" practice < "$TMPFILE" 2>&1) || true

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

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

        # Add this block to cumulative SQL for next iteration
        cumulative_sql+="$block"$'\n'
    done
}

main "$@"
