package sim_test

import (
	"reflect"
	"testing"

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

func world(seed model.Seed) (model.Party, model.Encounter, model.Encounter) {
	w := gen.Generate(seed)
	first := w.Campaign.Main.Steps[0].POI
	boss := w.Campaign.Main.Steps[len(w.Campaign.Main.Steps)-1].POI
	var a, b model.Encounter
	for _, e := range w.Encounters {
		switch e.POI {
		case first:
			a = e
		case boss:
			b = e
		}
	}
	return w.Party, a, b
}

func levelUp(p *model.Party, level int) {
	for i := range p.Units {
		for p.Units[i].Level < level {
			sim.Grant(&p.Units[i], sim.NextLevelXP(p.Units[i].Level))
		}
	}
}

func TestDeterministic(t *testing.T) {
	run := func() sim.Result {
		p, enc, _ := world(7)
		return sim.Fight(rng.New(7), &p, enc, 1)
	}
	a, b := run(), run()
	if !reflect.DeepEqual(a, b) || len(a.Log) == 0 {
		t.Fatal("same seed produced different results or an empty log")
	}
}

func TestFuzzBounded(t *testing.T) {
	for i := range 300 {
		r := rng.New(model.Seed(i))
		p, a, b := world(model.Seed(i % 30))
		levelUp(&p, 1+r.IntN(6))
		enc := a
		if r.IntN(3) == 0 {
			enc = b
		}
		res := sim.Fight(r, &p, enc, 1+r.IntN(5))
		if res.Rounds > sim.MaxRounds || res.Rounds < 1 {
			t.Fatalf("seed %d rounds %d", i, res.Rounds)
		}
		if res.Outcome != sim.OutcomeVictory && res.Outcome != sim.OutcomeDefeat {
			t.Fatalf("bad outcome %q", res.Outcome)
		}
		for _, e := range res.Log {
			if e.Tick < 1 || e.Tick > sim.MaxRounds || e.Text == "" {
				t.Fatalf("bad event %+v", e)
			}
		}
	}
}

func TestFreshPartyBeatsFirstStepAndLosesToBoss(t *testing.T) {
	wins, bossWins := 0, 0
	for seed := model.Seed(1); seed <= 40; seed++ {
		p, a, b := world(seed)
		q := p
		q.Units = append([]model.Unit(nil), p.Units...)
		if sim.Fight(rng.New(seed), &p, a, 1).Outcome == sim.OutcomeVictory {
			wins++
		}
		if sim.Fight(rng.New(seed), &q, b, 1).Outcome == sim.OutcomeVictory {
			bossWins++
		}
	}
	if wins < 36 || bossWins > 0 {
		t.Fatalf("first step won %d of 40, boss won %d of 40", wins, bossWins)
	}
}

func TestXPAndLevelUp(t *testing.T) {
	for _, c := range sim.Classes {
		u := model.Unit{Class: c.Name, Level: 1, Stats: c.Base}
		before := u.Stats
		if n := sim.Grant(&u, sim.NextLevelXP(1)+5); n != 1 || u.Level != 2 || u.XP != 5 {
			t.Fatalf("%s: level %d xp %d gained %d", c.Name, u.Level, u.XP, n)
		}
		if u.Stats.MaxHP <= before.MaxHP || u.Stats.Defense <= before.Defense {
			t.Fatalf("%s did not grow: %+v -> %+v", c.Name, before, u.Stats)
		}
		if n := sim.Grant(&u, 100000); u.Level != sim.MaxLevel || n != sim.MaxLevel-2 {
			t.Fatalf("cap: level %d gained %d", u.Level, n)
		}
	}
}

func TestDefeatGivesNothing(t *testing.T) {
	p, _, boss := world(3)
	res := sim.Fight(rng.New(3), &p, boss, 1)
	if res.Outcome != sim.OutcomeDefeat || res.Rewards.XP != 0 || p.Units[0].XP != 0 {
		t.Fatalf("defeat must not reward: %+v", res.Rewards)
	}
}

func TestLootRolls(t *testing.T) {
	r := rng.New(5)
	count := map[string]int{}
	var lowSum, highSum int
	for range 2000 {
		lo, hi := sim.RollItem(r, 1), sim.RollItem(r, 6)
		count[lo.Rarity]++
		if lo.ID == "" || lo.Name == "" || lo.Slot == "" || lo.Value <= 0 {
			t.Fatalf("bad item %+v", lo)
		}
		lowSum += lo.Bonus.Attack + lo.Bonus.Defense + lo.Bonus.MaxHP
		highSum += hi.Bonus.Attack + hi.Bonus.Defense + hi.Bonus.MaxHP
	}
	if count["common"] <= count["rare"] || count["rare"] == 0 {
		t.Fatalf("rarity distribution %v", count)
	}
	if highSum <= lowSum {
		t.Fatal("higher tier must give stronger items")
	}
	common := sim.BuildItem(r, model.SlotWeapon, "common", 1)
	epic := sim.BuildItem(r, model.SlotWeapon, "epic", 1)
	if epic.Bonus.Attack <= common.Bonus.Attack || len(epic.Abilities) == 0 || len(common.Abilities) != 0 {
		t.Fatalf("rarity scaling %+v %+v", common, epic)
	}
}

func TestGearModifiesStatsAndAbilities(t *testing.T) {
	p, _, _ := world(2)
	u := p.Units[0]
	u.Gear = model.Gear{}
	base := sim.Effective(u)
	it := sim.BuildItem(rng.New(2), model.SlotWeapon, "epic", 3)
	it.Abilities = []string{"cleave"}
	u.Gear[model.SlotWeapon] = &it
	if sim.Effective(u).Attack <= base.Attack {
		t.Fatal("gear must raise attack")
	}
	found := false
	for _, a := range sim.AllAbilities(u) {
		found = found || a.ID == "cleave"
	}
	if !found {
		t.Fatal("gear ability missing")
	}
}
