package main

import "bytes"

// chunk is the stretch compare skips at once when it is equal.
const chunk = 1 << 16

// file is one side of a comparison. In single-file mode B is a file with
// none set: its value is 0 at every position, end mark included.
type file struct {
	b    []byte
	none bool
}

// val is the value at position i: the byte when i is inside the file, 256
// at i == len (the end mark), 0 past it. The end mark keeps a missing byte
// apart from a zero byte.
func (f file) val(i int) int {
	switch {
	case f.none || i > len(f.b):
		return 0
	case i == len(f.b):
		return 256
	}
	return int(f.b[i])
}

// verdict holds what one pass over positions 0 .. lmax finds. first, last
// and lastW are -1 when no position differs.
type verdict struct {
	first, last int
	count, runs int
	lastW       int // last differing position below window start + FS*seconds
	lmax        int
}

func (v verdict) identical() bool { return v.count == 0 }

// compare walks every position once. seconds is the -s value, which bounds
// the stretch rendered after the recording starts.
func compare(a, b file, seconds int) verdict {
	v := verdict{first: -1, last: -1, lastW: -1, lmax: max(len(a.b), len(b.b))}
	common := min(len(a.b), len(b.b)) // 0 in single-file mode
	limit, prev := 0, false
	for i := 0; i <= v.lmax; i++ {
		if i%chunk == 0 && i+chunk <= common && bytes.Equal(a.b[i:i+chunk], b.b[i:i+chunk]) {
			i += chunk - 1 // an equal stretch holds no differing position
			prev = false
			continue
		}
		var d bool
		if i < common {
			d = a.b[i] != b.b[i] // the fast path; val gives the same answer here
		} else {
			d = a.val(i) != b.val(i)
		}
		if d {
			if v.first < 0 {
				v.first = i
				limit = recordingStart(i) + FS*seconds
			}
			if !prev {
				v.runs++
			}
			v.last = i
			v.count++
			if i < limit {
				v.lastW = i
			}
		}
		prev = d
	}
	return v
}

// recordingStart is one second of file before the first difference.
func recordingStart(first int) int { return max(0, first-FS) }
