package ollama

import "strings"

func ollamaMessagesFromInput(input map[string]any) []ollamaMessage {
	if raw, ok := input["messages"].([]any); ok {
		out := make([]ollamaMessage, 0, len(raw))
		for _, item := range raw {
			m, ok := item.(map[string]any)
			if !ok {
				continue
			}
			role, _ := m["role"].(string)
			content, _ := m["content"].(string)
			thinking, _ := m["thinking"].(string)
			toolName, _ := m["tool_name"].(string)
			role = strings.TrimSpace(role)
			content = strings.TrimSpace(content)
			if role == "" || (content == "" && thinking == "") {
				continue
			}
			out = append(out, ollamaMessage{
				Role:      role,
				Content:   content,
				Thinking:  thinking,
				Images:    anySlice(m["images"]),
				ToolCalls: anySlice(m["tool_calls"]),
				ToolName:  toolName,
			})
		}
		if len(out) > 0 {
			return out
		}
	}
	prompt := strings.TrimSpace(stringInput(input, "prompt"))
	if prompt == "" {
		return nil
	}
	return []ollamaMessage{{Role: "user", Content: prompt}}
}

func ollamaOptionsFromInput(input map[string]any, contextSize int) map[string]any {
	options := map[string]any{}
	if raw, ok := input["options"].(map[string]any); ok {
		for k, v := range raw {
			options[k] = v
		}
	}
	if contextSize > 0 {
		options["num_ctx"] = contextSize // Edge-owned: always overrides request
	}
	if len(options) == 0 {
		return nil
	}
	return options
}

func anySlice(v any) []any {
	if items, ok := v.([]any); ok {
		return items
	}
	return nil
}

func stringInput(input map[string]any, key string) string {
	if input == nil {
		return ""
	}
	if v, ok := input[key].(string); ok {
		return v
	}
	return ""
}

func countMessageWords(messages []ollamaMessage) int {
	n := 0
	for _, msg := range messages {
		n += len(strings.Fields(msg.Content))
	}
	return n
}
