#!/usr/bin/env bash
# Universal TTY Command Dispatcher
# Routes TTY commands to Nu functions with proper output handling
# Usage: tty-dispatch.sh <function-name> [flow-type] [args...]

set -euo pipefail

FUNCTION_NAME="${1:-}"
FLOW_TYPE="${2:-exit}"
shift 2 || true

if [[ -z "$FUNCTION_NAME" ]]; then
    echo "Error: Function name required" >&2
    exit 1
fi

# Find nu binary
NU=$(type -P nu 2>/dev/null || echo "")
if [[ -z "$NU" ]]; then
    echo "Error: nu not found in PATH" >&2
    exit 1
fi

# Get provisioning root
PROVISIONING="${PROVISIONING:-/usr/local/provisioning}"

# Map function name to Nu function with proper naming conventions
case "$FUNCTION_NAME" in
    "setup-wizard")
        NU_FUNCTION="run-setup-wizard-interactive"
        ;;
    "login"|"auth-login")
        NU_FUNCTION="login-interactive"
        ;;
    "mfa"|"mfa-enroll"|"auth-mfa-enroll")
        NU_FUNCTION="mfa-enroll-interactive"
        ;;
    "auth-get-key"|"get-key")
        NU_FUNCTION="get-api-key-interactive"
        ;;
    "auth-integrate"|"credential-input")
        NU_FUNCTION="get-provider-credentials-interactive"
        ;;
    "secret-configure")
        NU_FUNCTION="get-secret-config-interactive"
        ;;
    *)
        echo "Error: Unknown function: $FUNCTION_NAME" >&2
        exit 1
        ;;
esac

# Execute Nu function with proper output handling
case "$FLOW_TYPE" in
    "exit")
        # Standalone: Execute and exit immediately
        $NU -n -c "
            use '$PROVISIONING/core/nulib/lib_provisioning/plugins/auth.nu' *
            use '$PROVISIONING/core/nulib/lib_provisioning/setup/wizard.nu' *
            $NU_FUNCTION
        "
        exit $?
        ;;
    "pipe")
        # Pipeline: Output to stdout for piping
        $NU -n -c "
            use '$PROVISIONING/core/nulib/lib_provisioning/plugins/auth.nu' *
            use '$PROVISIONING/core/nulib/lib_provisioning/setup/wizard.nu' *
            $NU_FUNCTION
        "
        exit $?
        ;;
    "continue")
        # Continue to Nushell: Output as JSON for $TTY_OUTPUT
        $NU -n -c "
            use '$PROVISIONING/core/nulib/lib_provisioning/plugins/auth.nu' *
            use '$PROVISIONING/core/nulib/lib_provisioning/setup/wizard.nu' *
            $NU_FUNCTION | to json
        "
        exit $?
        ;;
    *)
        echo "Error: Unknown flow type: $FLOW_TYPE" >&2
        exit 1
        ;;
esac
