package store

import (
	"slices"
	"testing"
)

func TestEffectivePlatformModelCapabilitiesDeepMergesNestedObjects(t *testing.T) {
	baseLevels := []any{"none", "minimal", "low"}
	baseTextGenerate := map[string]any{
		"max_context_tokens":   204800,
		"supportThinking":      true,
		"thinkingEffortLevels": baseLevels,
	}
	overrideTextGenerate := map[string]any{
		"max_thinking_tokens":       131072,
		"supportThinking":           false,
		"supportThinkingModeSwitch": true,
	}

	capabilities := EffectivePlatformModelCapabilities(
		map[string]any{
			"originalTypes": []any{"text_generate"},
			"text_generate": baseTextGenerate,
		},
		map[string]any{
			"text_generate": overrideTextGenerate,
		},
	)

	textGenerate, ok := capabilities["text_generate"].(map[string]any)
	if !ok {
		t.Fatalf("expected text_generate capabilities object, got %#v", capabilities["text_generate"])
	}
	if textGenerate["max_context_tokens"] != 204800 {
		t.Fatalf("expected base max_context_tokens to be preserved, got %#v", textGenerate["max_context_tokens"])
	}
	if textGenerate["max_thinking_tokens"] != 131072 {
		t.Fatalf("expected override max_thinking_tokens to be applied, got %#v", textGenerate["max_thinking_tokens"])
	}
	if textGenerate["supportThinking"] != false {
		t.Fatalf("expected override supportThinking false to win, got %#v", textGenerate["supportThinking"])
	}
	if textGenerate["supportThinkingModeSwitch"] != true {
		t.Fatalf("expected override supportThinkingModeSwitch true, got %#v", textGenerate["supportThinkingModeSwitch"])
	}
	assertAnyStringList(t, textGenerate["thinkingEffortLevels"], []string{"none", "minimal", "low"})

	baseTextGenerate["max_context_tokens"] = 1
	overrideTextGenerate["max_thinking_tokens"] = 2
	baseLevels[0] = "changed"

	if textGenerate["max_context_tokens"] != 204800 {
		t.Fatalf("expected merged capabilities to be detached from base mutations, got %#v", textGenerate["max_context_tokens"])
	}
	if textGenerate["max_thinking_tokens"] != 131072 {
		t.Fatalf("expected merged capabilities to be detached from override mutations, got %#v", textGenerate["max_thinking_tokens"])
	}
	assertAnyStringList(t, textGenerate["thinkingEffortLevels"], []string{"none", "minimal", "low"})
}

func assertAnyStringList(t *testing.T, got any, want []string) {
	t.Helper()
	items, ok := got.([]any)
	if !ok {
		t.Fatalf("expected string list %v, got %#v", want, got)
	}
	normalized := make([]string, 0, len(items))
	for _, item := range items {
		text, ok := item.(string)
		if !ok {
			t.Fatalf("expected string list %v, got non-string item %#v in %#v", want, item, got)
		}
		normalized = append(normalized, text)
	}
	if !slices.Equal(normalized, want) {
		t.Fatalf("expected string list %v, got %v", want, normalized)
	}
}
