package sim

import (
	"slices"
	"strings"

	"tinyadventure/internal/model"
)

type trait struct {
	suffix string
	slots  []model.Slot
	cost   model.Stats
}

var weaponTrinket = []model.Slot{model.SlotWeapon, model.SlotTrinket}
var armorTrinket = []model.Slot{model.SlotArmor, model.SlotHelm, model.SlotTrinket}

var itemTraits = map[string]trait{
	"lifesteal": {"of the Leech", weaponTrinket, model.Stats{Defense: 2}},
	"first":     {"of the Hawk", weaponTrinket, model.Stats{MaxHP: 6}},
	"sweep":     {"of Sweeping", []model.Slot{model.SlotWeapon}, model.Stats{Crit: 5}},
	"pierce":    {"of Piercing", []model.Slot{model.SlotWeapon}, model.Stats{Crit: 4}},
	"edge":      {"", weaponTrinket, model.Stats{Magic: 2}},
	"thorns":    {"of Thorns", armorTrinket, model.Stats{Speed: 2}},
	"guard":     {"", armorTrinket, model.Stats{Attack: 2}},
}

var traitOrder = []string{"lifesteal", "first", "sweep", "pierce", "edge", "thorns", "guard"}

var edgeSuffix = map[string]string{Poison: "of Venom", Fire: "of Embers", Frost: "of Rime", Lightning: "of Storms", Holy: "of Dawn", Shadow: "of Dusk"}

var guardSuffix = map[string]string{Poison: "of Venomguard", Fire: "of Fireguard", Frost: "of Frostguard", Lightning: "of Stormguard", Holy: "of Dawnguard", Shadow: "of Shadowguard"}

const guardPrefix = "guard-"

var traitChance = map[string]int{"common": 0, "uncommon": 45, "rare": 75, "epic": 100, "legendary": 100}

func Imbue(roll func(n int) int, it *model.Item) {
	if roll(100) >= traitChance[it.Rarity] {
		return
	}
	var fits []string
	for _, name := range traitOrder {
		if slices.Contains(itemTraits[name].slots, it.Slot) {
			fits = append(fits, name)
		}
	}
	name := fits[roll(len(fits))]
	t := itemTraits[name]
	suffix := t.suffix
	it.Trait = name
	switch name {
	case "edge":
		it.Trait = Elements[roll(len(Elements))]
		suffix = edgeSuffix[it.Trait]
	case "guard":
		el := Elements[roll(len(Elements))]
		it.Trait, suffix = guardPrefix+el, guardSuffix[el]
	}
	it.Name += " " + suffix
	b := &it.Bonus
	b.MaxHP -= t.cost.MaxHP
	b.Attack -= t.cost.Attack
	b.Defense -= t.cost.Defense
	b.Magic -= t.cost.Magic
	b.Speed -= t.cost.Speed
	b.Crit -= t.cost.Crit
	it.Value = model.Price(*it)
}

func TraitsOf(u model.Unit) []string {
	out := append([]string(nil), u.Traits...)
	for _, slot := range Slots {
		if it := u.Gear[slot]; it != nil && it.Trait != "" && !slices.Contains(out, it.Trait) {
			out = append(out, it.Trait)
		}
	}
	return out
}

func edgeOf(traits []string) string {
	for _, t := range traits {
		if slices.Contains(Elements, t) {
			return t
		}
	}
	return ""
}

func guardsOf(traits, resist []string) []string {
	out := slices.Clone(resist)
	for _, t := range traits {
		if el, ok := strings.CutPrefix(t, guardPrefix); ok {
			out = append(out, el)
		}
	}
	return out
}

func Guards(u model.Unit, typ string) bool {
	return slices.Contains(guardsOf(TraitsOf(u), u.Resist), typ)
}

func typesOf(u model.Unit) []string {
	edge := edgeOf(TraitsOf(u))
	var out []string
	for _, a := range slices.Concat(AllAbilities(u), Abilities(StrikeID)) {
		if a.Kind != KindDamage && a.Kind != KindAoE {
			continue
		}
		typ := a.Type
		if typ == Physical && edge != "" {
			typ = edge
		}
		if typ != Physical && !slices.Contains(out, typ) {
			out = append(out, typ)
		}
	}
	return out
}

func EdgeOf(units, foes []model.Unit) model.Edge {
	e := model.Edge{Hits: []string{}, Blunted: []string{}}
	armored := slices.ContainsFunc(foes, func(f model.Unit) bool { return slices.Contains(f.Traits, "armored") })
	has := func(pick func(model.Unit) []string, el string) bool {
		return slices.ContainsFunc(foes, func(f model.Unit) bool { return slices.Contains(pick(f), el) })
	}
	for _, u := range units {
		for _, el := range typesOf(u) {
			switch {
			case has(func(f model.Unit) []string { return f.Weak }, el):
				e.Hits = append(e.Hits, el+" ("+u.Name+")")
			case has(func(f model.Unit) []string { return f.Resist }, el):
				e.Blunted = append(e.Blunted, el+" ("+u.Name+")")
			}
		}
		if armored && slices.Contains(TraitsOf(u), "pierce") {
			e.Hits = append(e.Hits, "pierce ("+u.Name+")")
		}
	}
	return e
}
