package service

import "fmt"

type TemplateSlotGroup struct {
	Inputs   []TemplateSlot `json:"inputs"`
	Services []TemplateSlot `json:"services"`
	Outputs  []TemplateSlot `json:"outputs"`
}

type TemplateSlot struct {
	Name        string `json:"name"`
	Type        string `json:"type"`
	Required    bool   `json:"required"`
	Description string `json:"description"`
}

func parseTemplateSlots(raw map[string]any) (TemplateSlotGroup, error) {
	group := TemplateSlotGroup{}
	slotsMap, _ := raw["slots"].(map[string]any)
	if slotsMap == nil {
		return group, nil
	}
	var err error
	if group.Inputs, err = parseTemplateSlotList(slotsMap["inputs"]); err != nil {
		return TemplateSlotGroup{}, fmt.Errorf("parse input slots: %w", err)
	}
	if group.Services, err = parseTemplateSlotList(slotsMap["services"]); err != nil {
		return TemplateSlotGroup{}, fmt.Errorf("parse service slots: %w", err)
	}
	if group.Outputs, err = parseTemplateSlotList(slotsMap["outputs"]); err != nil {
		return TemplateSlotGroup{}, fmt.Errorf("parse output slots: %w", err)
	}
	return group, nil
}

func parseTemplateSlotList(raw any) ([]TemplateSlot, error) {
	items, _ := raw.([]any)
	if len(items) == 0 {
		return nil, nil
	}
	out := make([]TemplateSlot, 0, len(items))
	for _, item := range items {
		slotMap, _ := item.(map[string]any)
		if slotMap == nil {
			return nil, fmt.Errorf("slot entry must be an object")
		}
		slot := TemplateSlot{
			Name:        stringValue(slotMap["name"]),
			Type:        stringValue(slotMap["type"]),
			Required:    boolValue(slotMap["required"], false),
			Description: stringValue(slotMap["description"]),
		}
		if slot.Name == "" {
			return nil, fmt.Errorf("slot name is required")
		}
		if err := validateConfigName(slot.Name); err != nil {
			return nil, fmt.Errorf("invalid slot name %q: %w", slot.Name, err)
		}
		if slot.Type == "" {
			return nil, fmt.Errorf("slot type is required for %s", slot.Name)
		}
		out = append(out, slot)
	}
	return out, nil
}

