package nvidia

import (
	"testing"

	"git.mchus.pro/mchus/logpile/internal/models"
)

func TestApplyInventoryPCIIDsAndNVFlashFirmware(t *testing.T) {
	result := &models.AnalysisResult{
		Hardware: &models.HardwareConfig{
			GPUs: []models.GPU{
				{
					Slot:     "GPUSXM5",
					DeviceID: 0x2335,
				},
			},
			PCIeDevices: []models.PCIeDevice{
				{
					Slot:     "NVSWITCHNVSWITCH2",
					DeviceID: 0x22a3,
				},
			},
		},
	}

	inventoryLog := []byte(`
GPU_SXM5_PCIID: 0000:ba:00.0
NVSWITCH_NVSWITCH2_PCIID: 0000:07:00.0
`)

	nvflashLog := []byte(`
Adapter: Graphics Device      (10DE,2335,10DE,18BE) S:00,B:BA,D:00,F:00
Version               : 96.00.D0.00.03
Board ID              : 0x053C
Vendor ID             : 0x10DE
Device ID             : 0x2335
Hierarchy ID          : Normal Board
Chip SKU              : 895-0
Project               : G520-0280

Adapter: Graphics Device      (10DE,22A3,10DE,1796) S:00,B:07,D:00,F:00
Version               : 96.10.6D.00.01
Board ID              : 0x03B7
Vendor ID             : 0x10DE
Device ID             : 0x22A3
Hierarchy ID          : Normal Board
Chip SKU              : 890-0
Project               : 5612-0002
`)

	if err := ApplyInventoryPCIIDs(inventoryLog, result); err != nil {
		t.Fatalf("ApplyInventoryPCIIDs failed: %v", err)
	}
	if err := ParseNVFlashVerboseLog(nvflashLog, result); err != nil {
		t.Fatalf("ParseNVFlashVerboseLog failed: %v", err)
	}

	if got := result.Hardware.GPUs[0].BDF; got != "0000:ba:00.0" {
		t.Fatalf("expected GPU BDF 0000:ba:00.0, got %q", got)
	}
	if got := result.Hardware.GPUs[0].Firmware; got != "96.00.D0.00.03" {
		t.Fatalf("expected GPU firmware 96.00.D0.00.03, got %q", got)
	}

	if got := result.Hardware.PCIeDevices[0].BDF; got != "0000:07:00.0" {
		t.Fatalf("expected NVSwitch BDF 0000:07:00.0, got %q", got)
	}
	if got := result.Hardware.PCIeDevices[0].PartNumber; got != "965-25612-0002-000" {
		t.Fatalf("expected NVSwitch part number 965-25612-0002-000, got %q", got)
	}

	if len(result.Hardware.Firmware) == 0 {
		t.Fatalf("expected firmware entries to be populated from nvflash log")
	}

	hasGPUFW := false
	hasNVSwitchFW := false
	for _, fw := range result.Hardware.Firmware {
		if fw.Version == "96.00.D0.00.03" {
			hasGPUFW = true
		}
		if fw.Version == "96.10.6D.00.01" {
			hasNVSwitchFW = true
		}
	}
	if !hasGPUFW {
		t.Fatalf("expected GPU firmware version 96.00.D0.00.03 in hardware firmware list")
	}
	if !hasNVSwitchFW {
		t.Fatalf("expected NVSwitch firmware version 96.10.6D.00.01 in hardware firmware list")
	}
}
