package main

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
)

// Slip is one correction, anchored to a line by content.
type Slip struct {
	N         int    `json:"n"`
	Date      string `json:"date"`
	Edition   string `json:"edition"`
	Line      int    `json:"line"`
	Text      string `json:"text"`
	Hash      string `json:"hash"`
	Copies    int    `json:"copies"`
	Twins     int    `json:"twins"`
	Rank      int    `json:"rank"`
	Before    string `json:"before"`
	After     string `json:"after"`
	Note      string `json:"note"`
	Withdrawn string `json:"withdrawn,omitempty"`
}

// Sidecar is the whole slip file, keys in the order they are written.
type Sidecar struct {
	About string `json:"about"`
	Tipin int    `json:"tipin"`
	Book  string `json:"book"`
	Next  int    `json:"next"`
	Slips []Slip `json:"slips"`
}

// Book is a text file as the anchoring sees it.
type Book struct {
	Lines   [][]byte
	Hashes  []string
	Edition string
}

type state int

const (
	gone  state = iota // no longer fits
	fits               // same edition, same line
	moved              // edition differs; line still fits
)

func lineHash(b []byte) string {
	sum := sha256.Sum256(b)
	return hex.EncodeToString(sum[:])[:16]
}

func editionHash(data []byte) string {
	sum := sha256.Sum256(data)
	return hex.EncodeToString(sum[:])
}

// splitLines splits on \n; a final newline makes no extra line; a trailing \r is dropped.
func splitLines(data []byte) [][]byte {
	if len(data) == 0 {
		return nil
	}
	lines := bytes.Split(data, []byte("\n"))
	if len(lines[len(lines)-1]) == 0 {
		lines = lines[:len(lines)-1]
	}
	for i, l := range lines {
		lines[i] = bytes.TrimSuffix(l, []byte("\r"))
	}
	return lines
}

func newBook(data []byte) *Book {
	b := &Book{Lines: splitLines(data), Edition: editionHash(data)}
	b.Hashes = make([]string, len(b.Lines))
	for i, l := range b.Lines {
		b.Hashes[i] = lineHash(l)
	}
	return b
}

// at returns the hash of 1-based line n, or "" past either edge.
func (b *Book) at(n int) string {
	if n < 1 || n > len(b.Hashes) {
		return ""
	}
	return b.Hashes[n-1]
}

// twins lists, in file order, the 1-based lines whose triple equals (before, hash, after).
func (b *Book) twins(before, hash, after string) []int {
	var out []int
	for i, h := range b.Hashes {
		n := i + 1
		if h == hash && b.at(n-1) == before && b.at(n+1) == after {
			out = append(out, n)
		}
	}
	return out
}

// anchor fills a new slip's anchoring fields for 1-based line n.
func (b *Book) anchor(n int) Slip {
	s := Slip{
		Edition: b.Edition,
		Line:    n,
		Text:    string(b.Lines[n-1]),
		Hash:    b.at(n),
		Before:  b.at(n - 1),
		After:   b.at(n + 1),
	}
	for _, h := range b.Hashes {
		if h == s.Hash {
			s.Copies++
		}
	}
	tw := b.twins(s.Before, s.Hash, s.After)
	s.Twins = len(tw)
	for i, l := range tw {
		if l == n {
			s.Rank = i + 1
		}
	}
	return s
}

// locate applies the three rules, in order, and nothing else.
func locate(b *Book, s Slip) (state, int) {
	if b.Edition == s.Edition {
		if s.Line < 1 || s.Line > len(b.Lines) { // only a hand-edited sidecar gets here
			return gone, 0
		}
		return fits, s.Line
	}
	if s.Copies == 1 {
		at := 0
		for i, h := range b.Hashes {
			if h == s.Hash {
				if at != 0 {
					return gone, 0
				}
				at = i + 1
			}
		}
		if at == 0 {
			return gone, 0
		}
		return moved, at
	}
	tw := b.twins(s.Before, s.Hash, s.After)
	if len(tw) != s.Twins || s.Rank < 1 || s.Rank > len(tw) {
		return gone, 0
	}
	return moved, tw[s.Rank-1]
}
