package facts

import (
	"encoding/json"
	"os"
	"path/filepath"
	"testing"

	"metis/pkg/inventory"
)

func TestAggregateAndLoadBranches(t *testing.T) {
	dir := t.TempDir()
	nested := filepath.Join(dir, "nested")
	if err := os.MkdirAll(nested, 0o755); err != nil {
		t.Fatal(err)
	}
	snapPath := filepath.Join(dir, "one.json")
	data, _ := json.Marshal(Snapshot{Hostname: "n1", Kernel: "k1", PackageSample: map[string]string{"p": "1"}})
	if err := os.WriteFile(snapPath, data, 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(nested, "two.json"), data, 0o644); err != nil {
		t.Fatal(err)
	}
	snaps, err := LoadDir(dir)
	if err != nil || len(snaps) != 2 {
		t.Fatalf("LoadDir = %#v err=%v", snaps, err)
	}
	if _, err := LoadDir(filepath.Join(dir, "missing")); err == nil {
		t.Fatal("expected LoadDir to fail for missing dir")
	}
	sums := Aggregate(nil, snaps)
	if sums["unknown"] == nil || len(sums["unknown"].Nodes) != 2 {
		t.Fatalf("Aggregate unknown = %#v", sums)
	}

	inv := &inventory.Inventory{
		Classes: []inventory.NodeClass{{Name: "rpi4"}},
		Nodes:   []inventory.NodeSpec{{Name: "n1", Class: "rpi4"}},
	}
	sums = Aggregate(inv, snaps)
	if sums["rpi4"] == nil {
		t.Fatalf("expected class summary: %#v", sums)
	}
	if got := ChooseTargets(&ClassSummary{Kernels: map[string]int{"a": 1, "b": 1}}); got.Kernel != "" {
		t.Fatalf("tie should clear target: %#v", got)
	}
	if got := ChooseTargets(nil); got.Packages == nil {
		t.Fatal("ChooseTargets should return initialized package map")
	}
}
