package uv

import (
	
	
	

	
)

// StyledString is a string that can be decomposed into a series of styled
// lines and cells. It is used to disassemble a rendered string with ANSI
// escape codes into a series of cells that can be used in a [Buffer].
// A StyledString supports reading [ansi.SGR] and [ansi.Hyperlink] escape
// codes.
type StyledString struct {
	// Text is the original string that was used to create the styled string.
	Text string
	// Wrap determines whether the styled string should wrap to the next line.
	Wrap bool
	// Tail is the string that will be appended to the end of the line when the
	// string is truncated i.e. when [StyledString.Wrap] is false.
	Tail string
}

var _ Drawable = (*StyledString)(nil)

// NewStyledString creates a new [StyledString] for the given method and styled
// string. The method is used to calculate the width of each line.
func ( string) *StyledString {
	 := new(StyledString)
	.Text = 
	return 
}

// String returns the text of the styled string.
//
// It implements the [fmt.Stringer] interface.
func ( *StyledString) () string {
	return .Text
}

// Lines returns the styled string decomposed into a slice of [Line]s.
func ( *StyledString) ( ansi.Method) []Line {
	return printString(nil, , 0, 0, Rectangle{}, .Text, false, "")
}

// Draw renders the styled string to the given buffer at the
// specified area.
func ( *StyledString) ( Screen,  Rectangle) {
	// Clear the area before drawing.
	for  := .Min.Y;  < .Max.Y; ++ {
		for  := .Min.X;  < .Max.X; ++ {
			.SetCell(, , nil)
		}
	}
	 := .Text
	// We need to normalize newlines "\n" to "\r\n" to emulate a raw terminal
	// output.
	 = strings.ReplaceAll(, "\r\n", "\n")
	printString(, .WidthMethod(), .Min.X, .Min.Y, , , !.Wrap, .Tail)
}

// Height returns the number of lines in the styled string. This is the number
// of lines that the styled string will occupy when rendered to the screen.
func ( *StyledString) () int {
	return strings.Count(.Text, "\n") + 1
}

// UnicodeWidth returns the cells width of the widest line in the styled string
// using the [ansi.GraphemeWidth] method.
func ( *StyledString) () int {
	,  := .widthHeight(ansi.GraphemeWidth)
	return 
}

// WcWidth returns the cells width of the widest line in the styled string
// using the [ansi.WcWidth] method.
func ( *StyledString) () int {
	,  := .widthHeight(ansi.WcWidth)
	return 
}

func ( *StyledString) ( ansi.Method) (,  int) {
	 := strings.Split(.Text, "\n")
	 = len()
	for ,  := range  {
		 = max(, .StringWidth())
	}
	return
}

// Bounds returns the minimum area that can contain the whole styled string.
func ( *StyledString) () Rectangle {
	,  := .widthHeight(ansi.GraphemeWidth)
	return Rect(0, 0, , )
}

// printString draws a string starting at the given position. If s is nil, it
// will build and return a slice of [Line]s instead (unwrapped, ignoring bounds).
func [ []byte | string](
	 Screen,
	 WidthMethod,
	,  int,
	 Rectangle,  ,
	 bool,  string,
) ( []Line) {
	 := ansi.GetParser()
	defer ansi.PutParser()

	var  Cell
	if  && len() > 0 {
		 = *NewCell(, )
	}

	// A [WidthMethod] the ansi package doesn't know about falls back to
	// wcwidth, so the segmenter below always agrees with the decoder.
	,  := ansi.DecodeSequenceWc[], ansi.WcWidth
	if  == ansi.GraphemeWidth {
		,  = ansi.DecodeSequence[], ansi.GraphemeWidth
	}

	if  == nil {
		 = []Line{}
	}

	var  Cell
	var  Style
	var  Link
	var  byte
	,  := -1, -1 // last cell written, for folding in combining marks
	for len() > 0 {
		, , ,  := (, , )
		// The decoder's ASCII fast path doesn't check for trailing combining
		// sequences, so re-decode as a full cluster when one starts here.
		// The str[1] >= 0xc0 check skips the segmenter for plain ASCII.
		if  == 1 && [0] > 0x1f && [0] < 0x7f && len() > 1 && [1] >= 0xc0 {
			if ,  := ansi.FirstGraphemeCluster(, ); len() > 1 {
				, ,  = , , len()
			}
		}
		switch {
		// Any positive width is a printable grapheme cluster. Wcwidth measures
		// a cluster per codepoint, so this is not bounded by how wide a glyph
		// can be: a ZWJ emoji sequence such as "๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ" is eight columns,
		// and capping the width here would fall through to the escape sequence
		// branch and drop the cluster from the screen.
		case  > 0:
			.Width = 
			.Content = string()
			.Style = 
			.Link = 

			if  == nil {
				// Building lines: unwrapped, no bounds
				if  >= len() {
					 = append(, Line{})
				}
				[] = append([], )
				,  = len([])-1, 
				 += 
			} else {
				// Drawing to screen: handle wrapping, truncation, and bounds
				if ! && +.Width > .Max.X && +1 < .Max.Y {
					// Wrap the string to the width of the window
					 = .Min.X
					++
				}

				 := Pos(, )
				if .In() {
					if  && .Width > 0 && +.Width > .Max.X-.Width {
						// Truncate the string and append the tail if any.
						 = 
						.Style = 
						.Link = 
						.SetCell(, , &)
						,  = , 
						 += .Width
					} else {
						// Print the cell to the screen
						.SetCell(, , &)
						,  = , 
						 += 
					}
				}
			}

			// Reset cell for next iteration
			 = Cell{}
		default:
			// Valid sequences always have a non-zero Cmd.
			// TODO: Handle cursor movement and other sequences
			switch {
			case ansi.HasCsiPrefix() && .Command() == 'm':
				// SGR - Select Graphic Rendition
				ReadStyle(.Params(), &)
			case ansi.HasOscPrefix() && .Command() == 8:
				// Hyperlinks
				ReadLink(.Data(), &)
			case ansi.Equal(, ("\n")):
				if  == nil {
					// When building lines, we need to ensure empty lines are represented.
					if  >= len() {
						 = append(, Line{})
					}
				}
				++
				// Always treat a NL as CR-LF similar to Termios ONLCR.
				fallthrough
			case ansi.Equal(, ("\r")):
				if  == nil {
					 = 0
				} else {
					 = .Min.X
				}
			case len() > 0 && [0] >= 0xc0:
				// A zero-width grapheme, i.e. a combining mark the re-decode
				// above couldn't fold because an escape sequence sits between
				// it and its base, as in "a\x1b[31m\u0301". Every escape
				// introducer is a C0 or C1 byte, so a UTF-8 lead byte here is
				// always text. The mark belongs to the cell we last wrote; the
				// accumulator below would let the next glyph clobber it.
				if  == nil {
					if  >= 0 &&  < len() &&  < len([]) {
						[][].Content += string()
					}
				} else if  >= 0 {
					if  := .CellAt(, );  != nil {
						 := *
						.Content += string()
						.SetCell(, , &)
					}
				}
			default:
				.Content += string()
			}
		}

		// Advance the state and data
		 = 
		 = [:]

		if  >= .Max.Y {
			// We've reached the bottom of the bounds, stop processing further
			// lines.
			break
		}
	}

	// Make sure to set the last cell if it's not empty.
	if !.IsZero() &&  != nil {
		.SetCell(, , &)
	}

	return 
}

// ReadStyle reads a Select Graphic Rendition (SGR) escape sequences from a
// list of parameters into pen.
func ( ansi.Params,  *Style) {
	if len() == 0 {
		* = Style{}
		return
	}

	for  := 0;  < len(); ++ {
		, ,  := .Param(, 0)
		switch  {
		case 0: // Reset
			* = Style{}
		case 1: // Bold
			.Attrs |= AttrBold
		case 2: // Dim/Faint
			.Attrs |= AttrFaint
		case 3: // Italic
			.Attrs |= AttrItalic
		case 4: // Underline
			, ,  := .Param(+1, 0)
			if  &&  { // Only accept subparameters i.e. separated by ":"
				switch  {
				case 0, 1, 2, 3, 4, 5:
					++
					switch  {
					case 0: // No Underline
						.Underline = UnderlineStyleNone
					case 1: // Single Underline
						.Underline = UnderlineStyleSingle
					case 2: // Double Underline
						.Underline = UnderlineStyleDouble
					case 3: // Curly Underline
						.Underline = UnderlineStyleCurly
					case 4: // Dotted Underline
						.Underline = UnderlineStyleDotted
					case 5: // Dashed Underline
						.Underline = UnderlineStyleDashed
					}
				}
			} else {
				// Single Underline
				.Underline = UnderlineStyleSingle
			}
		case 5: // Slow Blink
			.Attrs |= AttrBlink
		case 6: // Rapid Blink
			.Attrs |= AttrRapidBlink
		case 7: // Reverse
			.Attrs |= AttrReverse
		case 8: // Conceal
			.Attrs |= AttrConceal
		case 9: // Crossed-out/Strikethrough
			.Attrs |= AttrStrikethrough
		case 22: // Normal Intensity (not bold or faint)
			.Attrs &^= (AttrBold | AttrFaint)
		case 23: // Not italic, not Fraktur
			.Attrs &^= AttrItalic
		case 24: // Not underlined
			.Underline = UnderlineStyleNone
		case 25: // Blink off
			.Attrs &^= (AttrBlink | AttrRapidBlink)
		case 27: // Positive (not reverse)
			.Attrs &^= AttrReverse
		case 28: // Reveal
			.Attrs &^= AttrConceal
		case 29: // Not crossed out
			.Attrs &^= AttrStrikethrough
		case 30, 31, 32, 33, 34, 35, 36, 37: // Set foreground
			.Fg = ansi.Black + ansi.BasicColor(-30) //nolint:gosec
		case 38: // Set foreground 256 or truecolor
			var  color.Color
			 := ansi.ReadStyleColor([:], &)
			if  > 0 {
				.Fg = 
				 +=  - 1
			}
		case 39: // Default foreground
			.Fg = nil
		case 40, 41, 42, 43, 44, 45, 46, 47: // Set background
			.Bg = ansi.Black + ansi.BasicColor(-40) //nolint:gosec
		case 48: // Set background 256 or truecolor
			var  color.Color
			 := ansi.ReadStyleColor([:], &)
			if  > 0 {
				.Bg = 
				 +=  - 1
			}
		case 49: // Default Background
			.Bg = nil
		case 58: // Set underline color
			var  color.Color
			 := ansi.ReadStyleColor([:], &)
			if  > 0 {
				.UnderlineColor = 
				 +=  - 1
			}
		case 59: // Default underline color
			.UnderlineColor = nil
		case 90, 91, 92, 93, 94, 95, 96, 97: // Set bright foreground
			.Fg = ansi.BrightBlack + ansi.BasicColor(-90) //nolint:gosec
		case 100, 101, 102, 103, 104, 105, 106, 107: // Set bright background
			.Bg = ansi.BrightBlack + ansi.BasicColor(-100) //nolint:gosec
		}
	}
}

// ReadLink reads a hyperlink escape sequence from a data buffer into link.
func ( []byte,  *Link) {
	 := bytes.Split(, []byte{';'})
	if len() != 3 {
		return
	}
	.Params = string([1])
	.URL = string([2])
}