package gitrepo

import (
	"context"
	"errors"
	"os/exec"
	"strconv"
	"strings"
)

// DiffLine is één regel in een unified diff.
// New is het regelnummer in het nieuwe bestand. 0 betekent dat de regel
// alleen in het oude bestand staat.
type DiffLine struct {
	Kind string
	Old  int
	New  int
	Text string
}

// DiffFile is één bestand in een diff.
type DiffFile struct {
	Path  string
	Lines []DiffLine
}

// DiffFiles vergelijkt source met de merge-base van target.
// Een diff zonder wijzigingen is een lege lijst.
func DiffFiles(ctx context.Context, gitBin, dir, target, source string) ([]DiffFile, error) {
	out, err := runAllow(ctx, gitBin, nil, 1, "-C", dir, "diff", "--no-color", "--unified=3", target+"..."+source)
	if err != nil {
		return nil, err
	}
	return ParseDiff(out), nil
}

// BlobText leest een bestand op een revisie. Een ontbrekend bestand is een fout.
func BlobText(ctx context.Context, gitBin, dir, rev, path string) (string, error) {
	return run(ctx, gitBin, nil, "-C", dir, "show", rev+":"+path)
}

// ParseDiff leest de tekst van git diff.
func ParseDiff(raw string) []DiffFile {
	var files []DiffFile
	var cur *DiffFile
	var oldLine, newLine int
	inHunk := false
	for _, line := range strings.Split(raw, "\n") {
		switch {
		case strings.HasPrefix(line, "diff --git "):
			files = append(files, DiffFile{})
			cur = &files[len(files)-1]
			oldLine, newLine = 0, 0
			inHunk = false
		case cur == nil:
			continue
		case !inHunk && strings.HasPrefix(line, "rename to "):
			cur.Path = strings.TrimSpace(strings.TrimPrefix(line, "rename to "))
		case !inHunk && strings.HasPrefix(line, "+++ "):
			p := strings.TrimSpace(strings.TrimPrefix(line, "+++ "))
			if p != "/dev/null" {
				cur.Path = stripAB(p)
			}
		case strings.HasPrefix(line, "@@"):
			oldLine, newLine = hunkStart(line)
			oldLine--
			newLine--
			inHunk = true
			cur.Lines = append(cur.Lines, DiffLine{Kind: "hunk", Text: line})
		case !inHunk:
			continue
		case strings.HasPrefix(line, `\`):
			continue
		case strings.HasPrefix(line, "+"):
			newLine++
			cur.Lines = append(cur.Lines, DiffLine{Kind: "add", New: newLine, Text: line[1:]})
		case strings.HasPrefix(line, "-"):
			oldLine++
			cur.Lines = append(cur.Lines, DiffLine{Kind: "del", Old: oldLine, Text: line[1:]})
		case strings.HasPrefix(line, " "):
			oldLine++
			newLine++
			cur.Lines = append(cur.Lines, DiffLine{Kind: "ctx", Old: oldLine, New: newLine, Text: line[1:]})
		}
	}
	var out []DiffFile
	for _, f := range files {
		if f.Path != "" {
			out = append(out, f)
		}
	}
	return out
}

func hunkStart(line string) (old, new int) {
	parts := strings.Fields(line)
	if len(parts) < 3 {
		return 0, 0
	}
	return sideStart(parts[1]), sideStart(parts[2])
}

func sideStart(s string) int {
	s = strings.TrimLeft(s, "+-")
	if i := strings.IndexByte(s, ','); i >= 0 {
		s = s[:i]
	}
	n, _ := strconv.Atoi(s)
	return n
}

func stripAB(p string) string {
	if strings.HasPrefix(p, `"`) {
		if u, err := strconv.Unquote(p); err == nil {
			p = u
		}
	}
	if strings.HasPrefix(p, "a/") || strings.HasPrefix(p, "b/") {
		return p[2:]
	}
	return p
}

// runAllow is run, maar exitcode allow is geen fout. git diff doet dat bij wijzigingen.
func runAllow(ctx context.Context, bin string, env []string, allow int, args ...string) (string, error) {
	if bin == "" {
		bin = "git"
	}
	cmd := exec.CommandContext(ctx, bin, args...)
	if env != nil {
		cmd.Env = env
	}
	var stdout, stderr strings.Builder
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	err := cmd.Run()
	if err == nil {
		return stdout.String(), nil
	}
	var ee *exec.ExitError
	if errors.As(err, &ee) && ee.ExitCode() == allow {
		return stdout.String(), nil
	}
	msg := strings.TrimSpace(stderr.String())
	if msg == "" {
		msg = err.Error()
	}
	return "", errors.New(msg)
}
