package sim

import (
	"fmt"
	"slices"

	"tinyadventure/internal/model"
)

type effect struct {
	id    string
	owner *combatant
	power float64
	due   bool
}

func (c *combatant) under(id string) bool {
	return slices.ContainsFunc(c.effects, func(e effect) bool { return e.id == id })
}

func (c *combatant) drop(id string) {
	c.effects = slices.DeleteFunc(c.effects, func(e effect) bool { return e.id == id })
}

func (c *combatant) sum(id string) float64 {
	n := 0.0
	for _, e := range c.effects {
		if e.id == id {
			n += e.power
		}
	}
	return n
}

func (c *combatant) boost() float64 { return 1 + c.sum("rage") + c.sum("rally") }

func (c *combatant) tauntedBy(foes []*combatant) *combatant {
	for i := len(c.effects) - 1; i >= 0; i-- {
		if e := c.effects[i]; e.id == "taunt" && slices.Contains(foes, e.owner) {
			return e.owner
		}
	}
	return nil
}

func (c *combatant) exposure() float64 { return 1 + c.sum("mark") }

func (c *combatant) hidden() bool { return c.under("sneak") }

func (c *combatant) startTurn() {
	for i := range c.effects {
		c.effects[i].due = true
	}
}

func (c *combatant) endTurn() {
	c.effects = slices.DeleteFunc(c.effects, func(e effect) bool { return e.due })
}

var effectText = map[string]string{
	"taunt": "must attack %s next",
	"rage":  "rages: %d%% more damage on the next attack",
	"sneak": "slips out of sight",
	"dodge": "gets ready to dodge",
	"ward":  "is warded against every type",
	"rally": "deals %d%% more damage",
	"mark":  "is marked to take %d%% more damage",
	"haste": "acts at once",
}

func (b *battle) cast(actor *combatant, a model.Ability) {
	var targets []*combatant
	switch a.Target {
	case TargetSelf:
		targets = []*combatant{actor}
	case TargetAllAllies:
		targets = b.side(actor.side)
	case TargetAllEnemies:
		targets = b.side(1 - actor.side)
	case TargetEnemy:
		targets = []*combatant{b.pickTarget(actor, b.side(1-actor.side))}
	case TargetAlly:
		targets = []*combatant{b.hasteTarget(actor)}
	}
	for _, t := range targets {
		if a.ID != "haste" {
			t.effects = append(t.effects, effect{id: a.ID, owner: actor, power: a.Power})
		}
		text := effectText[a.ID]
		if a.ID == "taunt" {
			text = fmt.Sprintf(text, actor.unit.Name)
		} else if a.Power > 0 {
			text = fmt.Sprintf(text, int(a.Power*100))
		}
		b.log = append(b.log, model.CombatEvent{
			Tick: b.tick, Actor: actor.unit.ID, Target: t.unit.ID, Ability: a.ID, Kind: a.Kind, Amount: int(a.Power * 100),
			Text: fmt.Sprintf("%s uses %s: %s %s", actor.unit.Name, a.Name, t.unit.Name, text),
		})
	}
	if a.ID == "sneak" {
		actor.ambush = true
	}
	if a.ID == "haste" && targets[0] != actor {
		b.act(targets[0], true)
	}
}

func (b *battle) hasteTarget(actor *combatant) *combatant {
	best := actor
	for _, al := range b.side(actor.side) {
		if al != actor && (best == actor || max(al.stats.Attack, al.stats.Magic) > max(best.stats.Attack, best.stats.Magic)) {
			best = al
		}
	}
	return best
}
