package cli

import (
	"regexp"
	"strings"
	"unicode"
)

var (
	claudeTerminalOSCRegex     = regexp.MustCompile(`\x1b\][^\x07]*(?:\x07|\x1b\\)`)
	claudeTerminalCSIRegex     = regexp.MustCompile(`\x1b\[[?0-9;]*[ -/]*[@-~]`)
	claudeTerminalControlRegex = regexp.MustCompile(`[\x00-\x08\x0b\x0c\x0e-\x1f]`)
)

func cleanClaudeTerminalOutput(text string) string {
	text = claudeTerminalOSCRegex.ReplaceAllString(text, "")
	text = claudeTerminalCSIRegex.ReplaceAllString(text, "")
	text = strings.ReplaceAll(text, "\r\n", "\n")
	text = strings.ReplaceAll(text, "\r", "\n")
	text = strings.ReplaceAll(text, "\u00a0", " ")
	return claudeTerminalControlRegex.ReplaceAllString(text, "")
}

func isClaudePromptEchoMessage(message, prompt string) bool {
	prompt = normalizeClaudePromptEchoText(prompt)
	if prompt == "" {
		return false
	}
	lines := strings.Split(message, "\n")
	checked := 0
	for _, line := range lines {
		rawLine := strings.TrimSpace(line)
		if strings.Contains(rawLine, "_") && len(rawLine) >= 12 {
			return false
		}
		normalizedLine := normalizeClaudePromptEchoText(rawLine)
		if normalizedLine == "" {
			continue
		}
		if len(normalizedLine) >= 16 {
			return false
		}
		if !strings.Contains(prompt, normalizedLine) {
			return false
		}
		checked++
	}
	return checked > 0
}

func normalizeClaudePromptEchoText(s string) string {
	var b strings.Builder
	for _, r := range strings.ToLower(s) {
		if unicode.IsLetter(r) || unicode.IsDigit(r) {
			b.WriteRune(r)
		}
	}
	return b.String()
}

func fallbackClaudeVisibleMessage(text, prompt string) string {
	lines := strings.Split(text, "\n")
	var block []string
	var lastBlock []string
	for _, raw := range lines {
		line := strings.TrimSpace(raw)
		if line == "" {
			if len(block) > 0 {
				block = append(block, "")
			}
			continue
		}
		if !isClaudeMessageCandidate(line, prompt) {
			if len(block) > 0 {
				lastBlock = append(lastBlock[:0], trimTrailingEmptyLines(block)...)
				block = nil
			}
			continue
		}
		block = append(block, line)
	}
	if len(block) == 0 {
		block = lastBlock
	}
	return strings.Join(trimTrailingEmptyLines(block), "\n")
}

func trimTrailingEmptyLines(lines []string) []string {
	for len(lines) > 0 && lines[len(lines)-1] == "" {
		lines = lines[:len(lines)-1]
	}
	return lines
}

func isClaudeMessageCandidate(line, prompt string) bool {
	if line == "" || isClaudeTUIBoundaryLine(line) {
		return false
	}
	if prompt != "" && strings.Contains(line, prompt) {
		return false
	}
	if isNumericOnlyLine(line) {
		return false
	}
	lower := strings.ToLower(line)
	switch {
	case strings.HasPrefix(lower, "claude code"):
		return false
	case strings.HasPrefix(lower, "welcome to claude"):
		return false
	case strings.HasPrefix(lower, "cwd:"):
		return false
	case strings.HasPrefix(lower, "model:"):
		return false
	case strings.HasPrefix(lower, "session:"):
		return false
	case strings.HasPrefix(lower, "permissions:"):
		return false
	case strings.HasPrefix(lower, "warning:"):
		return false
	case strings.HasPrefix(lower, "yes, i accept"):
		return false
	case strings.HasPrefix(lower, "no, exit"):
		return false
	}
	return true
}

func isClaudeTransientStatusLine(line string) bool {
	lower := strings.ToLower(strings.TrimSpace(line))
	for _, word := range []string{
		"cogitating",
		"crunched",
		"dallying",
		"dilly",
		"pondering",
		"processing",
		"thinking",
		"thundering",
		"undulating",
		"working",
	} {
		if strings.Contains(lower, word) {
			return true
		}
	}
	return false
}

func isNumericOnlyLine(line string) bool {
	line = strings.TrimSpace(line)
	if line == "" {
		return false
	}
	for _, r := range line {
		if !unicode.IsDigit(r) {
			return false
		}
	}
	return true
}
