package collector

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

	"bee/audit/internal/schema"
)

func TestEnrichCPUsWithTelemetry(t *testing.T) {
	tmp := t.TempDir()
	oldBase := cpuSysBaseDir
	cpuSysBaseDir = tmp
	t.Cleanup(func() { cpuSysBaseDir = oldBase })

	mustWriteFile(t, filepath.Join(tmp, "cpu0", "topology", "physical_package_id"), "0\n")
	mustWriteFile(t, filepath.Join(tmp, "cpu0", "thermal_throttle", "package_throttle_count"), "3\n")
	mustWriteFile(t, filepath.Join(tmp, "cpu1", "topology", "physical_package_id"), "1\n")
	mustWriteFile(t, filepath.Join(tmp, "cpu1", "thermal_throttle", "package_throttle_count"), "0\n")

	doc := sensorsDoc{
		"coretemp-isa-0000": {
			"Package id 0": map[string]any{"temp1_input": 61.5},
			"Package id 1": map[string]any{"temp2_input": 58.0},
		},
		"intel-rapl-mmio-0": {
			"Package id 0": map[string]any{"power1_average": 180.0},
			"Package id 1": map[string]any{"power2_average": 175.0},
		},
	}

	socket0 := 0
	socket1 := 1
	status := statusOK
	cpus := []schema.HardwareCPU{
		{Socket: &socket0, HardwareComponentStatus: schema.HardwareComponentStatus{Status: &status}},
		{Socket: &socket1, HardwareComponentStatus: schema.HardwareComponentStatus{Status: &status}},
	}

	got := enrichCPUsWithTelemetry(cpus, doc)

	if got[0].TemperatureC == nil || *got[0].TemperatureC != 61.5 {
		t.Fatalf("cpu0 temperature mismatch: %#v", got[0].TemperatureC)
	}
	if got[0].PowerW == nil || *got[0].PowerW != 180.0 {
		t.Fatalf("cpu0 power mismatch: %#v", got[0].PowerW)
	}
	if got[0].Throttled == nil || !*got[0].Throttled {
		t.Fatalf("cpu0 throttled mismatch: %#v", got[0].Throttled)
	}
	if got[1].TemperatureC == nil || *got[1].TemperatureC != 58.0 {
		t.Fatalf("cpu1 temperature mismatch: %#v", got[1].TemperatureC)
	}
	if got[1].PowerW == nil || *got[1].PowerW != 175.0 {
		t.Fatalf("cpu1 power mismatch: %#v", got[1].PowerW)
	}
	if got[1].Throttled != nil && *got[1].Throttled {
		t.Fatalf("cpu1 throttled mismatch: %#v", got[1].Throttled)
	}
}

func mustWriteFile(t *testing.T, path, content string) {
	t.Helper()
	if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
		t.Fatalf("mkdir %s: %v", path, err)
	}
	if err := os.WriteFile(path, []byte(content), 0644); err != nil {
		t.Fatalf("write %s: %v", path, err)
	}
}
