package server

import (
	"fmt"
	"maps"
	"slices"

	"tinyadventure/internal/model"
	"tinyadventure/internal/sim"
)

const (
	hazardPC   = 2
	hazardToll = 6
)

var hazardBiomes = map[byte]string{2: sim.Frost, 5: sim.Poison, 6: sim.Fire}

func hazardOf(m *model.Map, x, y int) (string, string) {
	h := m.Hex(x, y)
	switch {
	case h[3]&model.FlagRoad != 0:
		return "", ""
	case h[0] == model.ShapeShallow:
		return "Wading", sim.Frost
	case h[0] == model.ShapeMountain:
		return "The climb", sim.Physical
	}
	if typ, ok := hazardBiomes[h[1]]; ok {
		return model.Biomes[h[1]], typ
	}
	return "", ""
}

func endure(m *model.Map, units []model.Unit, x, y int, lost map[string]int) {
	name, typ := hazardOf(m, x, y)
	if name == "" {
		return
	}
	for i := range units {
		u := &units[i]
		if typ != sim.Physical && sim.Guards(*u, typ) {
			continue
		}
		hit := min(u.Stats.HP-1, max(1, sim.Effective(*u).MaxHP*hazardPC/100))
		u.Stats.HP -= max(0, hit)
		lost[name] += max(0, hit)
	}
}

func (g *game) toll(x, y int) int {
	if name, _ := hazardOf(&g.state.Map, x, y); name != "" {
		return hazardToll
	}
	return 0
}

func (g *game) noteHazards(lost map[string]int) {
	for _, name := range slices.Sorted(maps.Keys(lost)) {
		if lost[name] > 0 {
			g.note(fmt.Sprintf("%s costs the party %d hp", name, lost[name]))
		}
	}
}

func (g *game) note(text string) { g.state.Notes = append(g.state.Notes, text) }
