package sim

import (
	"fmt"
	"slices"

	"tinyadventure/internal/model"
)

const (
	weakMult    = 1.5
	armorPlus   = 3
	firstMult   = 1.5
	lifestealPC = 30
	thornsPC    = 25
	sweepPC     = 50
)

var (
	thornsAbility    = model.Ability{ID: "thorns", Name: "Thorns", Kind: KindDamage, Type: Physical}
	lifestealAbility = model.Ability{ID: "lifesteal", Name: "Lifesteal", Kind: KindHeal}
)

func (c *combatant) typeOf(a model.Ability) string {
	if a.Type == Physical && c.edge != "" {
		return c.edge
	}
	return a.Type
}

func (c *combatant) statFor(a model.Ability) int {
	if usesAttack(a.Type) {
		return c.stats.Attack
	}
	return c.stats.Magic
}

func (c *combatant) guarded(typ string) bool {
	return typ == Physical || slices.Contains(c.guards, typ) || c.under("ward")
}

func (c *combatant) defense() int {
	def := max(c.stats.Defense, 0)
	if c.has("armored") {
		def += armorPlus
	}
	return def
}

func (b *battle) hit(actor, target *combatant, a model.Ability, scale float64) {
	typ := actor.typeOf(a)
	if target.under("dodge") {
		target.drop("dodge")
		b.log = append(b.log, model.CombatEvent{
			Tick: b.tick, Actor: actor.unit.ID, Target: target.unit.ID, Ability: a.ID, Kind: a.Kind, Type: typ, Dodged: true,
			Text: fmt.Sprintf("%s dodges %s's %s", target.unit.Name, actor.unit.Name, a.Name),
		})
		return
	}
	raw := float64(max(actor.statFor(a), 1)) * a.Power * scale * (0.85 + 0.3*b.r.Float64())
	crit := actor.ambush || b.r.IntN(100) < actor.stats.Crit
	actor.ambush = false
	if crit {
		raw *= 2
	}
	if actor.has("first") && !actor.struck {
		raw *= firstMult
	}
	actor.struck = true
	raw *= actor.boost() * target.exposure()
	verb := "damage"
	if typ != Physical {
		verb = typ + " damage"
	}
	if slices.Contains(target.unit.Weak, typ) {
		raw *= weakMult
		verb += ", a weakness"
	}
	if target.guarded(typ) {
		def := target.defense()
		if actor.has("pierce") {
			def = 0
		}
		raw = raw * 10 / float64(10+def)
		if typ != Physical {
			verb += ", guarded"
		}
	}
	dmg := max(1, int(raw))
	target.hp = max(0, target.hp-dmg)
	target.hurtBy = actor
	b.emit(actor, target, a, typ, dmg, crit, !target.alive(), verb)
	if actor.has("lifesteal") && actor.alive() && actor.hp < actor.stats.MaxHP {
		drain := min(actor.stats.MaxHP-actor.hp, max(1, dmg*lifestealPC/100))
		actor.hp += drain
		b.emit(actor, actor, lifestealAbility, "", drain, false, false, "healing")
	}
	if target.has("thorns") && a.Kind == KindDamage && usesAttack(a.Type) && actor.alive() {
		back := max(1, dmg*thornsPC/100)
		actor.hp = max(0, actor.hp-back)
		b.emit(target, actor, thornsAbility, Physical, back, false, !actor.alive(), "damage")
	}
	if scale == 1 && actor.alive() && actor.has("sweep") && a.Kind == KindDamage {
		for _, f := range b.side(target.side) {
			if f != target {
				b.hit(actor, f, a, float64(sweepPC)/100)
				break
			}
		}
	}
}

func (b *battle) heal(actor *combatant, a model.Ability) {
	allies := b.side(actor.side)
	targets := allies[:0:0]
	if a.Target == TargetAllAllies {
		for _, al := range allies {
			if al.hp < al.stats.MaxHP {
				targets = append(targets, al)
			}
		}
	} else {
		t := allies[0]
		for _, al := range allies[1:] {
			if al.hp*t.stats.MaxHP < t.hp*al.stats.MaxHP {
				t = al
			}
		}
		targets = append(targets, t)
	}
	for _, t := range targets {
		amt := max(1, int(float64(actor.stats.Magic)*a.Power*(0.85+0.3*b.r.Float64())))
		amt = min(amt, t.stats.MaxHP-t.hp)
		t.hp += amt
		b.emit(actor, t, a, "", amt, false, false, "healing")
	}
}

func (b *battle) emit(actor, target *combatant, a model.Ability, typ string, amount int, crit, killed bool, verb string) {
	text := fmt.Sprintf("%s uses %s on %s for %d %s", actor.unit.Name, a.Name, target.unit.Name, amount, verb)
	if crit {
		text += " (crit)"
	}
	if killed {
		text += ", " + target.unit.Name + " falls"
	}
	b.log = append(b.log, model.CombatEvent{
		Tick: b.tick, Actor: actor.unit.ID, Target: target.unit.ID, Ability: a.ID, Kind: a.Kind, Type: typ,
		Amount: amount, Crit: crit, Killed: killed, Text: text,
	})
}
