package gen

import (
	"fmt"
	"math/rand/v2"

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

var spawnKinds = []struct{ kind, hint string }{
	{"shrine", "A roadside shrine, its offering bowl full of fresh ash. A pilgrim's note points toward %s."},
	{"burned inn", "The burned inn still smells of smoke. A survivor mutters that the trouble began near %s."},
	{"crossroads", "A weathered signpost has one arm scratched over in blood: %s."},
	{"watchpost", "An abandoned watchpost. The last log entry reads: all eyes on %s."},
	{"wagon", "A broken merchant wagon. A torn map is marked at %s."},
}

func buildSpawns(r *rand.Rand, m *model.Map, main map[[2]int]bool) []model.SpawnPoint {
	kinds := rng.Shuffled(r, spawnKinds)
	west := func(open bool) func(c [2]int) bool {
		return func(c [2]int) bool {
			h := m.Hex(c[0], c[1])
			return main[c] && c[0] >= 3 && c[0] <= mapW/5 && c[1] >= 5 && c[1] < mapH-5 && (!open || h[0] == model.ShapePlain && h[3]&model.FlagForest == 0)
		}
	}
	sites := hexes(m, west(true))
	if len(sites) < 2 {
		sites = hexes(m, west(false))
	}
	a := rng.Pick(r, sites)
	b := a
	for _, c := range rng.Shuffled(r, sites) {
		if d := world.Distance(a[0], a[1], c[0], c[1]); d >= 6 && d <= 14 {
			b = c
			break
		}
	}
	out := []model.SpawnPoint{
		{ID: "sp1", Kind: kinds[0].kind, X: a[0], Y: a[1], Hint: kinds[0].hint},
		{ID: "sp2", Kind: kinds[1].kind, X: b[0], Y: b[1], Hint: kinds[1].hint},
	}
	for _, s := range out {
		m.Hex(s.X, s.Y)[3] &^= model.FlagForest
	}
	return out
}

func hintSpawns(spawns []model.SpawnPoint, first model.POI) {
	for i := range spawns {
		spawns[i].Hint = fmt.Sprintf(spawns[i].Hint, first.Name)
	}
}
