#!/bin/bash
# Description: Flow-Aware TTY Command Filter
# Manages three execution flows: exit (standalone), pipe (inter-command), continue (Nushell)
# Arguments:   $@ - Command and arguments
# Returns:     0 if TTY command handled with flow=continue (continue to Nushell)
#              Exits with wrapper code for flow=exit or flow=pipe
#              1 if not a TTY command (continue to normal processing)
# Output:      Exports TTY_OUTPUT and PROVISIONING_BYPASS_DAEMON on flow=continue

# Only apply strict mode when run standalone — sourcing this file must not
# contaminate the calling shell's options (set -e would cause `DAEMON_OUTPUT=$(curl ...)`
# to exit the parent script with curl's non-zero exit code instead of falling through).
[[ "${BASH_SOURCE[0]}" == "${0}" ]] && set -euo pipefail

# Description: Check if command matches TTY pattern and manage flow
# Arguments:   $@ - Full command line
# Returns:     0 for flow=continue (don't exit), non-zero for error/not-matched
#              Exits for flow=exit or flow=pipe (calls exit)
# Output:      Executes wrapper or exports environment
filter_tty_command() {
    local cmd="$*"
    local registry_file="${PROVISIONING:-}/core/cli/tty-commands.conf"

    # Validate registry exists
    if [[ ! -f "$registry_file" ]]; then
        return 1
    fi

    # Read registry using separate file descriptor to preserve stdin
    while IFS= read -r line <&3 || [[ -n "$line" ]]; do
        # Skip comments and separators
        [[ "$line" =~ ^[[:space:]]*# ]] && continue
        [[ "$line" =~ ^[[:space:]]*═ ]] && continue
        [[ -z "$line" ]] && continue

        # Parse three-field format: "PATTERN" "WRAPPER" "FLOW_TYPE"
        if [[ "$line" =~ ^\"([^\"]+)\"[[:space:]]+\"([^\"]+)\"[[:space:]]+\"([^\"]+)\" ]]; then
            local pattern="${BASH_REMATCH[1]}"
            local wrapper="${BASH_REMATCH[2]}"
            local flow_type="${BASH_REMATCH[3]}"

            # Check if command starts with pattern (prefix match)
            # This allows commands with additional arguments like "auth integrate --provider azure"
            if [[ "$cmd" == "$pattern"* ]]; then
                local wrapper_path="${PROVISIONING}/${wrapper}"

                # Validate wrapper exists and is executable
                if [[ ! -x "$wrapper_path" ]]; then
                    echo "Warning: TTY wrapper not found or not executable: $wrapper_path" >&2
                    return 1
                fi

                # Extract arguments after pattern
                # Pattern may be multi-word (e.g., "setup platform")
                # Count pattern words and skip them from arguments
                local pattern_words=($pattern)
                local pattern_count=${#pattern_words[@]}
                local wrapper_args=()

                # Shift arguments to skip pattern words
                for ((i=pattern_count; i<$#; i++)); do
                    wrapper_args+=("${@:i+1:1}")
                done

                # ═══════════════════════════════════════════════════════════
                # FLOW TYPE: exit (standalone TTY)
                # Execute wrapper and exit immediately
                # Never reaches Nushell dispatcher
                # ═══════════════════════════════════════════════════════════
                if [[ "$flow_type" == "exit" ]]; then
                    if [[ ${#wrapper_args[@]} -gt 0 ]]; then
                        bash "$wrapper_path" "${wrapper_args[@]}"
                    else
                        bash "$wrapper_path"
                    fi
                    exit $?

                # ═══════════════════════════════════════════════════════════
                # FLOW TYPE: pipe (inter-command piping)
                # Execute wrapper, output to stdout, exit
                # Allows piping to next command in pipeline
                # ═══════════════════════════════════════════════════════════
                elif [[ "$flow_type" == "pipe" ]]; then
                    if [[ ${#wrapper_args[@]} -gt 0 ]]; then
                        bash "$wrapper_path" "${wrapper_args[@]}"
                    else
                        bash "$wrapper_path"
                    fi
                    exit $?

                # ═══════════════════════════════════════════════════════════
                # FLOW TYPE: continue (same-command Nushell processing)
                # Execute wrapper, capture output, continue to Nushell
                # Nushell receives $env.TTY_OUTPUT and original args
                # ═══════════════════════════════════════════════════════════
                elif [[ "$flow_type" == "continue" ]]; then
                    # Execute wrapper and capture output
                    local tty_output
                    if [[ ${#wrapper_args[@]} -gt 0 ]]; then
                        tty_output=$(bash "$wrapper_path" "${wrapper_args[@]}" 2>&1) || {
                            local exit_code=$?
                            echo "Error: TTY wrapper failed with code $exit_code" >&2
                            echo "$tty_output" >&2
                            exit $exit_code
                        }
                    else
                        tty_output=$(bash "$wrapper_path" 2>&1) || {
                            local exit_code=$?
                            echo "Error: TTY wrapper failed with code $exit_code" >&2
                            echo "$tty_output" >&2
                            exit $exit_code
                        }
                    fi

                    # Export output for Nushell scripts to access
                    export TTY_OUTPUT="$tty_output"
                    export PROVISIONING_BYPASS_DAEMON="true"
                    export TTY_WRAPPER_EXECUTED="true"

                    # Return 0 WITHOUT exiting - allows continuation to Nushell
                    return 0

                else
                    echo "Warning: Unknown flow type '$flow_type' for pattern '$pattern'" >&2
                    return 1
                fi
            fi
        fi
    done 3< "$registry_file"

    return 1
}

# Only run filter if called directly (not sourced)
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    filter_tty_command "$@"
fi
