package scrabble

import (
	"sort"
	"strconv"
	"strings"
)

// moveKey is a canonical string identifying a play (direction plus its placed tiles),
// used to de-duplicate and compare generated moves.
func moveKey(dir Direction, p []Placement) string {
	ps := append([]Placement(nil), p...)
	sort.Slice(ps, func(i, j int) bool {
		if ps[i].Row != ps[j].Row {
			return ps[i].Row < ps[j].Row
		}
		return ps[i].Col < ps[j].Col
	})
	var sb strings.Builder
	sb.WriteByte('0' + byte(dir))
	for _, pl := range ps {
		sb.WriteByte(';')
		sb.WriteString(strconv.Itoa(pl.Row))
		sb.WriteByte(',')
		sb.WriteString(strconv.Itoa(pl.Col))
		sb.WriteByte(',')
		sb.WriteString(strconv.Itoa(int(pl.Letter)))
		if pl.Blank {
			sb.WriteByte('*')
		}
	}
	return sb.String()
}

// Key returns the canonical identifier of the move (direction plus its placed tiles).
func (m Move) Key() string { return moveKey(m.Dir, m.Tiles) }
