package index

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"sort"
	"time"

	"github.com/go-git/go-git/v6/plumbing/hash"
	"github.com/go-git/go-git/v6/utils/binary"
)

var (
	// EncodeVersionSupported is the range of supported index versions
	EncodeVersionSupported uint32 = 4

	// ErrInvalidTimestamp is returned by Encode if a Index with a Entry with
	// negative timestamp values
	ErrInvalidTimestamp = errors.New("negative timestamps are not allowed")
)

// An Encoder writes an Index to an output stream.
type Encoder struct {
	w         io.Writer
	hash      hash.Hash
	lastEntry *Entry
	skipHash  bool
}

// NewEncoder returns a new encoder that writes to w.
func NewEncoder(w io.Writer, h hash.Hash, opts ...Option) *Encoder {
	var cfg options
	for _, o := range opts {
		o(&cfg)
	}

	e := &Encoder{
		hash:     h,
		skipHash: cfg.skipHash,
	}

	if e.skipHash {
		e.w = w
	} else {
		h.Reset()
		e.w = io.MultiWriter(w, h)
	}

	return e
}

// Encode writes the Index to the stream of the encoder.
func (e *Encoder) Encode(idx *Index) error {
	return e.encode(idx, true)
}

func (e *Encoder) encode(idx *Index, footer bool) error {
	// TODO: support extensions
	if idx.Version > EncodeVersionSupported {
		return ErrUnsupportedVersion
	}

	if err := e.encodeHeader(idx); err != nil {
		return err
	}

	if err := e.encodeEntries(idx); err != nil {
		return err
	}

	if footer {
		return e.encodeFooter()
	}
	return nil
}

func (e *Encoder) encodeHeader(idx *Index) error {
	return binary.Write(e.w,
		indexSignature,
		idx.Version,
		uint32(len(idx.Entries)),
	)
}

func (e *Encoder) encodeEntries(idx *Index) error {
	sort.Sort(byNameAndStage(idx.Entries))

	for _, entry := range idx.Entries {
		if err := e.encodeEntry(idx, entry); err != nil {
			return err
		}
		entryLength := entryHeaderLength + e.hash.Size()
		if entry.IntentToAdd || entry.SkipWorktree {
			entryLength += 2
		}

		wrote := entryLength + len(entry.Name)
		if err := e.padEntry(idx, wrote); err != nil {
			return err
		}
	}

	return nil
}

func (e *Encoder) encodeEntry(idx *Index, entry *Entry) error {
	sec, nsec, err := e.timeToUint32(&entry.CreatedAt)
	if err != nil {
		return err
	}

	msec, mnsec, err := e.timeToUint32(&entry.ModifiedAt)
	if err != nil {
		return err
	}

	flags := uint16(entry.Stage&0x3) << 12
	if l := len(entry.Name); l < nameMask {
		flags |= uint16(l)
	} else {
		flags |= nameMask
	}

	flagsFlow := []any{flags}

	flow := make([]any, 0, 11+len(flagsFlow))
	flow = append(flow,
		sec, nsec,
		msec, mnsec,
		entry.Dev,
		entry.Inode,
		entry.Mode,
		entry.UID,
		entry.GID,
		entry.Size,
		entry.Hash.Bytes(),
	)

	if entry.IntentToAdd || entry.SkipWorktree {
		var extendedFlags uint16

		if entry.IntentToAdd {
			extendedFlags |= intentToAddMask
		}
		if entry.SkipWorktree {
			extendedFlags |= skipWorkTreeMask
		}

		flagsFlow = []any{flags | entryExtended, extendedFlags}
	}

	flow = append(flow, flagsFlow...)

	if err := binary.Write(e.w, flow...); err != nil {
		return err
	}

	switch idx.Version {
	case 2, 3:
		err = e.encodeEntryName(entry)
	case 4:
		err = e.encodeEntryNameV4(entry)
	default:
		err = ErrUnsupportedVersion
	}

	return err
}

func (e *Encoder) encodeEntryName(entry *Entry) error {
	return binary.Write(e.w, []byte(entry.Name))
}

func (e *Encoder) encodeEntryNameV4(entry *Entry) error {
	// V4 prefix compression: find the longest common prefix between the
	// previous entry's name and the current one. The strip length tells
	// the decoder how many bytes to remove from the end of the previous
	// name, and the suffix is the remainder of the current name.
	prefix := 0
	if e.lastEntry != nil {
		prefix = commonPrefixLen(e.lastEntry.Name, entry.Name)
	}
	stripLen := 0
	if e.lastEntry != nil {
		stripLen = len(e.lastEntry.Name) - prefix
	}

	e.lastEntry = entry

	if err := binary.WriteVariableWidthInt(e.w, int64(stripLen)); err != nil {
		return err
	}

	suffix := entry.Name[prefix:]
	return binary.Write(e.w, append([]byte(suffix), '\x00'))
}

// commonPrefixLen returns the length of the longest common byte prefix
// between a and b.
func commonPrefixLen(a, b string) int {
	n := min(len(b), len(a))
	for i := range n {
		if a[i] != b[i] {
			return i
		}
	}
	return n
}

func (e *Encoder) encodeRawExtension(signature string, data []byte) error {
	if len(signature) != 4 {
		return fmt.Errorf("invalid signature length")
	}

	_, err := e.w.Write([]byte(signature))
	if err != nil {
		return err
	}

	err = binary.WriteUint32(e.w, uint32(len(data)))
	if err != nil {
		return err
	}

	_, err = e.w.Write(data)
	if err != nil {
		return err
	}

	return nil
}

func (e *Encoder) timeToUint32(t *time.Time) (uint32, uint32, error) {
	if t.IsZero() {
		return 0, 0, nil
	}

	if t.Unix() < 0 || t.UnixNano() < 0 {
		return 0, 0, ErrInvalidTimestamp
	}

	return uint32(t.Unix()), uint32(t.Nanosecond()), nil
}

func (e *Encoder) padEntry(idx *Index, wrote int) error {
	if idx.Version == 4 {
		return nil
	}

	padLen := 8 - wrote%8

	_, err := e.w.Write(bytes.Repeat([]byte{'\x00'}, padLen))
	return err
}

func (e *Encoder) encodeFooter() error {
	if e.skipHash {
		_, err := e.w.Write(make([]byte, e.hash.Size()))
		return err
	}
	return binary.Write(e.w, e.hash.Sum(nil))
}

type byNameAndStage []*Entry

func (l byNameAndStage) Len() int      { return len(l) }
func (l byNameAndStage) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
func (l byNameAndStage) Less(i, j int) bool {
	if l[i].Name == l[j].Name {
		return l[i].Stage < l[j].Stage
	}
	return l[i].Name < l[j].Name
}
