package bash

import (
	
	

	shlex 
)

// RedirectError current position is a redirect like `echo test >[TAB]`.
type RedirectError struct{}

func ( RedirectError) () string {
	return "current position is a redirect like `echo test >[TAB]`"
}

// TODO yuck! - set by Patch which also unsets bash comp environment variables so that they don't affect further completion
// introduces state and hides what is happening but works for now
var wordbreakPrefix string = ""

func () (string, bool) {
	,  := os.LookupEnv("COMP_LINE")
	if ! {
		return "", false
	}

	,  := os.LookupEnv("COMP_POINT")
	if ! {
		return "", false
	}

	,  := strconv.Atoi()
	if  != nil || len() <  {
		return "", false
	}

	return [:], true
}

// Patch patches args if `COMP_LINE` environment variable is set.
//
// Bash passes redirects to the completion function so these need to be filtered out.
//
//	`example action >/tmp/stdout.txt --values 2>/tmp/stderr.txt fi[TAB]`
//	["example", "action", ">", "/tmp/stdout.txt", "--values", "2", ">", "/tmp/stderr.txt", "fi"]
//	["example", "action", "--values", "fi"]
func ( []string) ([]string, error) { // TODO document and fix wordbreak splitting (e.g. `:`)
	,  := CompLine()
	if ! {
		return , nil
	}

	if  == "" {
		return , nil
	}

	,  := shlex.Split()
	if  != nil {
		return nil, 
	}

	if len() > 1 {
		if  := [len()-2]; .WordbreakType.IsRedirect() {
			return append([:1], [len()-1].Value), RedirectError{}
		}
	}
	 = append([:1], .CurrentPipeline().FilterRedirects().Words().Strings()...)

	// TODO find a better solution to pass the wordbreakprefix to bash/action.go
	wordbreakPrefix = .CurrentPipeline().WordbreakPrefix()
	unsetBashCompEnv()

	return , nil
}

func unsetBashCompEnv() {
	for ,  := range []string{
		// https://www.gnu.org/software/bash/manual/html_node/Bash-Variables.html
		"COMP_CWORD",
		"COMP_LINE",
		"COMP_POINT",
		"COMP_TYPE",
		"COMP_KEY",
		"COMP_WORDBREAKS",
		"COMP_WORDS",
	} {
		os.Unsetenv()
	}
}