package server

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

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

func TestReanimatorExport_RedfishExampleDoesNotDuplicateCPUs(t *testing.T) {
	payload, err := os.ReadFile(filepath.Join("..", "..", "example", "2026-03-11 (SYS-821GE-TNHR) - A514359X5C08846.zip"))
	if err != nil {
		t.Fatalf("read example bundle: %v", err)
	}

	rawPkg, ok, err := parseRawExportBundle(payload)
	if err != nil {
		t.Fatalf("parse raw export bundle: %v", err)
	}
	if !ok {
		t.Fatalf("example bundle was not recognized as raw export bundle")
	}

	s := &Server{}
	result, vendor, err := s.reanalyzeRawExportPackage(rawPkg)
	if err != nil {
		t.Fatalf("reanalyze raw export bundle: %v", err)
	}
	if vendor != "redfish" {
		t.Fatalf("expected redfish vendor, got %q", vendor)
	}
	if result == nil || result.Hardware == nil {
		t.Fatalf("expected parsed hardware result")
	}
	if got := len(result.Hardware.CPUs); got != 2 {
		t.Fatalf("expected 2 CPUs after replay, got %d", got)
	}

	reanimatorData, err := exporter.ConvertToReanimator(result)
	if err != nil {
		t.Fatalf("ConvertToReanimator: %v", err)
	}
	if got := len(reanimatorData.Hardware.CPUs); got != 2 {
		t.Fatalf("expected 2 CPUs in reanimator export, got %d", got)
	}
	for i, cpu := range reanimatorData.Hardware.CPUs {
		if cpu.SerialNumber != "" {
			t.Fatalf("expected CPU %d serial to stay empty, got %q", i, cpu.SerialNumber)
		}
	}
	for _, dev := range reanimatorData.Hardware.PCIeDevices {
		joined := strings.ToLower(strings.Join([]string{dev.Slot, dev.Model, dev.DeviceClass}, " "))
		if strings.Contains(joined, "nvme") || strings.Contains(joined, "ssd") || strings.Contains(joined, "disk") {
			t.Fatalf("expected storage endpoint to stay out of pcie export, got %+v", dev)
		}
		if strings.EqualFold(dev.Model, "Network Device View") {
			t.Fatalf("expected placeholder network model to be replaced, got %+v", dev)
		}
		if strings.Contains(dev.SerialNumber, "-PCIE-") {
			t.Fatalf("expected no synthetic pcie serials, got %+v", dev)
		}
		if isNumericOnly(dev.Slot) && dev.DeviceClass == "NetworkController" && dev.Model == "" && dev.SerialNumber == "" {
			t.Fatalf("expected placeholder numeric-slot network export to be skipped, got %+v", dev)
		}
	}
}

func isNumericOnly(v string) bool {
	v = strings.TrimSpace(v)
	if v == "" {
		return false
	}
	for _, r := range v {
		if r < '0' || r > '9' {
			return false
		}
	}
	return true
}
