package gen

import (
	"fmt"

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

const (
	guardChance = 40
	mimicChance = 15
	trapChance  = 25
)

func placeLoot(p *placer, maxDist int, byPower []model.Faction) []model.Band {
	var bands []model.Band
	for _, c := range p.take(rng.Between(p.r, 6, 9), 4, func([2]int) bool { return true }) {
		lv := levelAt(p.origin, maxDist, c[0], c[1])
		id := fmt.Sprintf("chest%d", len(p.m.Loot)+1)
		roll := p.r.IntN(100)
		bonus := 0
		node := model.LootNode{ID: id, X: c[0], Y: c[1]}
		switch {
		case roll < guardChance:
			bonus = 1
			f := factionAt(byPower, p.progress(c, maxDist), p.r.Float64())
			bands = append(bands, model.Band{Kind: "guard", Name: "Guards", Faction: f.ID, Level: lv, X: c[0], Y: c[1], HomeX: c[0], HomeY: c[1]})
		case roll < guardChance+mimicChance:
			bonus = 2
			bands = append(bands, model.Band{Kind: "mimic", Name: "Mimic", Level: lv, X: c[0], Y: c[1], HomeX: c[0], HomeY: c[1]})
		case roll < guardChance+mimicChance+trapChance:
			bonus = 1
			node.Trap = true
		}
		node.Item = sim.RollItem(p.r, lv+2*bonus)
		p.m.Loot = append(p.m.Loot, node)
	}
	return bands
}

func factionAt(byPower []model.Faction, prog, jitter float64) model.Faction {
	return byPower[min(len(byPower)-1, int(prog*float64(len(byPower))+jitter*0.8))]
}
