package godump

import (
	
	
	
	
	
	
	
)

// Diff prints a diff between two values to stdout.
// @group Diff
//
// Example: print diff
//
//	a := map[string]int{"a": 1}
//	b := map[string]int{"a": 2}
//	godump.Diff(a, b)
//	// <#diff // path:line
//	// - #map[string]int {
//	// -   a => 1 #int
//	// - }
//	// + #map[string]int {
//	// +   a => 2 #int
//	// + }
func (,  any) {
	defaultDumper.Diff(, )
}

// Diff prints a diff between two values to the configured writer.
// @group Diff
//
// Example: print diff with a custom dumper
//
//	d := godump.NewDumper()
//	a := map[string]int{"a": 1}
//	b := map[string]int{"a": 2}
//	d.Diff(a, b)
//	// <#diff // path:line
//	// - #map[string]int {
//	// -   a => 1 #int
//	// - }
//	// + #map[string]int {
//	// +   a => 2 #int
//	// + }
func ( *Dumper) (,  any) {
	fmt.Fprint(.writer, .DiffStr(, ))
}

// DiffStr returns a string diff between two values.
// @group Diff
//
// Example: diff string
//
//	a := map[string]int{"a": 1}
//	b := map[string]int{"a": 2}
//	out := godump.DiffStr(a, b)
//	_ = out
//	// <#diff // path:line
//	// - #map[string]int {
//	// -   a => 1 #int
//	// - }
//	// + #map[string]int {
//	// +   a => 2 #int
//	// + }
func (,  any) string {
	return defaultDumper.DiffStr(, )
}

// DiffStr returns a string diff between two values.
// @group Diff
//
// Example: diff string with a custom dumper
//
//	d := godump.NewDumper()
//	a := map[string]int{"a": 1}
//	b := map[string]int{"a": 2}
//	out := d.DiffStr(a, b)
//	_ = out
//	// <#diff // path:line
//	// - #map[string]int {
//	// -   a => 1 #int
//	// - }
//	// + #map[string]int {
//	// +   a => 2 #int
//	// + }
func ( *Dumper) (,  any) string {
	var  strings.Builder
	.printDiffHeader(&)
	.ensureColorizer()

	 := .diffDumps(, )
	 := splitLines(.left)
	 := splitLines(.right)
	 := diffLines(, )

	for ,  := range  {
		.WriteString(.diffPrefix(.kind))
		.WriteString(.diffTintLine(.text, .kind))
		.WriteString("\n")
	}

	return .String()
}

// DiffHTML returns an HTML diff between two values.
// @group Diff
//
// Example: HTML diff
//
//	a := map[string]int{"a": 1}
//	b := map[string]int{"a": 2}
//	html := godump.DiffHTML(a, b)
//	_ = html
//	// (html diff)
func (,  any) string {
	return defaultDumper.DiffHTML(, )
}

// DiffHTML returns an HTML diff between two values.
// @group Diff
//
// Example: HTML diff with a custom dumper
//
//	d := godump.NewDumper()
//	a := map[string]int{"a": 1}
//	b := map[string]int{"a": 2}
//	html := d.DiffHTML(a, b)
//	_ = html
//	// (html diff)
func ( *Dumper) (,  any) string {
	var  strings.Builder
	.WriteString(`<div style='background-color:black;'><pre style="background-color:black; color:white; padding:5px; border-radius: 5px">` + "\n")

	 := .clone()
	if !.disableColor {
		.colorizer = colorizeHTML
	}

	.WriteString(.DiffStr(, ))
	.WriteString("</pre></div>")
	return .String()
}

type diffDumpPair struct {
	left  string
	right string
}

// diffDumps builds the left and right dump strings, aligning reference ids.
func ( *Dumper) (,  any) diffDumpPair {
	 := .dumpStrNoHeader()
	 := .dumpStrNoHeader()

	if reflect.TypeOf() != reflect.TypeOf() {
		 := fmt.Sprintf("type: %s", .typeStringForAny())
		 := fmt.Sprintf("type: %s", .typeStringForAny())
		 =  + "\n" + 
		 =  + "\n" + 
	}

	return diffDumpPair{left: , right: }
}

// dumpStrNoHeader renders a dump without the header line.
func ( *Dumper) ( ...any) string {
	.ensureColorizer()
	 := newDumpState()

	var  strings.Builder
	 := tabwriter.NewWriter(&, 0, 0, 1, ' ', 0)
	.writeDump(, , ...)
	.Flush()
	return .String()
}

// printDiffHeader writes the diff header line when a caller frame is available.
func ( *Dumper) ( io.Writer) {
	,  := .findFirstNonInternalFrame(.skippedStackFrames)
	if  == "" {
		return
	}

	 := 
	if ,  := os.Getwd();  == nil {
		if ,  := filepath.Rel(, );  == nil {
			 = 
		}
	}

	 := fmt.Sprintf("<#diff // %s:%d", , )
	fmt.Fprintln(, .colorize(colorGray, ))
}

// typeStringForAny returns a displayable type for a value.
func ( *Dumper) ( any) string {
	if  == nil {
		return "<nil>"
	}
	return .getTypeString(reflect.TypeOf())
}

type diffKind int

const (
	diffEqual diffKind = iota
	diffDelete
	diffInsert
)

type diffLine struct {
	kind diffKind
	text string
}

// diffLines computes a line-level diff with insert/delete operations.
func diffLines(,  []string) []diffLine {
	if len() == 0 && len() == 0 {
		return nil
	}

	,  := len(), len()
	 := make([][]int, +1)
	for  := 0;  <= ; ++ {
		[] = make([]int, +1)
	}

	for  :=  - 1;  >= 0; -- {
		for  :=  - 1;  >= 0; -- {
			switch {
			case [] == []:
				[][] = [+1][+1] + 1
			case [+1][] >= [][+1]:
				[][] = [+1][]
			default:
				[][] = [][+1]
			}
		}
	}

	 := make([]diffLine, 0, +)
	,  := 0, 0
	for  <  &&  <  {
		switch {
		case [] == []:
			 = append(, diffLine{kind: diffEqual, text: []})
			++
			++
			continue
		case [+1][] >= [][+1]:
			 = append(, diffLine{kind: diffDelete, text: []})
			++
		default:
			 = append(, diffLine{kind: diffInsert, text: []})
			++
		}
	}

	for  <  {
		 = append(, diffLine{kind: diffDelete, text: []})
		++
	}
	for  <  {
		 = append(, diffLine{kind: diffInsert, text: []})
		++
	}

	return 
}

// diffPrefix returns the colored diff marker prefix.
func ( *Dumper) ( diffKind) string {
	switch  {
	case diffDelete:
		return .colorize(colorRed, "-") + " "
	case diffInsert:
		return .colorize(colorGreen, "+") + " "
	default:
		return "  "
	}
}

// diffTintLine tints a full diff line based on change type.
func ( *Dumper) ( string,  diffKind) string {
	if .disableColor {
		return 
	}

	switch  {
	case diffDelete:
		return .tintBackgroundLine(, colorRedBg, "#221010")
	case diffInsert:
		return .tintBackgroundLine(, colorGreenBg, "#102216")
	default:
		return 
	}
}

// tintBackgroundLine applies a full-line background while preserving text colors.
func ( *Dumper) (, ,  string) string {
	if isHTMLLine() {
		return `<span style="background-color:` +  + `; display:block; width:100%;">` +  + `</span>`
	}

	if strings.Contains(, string(ansiEscape)+"[") {
		return  + strings.ReplaceAll(, colorReset, colorReset+) + ansiEraseLine + colorReset
	}

	return  +  + ansiEraseLine + colorReset
}

const ansiEscape = '\x1b'
const ansiEraseLine = "\x1b[K"

// stripANSI removes ANSI escape sequences from a string.
func stripANSI( string) string {
	var  strings.Builder

	.Grow(len())
	for  := 0;  < len(); {
		if [] != ansiEscape {
			.WriteByte([])
			++
			continue
		}

		// Skip ANSI CSI sequences like "\x1b[31m" or "\x1b[K".
		if +1 < len() && [+1] == '[' {
			 += 2
			for  < len() && ([] < '@' || [] > '~') {
				++
			}
			if  < len() {
				++ // consume final byte
			}
			continue
		}

		// Drop lone escape byte.
		++
	}
	return .String()
}

// stripHTMLSpans removes color span tags while preserving content.
func stripHTMLSpans( string) string {
	const  = `<span style="color:`
	const  = `">`

	for {
		 := strings.Index(, )
		if  == -1 {
			break
		}
		 := [+len():]
		, ,  := strings.Cut(, )
		if ! {
			break
		}
		 :=  + len() + len() + len()
		 = [:] + [:]
	}
	return strings.ReplaceAll(, "</span>", "")
}

// isHTMLLine reports whether the line contains HTML color spans.
func isHTMLLine( string) bool {
	return strings.Contains(, `<span style="color:`)
}

// splitLines splits a string into lines while normalizing CRLF and trimming a trailing newline.
func splitLines( string) []string {
	 = strings.ReplaceAll(, "\r\n", "\n")
	 = strings.ReplaceAll(, "\r", "\n")
	 = strings.TrimSuffix(, "\n")
	if  == "" {
		return nil
	}
	return strings.Split(, "\n")
}