#!/bin/bash
#
# Debug version of setup-automation.sh to identify non-interactive mode failures
#

set -e

# Enable verbose debugging
set -x

echo "DEBUG: Script started at $(date)"
echo "DEBUG: Arguments received: $*"
echo "DEBUG: Total argument count: $#"

# Test the exact command that's failing
echo "DEBUG: Testing setup-automation.sh with --non-interactive flag"
echo "DEBUG: NON_INTERACTIVE environment variable before: ${NON_INTERACTIVE:-unset}"

# Simulate the command line parsing logic from setup-automation.sh
echo "DEBUG: Parsing command line arguments..."

command="${1:-setup}"
echo "DEBUG: Initial command: $command"

# Parse options (mimicking the main script logic)
while [[ $# -gt 0 ]]; do
    echo "DEBUG: Processing argument: $1"
    case "$1" in
        --non-interactive)
            export NON_INTERACTIVE="true"
            echo "DEBUG: NON_INTERACTIVE flag set to: $NON_INTERACTIVE"
            shift
            ;;
        --force-rebuild)
            export FORCE_REBUILD="true"
            echo "DEBUG: FORCE_REBUILD flag set to: $FORCE_REBUILD"
            shift
            ;;
        --debug)
            export CONFIG_DEBUG="true"
            echo "DEBUG: CONFIG_DEBUG flag set to: $CONFIG_DEBUG"
            shift
            ;;
        -h|--help)
            echo "DEBUG: Help requested"
            exit 0
            ;;
        -*)
            echo "DEBUG: Unknown option: $1"
            exit 1
            ;;
        *)
            echo "DEBUG: Breaking on non-option argument: $1"
            break
            ;;
    esac
done

# Update command after option parsing (this might be the bug)
command="${1:-setup}"
echo "DEBUG: Final command after parsing: $command"
echo "DEBUG: Remaining arguments: $*"

echo "DEBUG: NON_INTERACTIVE environment variable after parsing: ${NON_INTERACTIVE:-unset}"

# Test the specific condition that shows the interactive banner
echo "DEBUG: Testing banner condition..."
if [[ "$NON_INTERACTIVE" != "true" ]]; then
    echo "DEBUG: BANNER WOULD BE SHOWN - this is the problem!"
    echo "DEBUG: NON_INTERACTIVE value: '$NON_INTERACTIVE'"
    echo "DEBUG: Comparison result: '$NON_INTERACTIVE' != 'true'"
else
    echo "DEBUG: Banner would be suppressed (correct behavior)"
fi

# Test what happens when we call the actual script
echo "DEBUG: Now calling actual setup-automation.sh with timeout..."
echo "DEBUG: Command will be: timeout 10s bash scripts/vm/setup-automation.sh setup --non-interactive"

# Add timeout to prevent hanging
if timeout 10s bash scripts/vm/setup-automation.sh setup --non-interactive 2>&1; then
    echo "DEBUG: Script completed successfully"
else
    exit_code=$?
    echo "DEBUG: Script failed with exit code: $exit_code"
    if [[ $exit_code -eq 124 ]]; then
        echo "DEBUG: Script timed out (likely hanging on interactive prompt)"
    fi
fi

echo "DEBUG: Debug script completed at $(date)"