package gen

import (
	"reflect"
	"slices"
	"strings"
	"testing"

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

func TestDeterministic(t *testing.T) {
	for _, s := range []model.Seed{1, 42, 99999} {
		if !reflect.DeepEqual(Generate(s), Generate(s)) {
			t.Fatalf("seed %d not deterministic", s)
		}
	}
}

func bfs(m model.Map, sx, sy int) map[[2]int]bool {
	return world.Reach(&m, [2]int{sx, sy})
}

func TestSolvable(t *testing.T) {
	for i := 0; i < 200; i++ {
		seed := rng.NewSeed() + model.Seed(i)
		w := Generate(seed)
		c := w.Campaign
		if n := len(c.Main.Steps); n < 6 || n > 10 {
			t.Fatalf("seed %d: %d main steps", seed, n)
		}
		if n := len(w.Party.Units); n < 3 || n > 4 {
			t.Fatalf("seed %d: party %d", seed, n)
		}
		sp := w.Map.Spawns[0]
		reach := bfs(w.Map, sp.X, sp.Y)
		for _, s := range w.Map.Spawns {
			if !reach[[2]int{s.X, s.Y}] {
				t.Fatalf("seed %d: spawn unreachable", seed)
			}
		}
		pois := map[string]model.POI{}
		for _, p := range w.Map.POIs {
			pois[p.ID] = p
			if !reach[[2]int{p.X, p.Y}] {
				t.Fatalf("seed %d: poi %s unreachable", seed, p.ID)
			}
		}
		loot := map[string]model.LootNode{}
		for _, l := range w.Map.Loot {
			loot[l.Item.ID] = l
			if !reach[[2]int{l.X, l.Y}] {
				t.Fatalf("seed %d: loot %s unreachable", seed, l.ID)
			}
		}
		missions := append([]model.Mission{c.Main}, c.SideQuests...)
		for _, ms := range missions {
			for _, s := range ms.Steps {
				if _, ok := pois[s.POI]; !ok {
					t.Fatalf("seed %d: step %s poi missing", seed, s.ID)
				}
				if s.Slots.Item != "" {
					l, ok := loot[s.Slots.Item]
					if !ok || !l.Item.Key || l.X != pois[s.POI].X || l.Y != pois[s.POI].Y {
						t.Fatalf("seed %d: key item %s missing", seed, s.Slots.Item)
					}
				}
			}
		}
		last := c.Main.Steps[len(c.Main.Steps)-1]
		if last.Kind != "boss" {
			t.Fatalf("seed %d: no final boss step", seed)
		}
		boss := false
		for _, e := range w.Encounters {
			if e.Boss && e.POI == last.POI {
				boss = true
			}
		}
		if !boss {
			t.Fatalf("seed %d: boss encounter missing", seed)
		}
		if !strings.Contains(sp.Hint, pois[c.Main.Steps[0].POI].Name) {
			t.Fatalf("seed %d: hint does not name first step", seed)
		}
	}
}

func TestDifficultyScales(t *testing.T) {
	for seed := model.Seed(1); seed <= 50; seed++ {
		w := Generate(seed)
		first := w.Encounters[0].Enemies[len(w.Encounters[0].Enemies)-1].Level
		b := w.Encounters[len(w.Campaign.Main.Steps)-1]
		if b.Enemies[0].Stats.MaxHP <= w.Encounters[0].Enemies[0].Stats.MaxHP || b.Enemies[0].Level <= first {
			t.Fatalf("seed %d: boss not stronger", seed)
		}
	}
}

func TestSeedsVary(t *testing.T) {
	systems, factions, names := map[string]bool{}, map[string]bool{}, map[string]bool{}
	for seed := model.Seed(1); seed <= 60; seed++ {
		c := Generate(seed).Campaign
		systems[strings.Join(c.Systems, ",")] = true
		var fs []string
		for _, f := range c.Factions {
			fs = append(fs, f.Name)
		}
		factions[strings.Join(fs, ",")] = true
		names[c.Main.Name] = true
	}
	if len(systems) < 10 || len(factions) < 10 || len(names) < 3 {
		t.Fatalf("too little variety: %d %d %d", len(systems), len(factions), len(names))
	}
}

func TestEveryCampaignIsAKeyHuntOverPlacesOnTheMap(t *testing.T) {
	for seed := model.Seed(1); seed <= 200; seed++ {
		w := Generate(seed)
		names := map[string]bool{}
		for i, s := range w.Campaign.Main.Steps[1 : len(w.Campaign.Main.Steps)-1] {
			if s.Kind != "retrieve" || s.Slots.Item == "" || names[s.Text[:strings.Index(s.Text, " from ")]] {
				t.Fatalf("seed %d: main step %d is %q, %q, with item %q", seed, i+2, s.Kind, s.Text, s.Slots.Item)
			}
			names[s.Text[:strings.Index(s.Text, " from ")]] = true
		}
		for _, sys := range w.Campaign.Systems {
			kind, ok := strings.CutPrefix(sys, "poi:")
			if ok && !slices.ContainsFunc(w.Map.POIs, func(p model.POI) bool { return p.Kind == kind }) {
				t.Fatalf("seed %d lists %s with no %s on the map", seed, sys, kind)
			}
		}
	}
}

func TestEveryHeroDrawsThreeAbilitiesWithOneThatHits(t *testing.T) {
	for seed := model.Seed(1); seed <= 60; seed++ {
		for _, u := range Generate(seed).Party.Units {
			hits := slices.ContainsFunc(u.Abilities, func(a model.Ability) bool { return a.Kind == sim.KindDamage || a.Kind == sim.KindAoE })
			if len(u.Abilities) != sim.Drawn || !hits {
				t.Fatalf("seed %d %s %s: %+v", seed, u.Class, u.Name, u.Abilities)
			}
		}
	}
}
