package world

import (
	"container/heap"

	"tinyadventure/internal/model"
)

type node struct {
	at   [2]int
	cost int
}

type frontier []node

func (f frontier) Len() int           { return len(f) }
func (f frontier) Less(i, j int) bool { return f[i].cost < f[j].cost }
func (f frontier) Swap(i, j int)      { f[i], f[j] = f[j], f[i] }
func (f *frontier) Push(x any)        { *f = append(*f, x.(node)) }
func (f *frontier) Pop() any {
	old := *f
	n := old[len(old)-1]
	*f = old[:len(old)-1]
	return n
}

func Path(m *model.Map, from, to [2]int, blocked func(x, y int) bool, toll func(x, y int) int) [][2]int {
	if !m.Walkable(to[0], to[1]) {
		return nil
	}
	prev := map[[2]int][2]int{from: from}
	best := map[[2]int]int{from: 0}
	open := &frontier{{from, 0}}
	for open.Len() > 0 {
		c := heap.Pop(open).(node)
		if c.at == to {
			var out [][2]int
			for at := to; at != from; at = prev[at] {
				out = append([][2]int{at}, out...)
			}
			return out
		}
		if c.cost > best[c.at] {
			continue
		}
		for _, n := range Neighbours(c.at[0], c.at[1]) {
			if !m.Walkable(n[0], n[1]) || (n != to && blocked != nil && blocked(n[0], n[1])) {
				continue
			}
			cost := c.cost + m.Cost(n[0], n[1])
			if toll != nil {
				cost += toll(n[0], n[1])
			}
			if old, seen := best[n]; seen && old <= cost {
				continue
			}
			best[n], prev[n] = cost, c.at
			heap.Push(open, node{n, cost})
		}
	}
	return nil
}

func Reach(m *model.Map, from [2]int) map[[2]int]bool {
	seen := map[[2]int]bool{from: true}
	queue := [][2]int{from}
	for len(queue) > 0 {
		c := queue[0]
		queue = queue[1:]
		for _, n := range Neighbours(c[0], c[1]) {
			if !seen[n] && m.Walkable(n[0], n[1]) {
				seen[n] = true
				queue = append(queue, n)
			}
		}
	}
	return seen
}
