package iace

import "sort"

// EN ISO 12100 hazard-group ordering for the hazard log. Without it the log is
// returned in pattern-firing order, which reads as a jumble. This groups the
// hazards top-down by type (A. Mechanisch, B. Elektrisch, C. Thermisch, …),
// matching the frontend CATEGORY_LABELS.
var isoCategoryRank = map[string]int{
	// A. Mechanisch
	"mechanical_hazard": 10, "mechanical": 10, "maintenance_hazard": 11,
	// B. Elektrisch
	"electrical_hazard": 20, "electrical": 20, "emc_hazard": 21,
	// C. Thermisch
	"thermal_hazard": 30, "thermal": 30, "high_temperature": 31, "fire_explosion": 32,
	// D. Pneumatik / Hydraulik
	"pneumatic_hydraulic": 40,
	// E. Laerm / Vibration
	"noise_hazard": 50, "noise_vibration": 50, "vibration_hazard": 51,
	// F. Ergonomie
	"ergonomic_hazard": 60, "ergonomic": 60,
	// G. Stoffe / Umwelt
	"material_environmental": 70, "chemical_risk": 71, "radiation_hazard": 72,
	// H. Software / Steuerung (funktionale Sicherheit)
	"software_control": 80, "software_fault": 80, "safety_function_failure": 81,
	"configuration_error": 82, "sensor_fault": 83, "hmi_error": 84, "mode_confusion": 85,
	"communication_failure": 86, "update_failure": 87,
	// I. Cyber / Netzwerk (zur Ordnungs-Vollstaendigkeit; im CE-Log ausgeschlossen)
	"unauthorized_access": 90, "firmware_corruption": 91, "cyber_resilience": 92,
	"cyber_network": 93, "logging_audit_failure": 94, "sensor_spoofing": 95,
	// J. KI-spezifisch
	"ai_specific": 100, "ai_misclassification": 100, "false_classification": 100,
	"model_drift": 100, "data_poisoning": 100, "unintended_bias": 100,
}

func categoryRank(cat string) int {
	if r, ok := isoCategoryRank[cat]; ok {
		return r
	}
	return 999 // unknown categories last
}

// SortHazardsByISO12100 groups hazards by ISO 12100 hazard group. Stable: the
// relative order within a group (creation/priority order from the engine) is
// preserved.
func SortHazardsByISO12100(hazards []Hazard) {
	sort.SliceStable(hazards, func(i, j int) bool {
		return categoryRank(hazards[i].Category) < categoryRank(hazards[j].Category)
	})
}
