package cli

import (
	"bytes"
	"os"
	"strings"

	"git.eeqj.de/sneak/secret/internal/secret"
)

// ExecuteCommandInProcess executes a CLI command in-process for testing
func ExecuteCommandInProcess(args []string, stdin string, env map[string]string) (string, error) {
	secret.Debug("ExecuteCommandInProcess called", "args", args)

	// Save current environment
	savedEnv := make(map[string]string)
	for k := range env {
		savedEnv[k] = os.Getenv(k)
	}

	// Set test environment
	for k, v := range env {
		os.Setenv(k, v)
	}

	// Create root command
	rootCmd := newRootCmd()

	// Capture output
	var buf bytes.Buffer
	rootCmd.SetOut(&buf)
	rootCmd.SetErr(&buf)

	// Set stdin if provided
	if stdin != "" {
		rootCmd.SetIn(strings.NewReader(stdin))
	}

	// Set args
	rootCmd.SetArgs(args)

	// Execute command
	err := rootCmd.Execute()

	output := buf.String()
	secret.Debug("Command execution completed", "error", err, "outputLength", len(output), "output", output)

	// Add debug info for troubleshooting
	if len(output) == 0 && err == nil {
		secret.Debug("Warning: Command executed successfully but produced no output", "args", args)
	}

	// Restore environment
	for k, v := range savedEnv {
		if v == "" {
			os.Unsetenv(k)
		} else {
			os.Setenv(k, v)
		}
	}

	return output, err
}