package gen

import (
	"sort"

	"tinyadventure/internal/model"
	"tinyadventure/internal/world"
)

const (
	mapW = 68
	mapH = 46
)

var themeClimate = map[string]world.Climate{
	"blood": {Temp: -0.6, Moist: 1}, "reptile": {Temp: 1, Moist: 1}, "outlaw": {Temp: 1, Moist: -1}, "grave": {Temp: -1, Moist: -1},
	"occult": {Temp: 1, Moist: 0}, "greenskin": {Temp: 0.6, Moist: -0.6}, "wild": {Temp: 0, Moist: 0.8}, "hex": {Temp: -0.2, Moist: 1},
}

func band(v float64) int {
	return min(2, max(0, int(v+1.5)))
}

func harshest(c world.Climate) byte { return byte(3*band(c.Temp) + band(c.Moist)) }

func buildMap(seed model.Seed, toward world.Climate) model.Map {
	return model.Map{Width: mapW, Height: mapH, Hexes: world.New(uint64(seed), mapW, mapH, toward).Map()}
}

func land(m *model.Map, c [2]int) bool {
	return m.Walkable(c[0], c[1]) && m.Hex(c[0], c[1])[0] >= model.ShapePlain
}

func mainland(m *model.Map) map[[2]int]bool {
	var best map[[2]int]bool
	seen := map[[2]int]bool{}
	for y := range m.Height {
		for x := range m.Width {
			c := [2]int{x, y}
			if seen[c] || !land(m, c) {
				continue
			}
			r := world.Reach(m, c)
			for k := range r {
				seen[k] = true
			}
			if len(r) > len(best) {
				best = r
			}
		}
	}
	return best
}

func hexes(m *model.Map, keep func(c [2]int) bool) [][2]int {
	var out [][2]int
	for y := range m.Height {
		for x := range m.Width {
			if c := [2]int{x, y}; keep(c) {
				out = append(out, c)
			}
		}
	}
	return out
}

func layRoads(m *model.Map, pts [][2]int) {
	sort.SliceStable(pts, func(i, j int) bool { return pts[i][0] < pts[j][0] })
	mark := func(c [2]int) {
		h := m.Hex(c[0], c[1])
		h[3] = h[3]&^model.FlagForest | model.FlagRoad
	}
	for i := range pts {
		mark(pts[i])
		if i == 0 {
			continue
		}
		near := pts[0]
		for _, p := range pts[:i] {
			if world.Distance(p[0], p[1], pts[i][0], pts[i][1]) < world.Distance(near[0], near[1], pts[i][0], pts[i][1]) {
				near = p
			}
		}
		for _, s := range world.Path(m, pts[i], near, nil, nil) {
			mark(s)
		}
	}
}
