package empyrionitems

import (
	"os"
	"strings"
	"testing"
)

func TestLoadItemsConfig(t *testing.T) {
	idx, err := LoadFromFile("ItemsConfig.ecf")
	if err != nil {
		t.Fatalf("LoadFromFile: %v", err)
	}
	if len(idx.Items) < 30 {
		t.Fatalf("expected at least 30 items in ItemsConfig.ecf, got %d", len(idx.Items))
	}
	t.Logf("ItemsConfig: parsed %d items", len(idx.Items))

	// Spot checks against entries seen in the live ItemsConfig.ecf header sample.
	cases := []struct {
		id   int
		name string
	}{
		{1, "MeleePlayer"},
		{12, "Fillertool"},
		{220, "MetalPieces"},
		{240, "EnergyCellHydrogen"},
		{398, "XP"},
	}
	for _, tc := range cases {
		it := idx.ByID(tc.id)
		if it == nil {
			t.Errorf("id %d not found", tc.id)
			continue
		}
		if it.Name != tc.name {
			t.Errorf("id %d: name %q, want %q", tc.id, it.Name, tc.name)
		}
	}
}

func TestLoadBlocksConfig(t *testing.T) {
	if _, err := os.Stat("BlocksConfig.ecf"); os.IsNotExist(err) {
		t.Skip("BlocksConfig.ecf not present alongside test")
	}
	idx, err := LoadFromFile("BlocksConfig.ecf")
	if err != nil {
		t.Fatalf("LoadFromFile: %v", err)
	}
	if len(idx.Items) < 1500 {
		t.Fatalf("expected >1500 entries in BlocksConfig.ecf, got %d", len(idx.Items))
	}
	t.Logf("BlocksConfig: parsed %d entries", len(idx.Items))

	// Spot check by name (IDs evolve across versions; names are stable).
	for _, name := range []string{"Air", "Stone", "Grass"} {
		if idx.ByName(name) == nil {
			t.Errorf("expected to find %q", name)
		}
	}

	// Search must return matches for common item families.
	hits := idx.Search("Constructor", "", 50)
	if len(hits) < 2 {
		t.Errorf("search 'Constructor' should hit multiple devices, got %d", len(hits))
	}
	for _, h := range hits[:1] {
		if !strings.Contains(strings.ToLower(h.Name), "constructor") {
			t.Errorf("unexpected match: %+v", h)
		}
	}
}
