package cli

import (
	"strings"
)

type terminalPassthroughOutputFilter struct {
	prompt          string
	promptBuf       strings.Builder
	promptDone      bool
	suppressLineEnd bool
	emitted         bool
}

func newTerminalPassthroughOutputFilter(prompt string) *terminalPassthroughOutputFilter {
	return &terminalPassthroughOutputFilter{prompt: strings.TrimRight(prompt, "\r\n")}
}

func (f *terminalPassthroughOutputFilter) Filter(chunk string) string {
	if chunk == "" {
		return ""
	}
	if !f.promptDone && f.prompt != "" {
		f.promptBuf.WriteString(chunk)
		raw := f.promptBuf.String()
		if strings.HasPrefix(f.prompt, raw) {
			if raw == f.prompt {
				f.promptDone = true
				f.suppressLineEnd = true
				f.promptBuf.Reset()
			}
			return ""
		}
		if strings.HasPrefix(raw, f.prompt) {
			rest := raw[len(f.prompt):]
			if rest == "" {
				f.promptDone = true
				f.suppressLineEnd = true
				f.promptBuf.Reset()
				return ""
			}
			if strings.HasPrefix(rest, "\r") || strings.HasPrefix(rest, "\n") {
				f.promptDone = true
				f.promptBuf.Reset()
				return f.emit(strings.TrimLeft(rest, "\r\n"))
			}
		}
		f.promptDone = true
		f.promptBuf.Reset()
		return f.emit(raw)
	}
	if f.suppressLineEnd {
		f.suppressLineEnd = false
		chunk = strings.TrimLeft(chunk, "\r\n")
		if chunk == "" {
			return ""
		}
	}
	return f.emit(chunk)
}

func (f *terminalPassthroughOutputFilter) Flush() string {
	return ""
}

func (f *terminalPassthroughOutputFilter) HasOutput() bool {
	return f.emitted
}

func (f *terminalPassthroughOutputFilter) CompletionMessage() string {
	return ""
}

func (f *terminalPassthroughOutputFilter) emit(chunk string) string {
	if chunk != "" {
		f.emitted = true
	}
	return chunk
}
