package iace

import (
	"sort"
	"strings"
)

// MachineTypeInfo is one entry of the controlled machine-type vocabulary the
// pattern engine gates on. The project's machine type MUST come from this list
// (a form dropdown), otherwise the engine's machine-type gate either floods
// (empty) or under-covers (a free-text value that matches no pattern).
type MachineTypeInfo struct {
	Key     string `json:"key"`
	LabelDE string `json:"label_de"`
	Group   string `json:"group"`
}

// machineTypeLabels gives German labels + UI groups for the machine-type keys
// used in pattern MachineTypes. Keys not listed here still appear (derived from
// the pattern set) with a humanised fallback label, so the vocabulary never
// silently drops a gated machine class.
var machineTypeLabels = map[string]MachineTypeInfo{
	// Heben & Fördern
	"lift":       {LabelDE: "Hebevorrichtung / Hubgerät", Group: "Heben & Fördern"},
	"elevator":   {LabelDE: "Aufzug", Group: "Heben & Fördern"},
	"escalator":  {LabelDE: "Fahrtreppe / Rolltreppe", Group: "Heben & Fördern"},
	"crane":      {LabelDE: "Kran", Group: "Heben & Fördern"},
	"conveyor":   {LabelDE: "Förderanlage / Stetigförderer", Group: "Heben & Fördern"},
	"packaging":  {LabelDE: "Verpackungsmaschine", Group: "Heben & Fördern"},
	"bottling":   {LabelDE: "Abfüllanlage", Group: "Heben & Fördern"},
	// Pressen & Umformen
	"press":           {LabelDE: "Presse (allgemein)", Group: "Pressen & Umformen"},
	"hydraulic_press": {LabelDE: "Hydraulikpresse", Group: "Pressen & Umformen"},
	"mechanical_press": {LabelDE: "Mechanische Presse", Group: "Pressen & Umformen"},
	"printing_press":  {LabelDE: "Druckmaschine", Group: "Pressen & Umformen"},
	// Zerspanung & Bearbeitung
	"cnc":          {LabelDE: "CNC-Bearbeitungszentrum", Group: "Zerspanung & Bearbeitung"},
	"lathe":        {LabelDE: "Drehmaschine", Group: "Zerspanung & Bearbeitung"},
	"milling":      {LabelDE: "Fräsmaschine", Group: "Zerspanung & Bearbeitung"},
	"grinding":     {LabelDE: "Schleifmaschine", Group: "Zerspanung & Bearbeitung"},
	"circular_saw": {LabelDE: "Kreissäge", Group: "Zerspanung & Bearbeitung"},
	"metalworking": {LabelDE: "Metallbearbeitung", Group: "Zerspanung & Bearbeitung"},
	"woodworking":  {LabelDE: "Holzbearbeitung", Group: "Zerspanung & Bearbeitung"},
	"welding":      {LabelDE: "Schweißanlage", Group: "Zerspanung & Bearbeitung"},
	// Roboter & Automation
	"robotics_cobot":    {LabelDE: "Roboterzelle / Cobot", Group: "Roboter & Automation"},
	"rotary_transfer":   {LabelDE: "Rundtaktmaschine", Group: "Roboter & Automation"},
	"autonomous_vehicle": {LabelDE: "Fahrerloses Transportsystem (FTS/AGV)", Group: "Roboter & Automation"},
	// Kunststoff, Glas & Textil
	"textile":   {LabelDE: "Textilmaschine", Group: "Kunststoff, Glas & Textil"},
	"spinning":  {LabelDE: "Spinnmaschine", Group: "Kunststoff, Glas & Textil"},
	"weaving":   {LabelDE: "Webmaschine", Group: "Kunststoff, Glas & Textil"},
	"knitting":  {LabelDE: "Strickmaschine", Group: "Kunststoff, Glas & Textil"},
	"dyeing":    {LabelDE: "Färbemaschine", Group: "Kunststoff, Glas & Textil"},
	"carding":   {LabelDE: "Kardiermaschine", Group: "Kunststoff, Glas & Textil"},
	"twisting":  {LabelDE: "Zwirnmaschine", Group: "Kunststoff, Glas & Textil"},
	"stenter":   {LabelDE: "Spannrahmen", Group: "Kunststoff, Glas & Textil"},
	"finishing": {LabelDE: "Veredelungsmaschine", Group: "Kunststoff, Glas & Textil"},
	// Bau & mobile Maschinen
	"construction": {LabelDE: "Baumaschine", Group: "Bau & mobile Maschinen"},
	"excavator":    {LabelDE: "Bagger", Group: "Bau & mobile Maschinen"},
	"tractor":      {LabelDE: "Traktor", Group: "Bau & mobile Maschinen"},
	"harvester":    {LabelDE: "Erntemaschine", Group: "Bau & mobile Maschinen"},
	"combine":      {LabelDE: "Mähdrescher", Group: "Bau & mobile Maschinen"},
	"agricultural": {LabelDE: "Landmaschine", Group: "Bau & mobile Maschinen"},
	"forestry":     {LabelDE: "Forstmaschine", Group: "Bau & mobile Maschinen"},
	"sprayer":      {LabelDE: "Spritzgerät / Sprühmaschine", Group: "Bau & mobile Maschinen"},
	// Medizin & Labor
	"medical_device":  {LabelDE: "Medizingerät (allgemein)", Group: "Medizin & Labor"},
	"patient_monitor": {LabelDE: "Patientenmonitor", Group: "Medizin & Labor"},
	"infusion_pump":   {LabelDE: "Infusionspumpe", Group: "Medizin & Labor"},
	"ventilator":      {LabelDE: "Beatmungsgerät", Group: "Medizin & Labor"},
	"laser_device":    {LabelDE: "Lasergerät", Group: "Medizin & Labor"},
	"pharmaceutical":  {LabelDE: "Pharmamaschine", Group: "Medizin & Labor"},
	// Prozess & Sonstige
	"food_processing":   {LabelDE: "Lebensmittelmaschine", Group: "Prozess & Sonstige"},
	"pump":              {LabelDE: "Pumpe", Group: "Prozess & Sonstige"},
	"compressor":        {LabelDE: "Kompressor", Group: "Prozess & Sonstige"},
	"surface_treatment": {LabelDE: "Oberflächenbehandlung", Group: "Prozess & Sonstige"},
	"spray_booth":       {LabelDE: "Lackierkabine", Group: "Prozess & Sonstige"},
	"electroplating":    {LabelDE: "Galvanik", Group: "Prozess & Sonstige"},
	"grain_handling":    {LabelDE: "Getreide- / Schüttgutanlage", Group: "Prozess & Sonstige"},
	"glass_washing":     {LabelDE: "Glaswaschanlage", Group: "Prozess & Sonstige"},
	"laundry":           {LabelDE: "Wäschereimaschine", Group: "Prozess & Sonstige"},
	"playground":        {LabelDE: "Spielplatzgerät", Group: "Prozess & Sonstige"},
	"wind_turbine":      {LabelDE: "Windenergieanlage", Group: "Prozess & Sonstige"},
	"general_industry":  {LabelDE: "Allgemeine Industriemaschine", Group: "Prozess & Sonstige"},
}

// MachineTypeVocabulary returns the controlled machine-type vocabulary derived
// from the live pattern set (so it never drifts from what the engine gates on),
// each with a German label + UI group. Sorted by group, then label.
func MachineTypeVocabulary() []MachineTypeInfo {
	seen := make(map[string]bool)
	for _, p := range AllPatterns() {
		for _, mt := range p.MachineTypes {
			seen[mt] = true
		}
	}
	out := make([]MachineTypeInfo, 0, len(seen))
	for key := range seen {
		info, ok := machineTypeLabels[key]
		if !ok {
			info = MachineTypeInfo{LabelDE: humanizeMachineType(key), Group: "Sonstige"}
		}
		info.Key = key
		out = append(out, info)
	}
	sort.Slice(out, func(i, j int) bool {
		if out[i].Group != out[j].Group {
			return out[i].Group < out[j].Group
		}
		return out[i].LabelDE < out[j].LabelDE
	})
	return out
}

func humanizeMachineType(key string) string {
	parts := strings.Split(key, "_")
	for i, p := range parts {
		if p != "" {
			parts[i] = strings.ToUpper(p[:1]) + p[1:]
		}
	}
	return strings.Join(parts, " ")
}
