package clients

import "testing"

func TestOpenAIChatOfficialParametersSurviveBoundary(t *testing.T) {
	body := map[string]any{}
	for key := range openAIChatRequestParameters {
		body[key] = "sentinel-" + key
	}
	body["conversationId"] = "internal"
	body["future_official_field"] = map[string]any{"nested": []any{"must-survive"}}

	filtered := FilterOpenAIChatRequestBody(body)
	for key := range openAIChatRequestParameters {
		if _, ok := filtered[key]; !ok {
			t.Fatalf("official Chat parameter %q was removed", key)
		}
	}
	if _, ok := filtered["future_official_field"]; !ok {
		t.Fatal("future Chat field was removed at the upstream boundary")
	}
	for _, key := range []string{"conversationId"} {
		if _, ok := filtered[key]; ok {
			t.Fatalf("internal/unknown parameter %q leaked upstream", key)
		}
	}
}

func TestOpenAIResponsesOfficialParametersSurviveBoundary(t *testing.T) {
	body := map[string]any{}
	for key := range openAIResponsesRequestParameters {
		body[key] = "sentinel-" + key
	}
	body["request_id"] = "internal"
	body["future_official_field"] = map[string]any{"nested": []any{"must-survive"}}

	filtered := FilterOpenAIResponsesRequestBody(body)
	for key := range openAIResponsesRequestParameters {
		if _, ok := filtered[key]; !ok {
			t.Fatalf("official Responses parameter %q was removed", key)
		}
	}
	if _, ok := filtered["future_official_field"]; !ok {
		t.Fatal("future Responses field was removed at the upstream boundary")
	}
	for _, key := range []string{"request_id"} {
		if _, ok := filtered[key]; ok {
			t.Fatalf("internal/unknown parameter %q leaked upstream", key)
		}
	}
}

func TestValidateOpenAIRequestParametersAcceptsFutureTopLevelField(t *testing.T) {
	if err := ValidateOpenAIRequestParameters("responses", map[string]any{"model": "demo", "input": "hello", "future_official_field": true}); err != nil {
		t.Fatalf("future Responses fields must remain forward compatible, got %v", err)
	}
	if err := ValidateOpenAIRequestParameters("responses", map[string]any{"model": "demo", "input": "hello", "messages": []any{}, "request_id": "internal"}); err != nil {
		t.Fatalf("expected controlled Responses extensions to remain accepted, got %v", err)
	}
}

func TestValidateOpenAIRequestParametersAcceptsInternalSimulationAndAffinityFields(t *testing.T) {
	body := map[string]any{
		"model": "demo", "messages": []any{}, "simulation": true,
		"simulationDurationMs": 5, "simulationUsage": map[string]any{"inputTokens": 10},
		"cacheAffinityKey": "conversation-1",
	}
	if err := ValidateOpenAIRequestParameters("chat.completions", body); err != nil {
		t.Fatalf("expected documented gateway extensions to remain accepted, got %v", err)
	}
	filtered := FilterOpenAIChatRequestBody(body)
	for _, key := range []string{"simulation", "simulationDurationMs", "simulationUsage", "cacheAffinityKey"} {
		if _, ok := filtered[key]; ok {
			t.Fatalf("gateway-only field %q leaked upstream", key)
		}
	}
}

func TestResponsesFallbackMapsEquivalentCurrentParameters(t *testing.T) {
	body, err := ResponsesRequestToChat(map[string]any{
		"input": "hello", "store": false, "metadata": map[string]any{"trace": "1"},
		"request_id": "internal-request", "platform_id": "internal-platform",
		"moderation": map[string]any{"type": "auto"}, "prompt_cache_key": "cache-key",
		"prompt_cache_options": map[string]any{"type": "ephemeral"}, "prompt_cache_retention": "in_memory",
		"safety_identifier": "safe", "service_tier": "priority", "top_logprobs": 3,
		"stream_options": map[string]any{"include_usage": true},
		"text":           map[string]any{"format": map[string]any{"type": "text"}, "verbosity": "low"},
	}, nil)
	if err != nil {
		t.Fatalf("convert Responses request: %v", err)
	}
	for _, key := range []string{"store", "metadata", "moderation", "prompt_cache_key", "prompt_cache_options", "prompt_cache_retention", "safety_identifier", "service_tier", "top_logprobs", "stream_options", "verbosity"} {
		if _, ok := body[key]; !ok {
			t.Fatalf("equivalent parameter %q was not mapped", key)
		}
	}
	if body["logprobs"] != true {
		t.Fatalf("top_logprobs fallback must enable Chat logprobs: %+v", body)
	}
	for _, key := range []string{"request_id", "platform_id"} {
		if _, ok := body[key]; ok {
			t.Fatalf("internal Responses parameter %q leaked into Chat fallback: %+v", key, body)
		}
	}
}

func TestNormalizeChatRequestPreservesCustomAndLegacyFunctionCall(t *testing.T) {
	legacy := map[string]any{"name": "legacy", "arguments": "{\"x\":1}"}
	custom := map[string]any{
		"id": "call_custom", "type": "custom",
		"custom": map[string]any{"name": "shell", "input": "pwd"},
	}
	body := NormalizeChatCompletionRequestBody(map[string]any{"messages": []any{map[string]any{
		"role": "assistant", "content": nil, "function_call": legacy, "tool_calls": []any{custom},
	}}})
	messages, _ := body["messages"].([]any)
	message, _ := messages[0].(map[string]any)
	if got, ok := message["function_call"].(map[string]any); !ok || got["name"] != "legacy" || got["arguments"] != "{\"x\":1}" {
		t.Fatalf("legacy function_call changed: %+v", message)
	}
	toolCalls, _ := message["tool_calls"].([]any)
	got, _ := toolCalls[0].(map[string]any)
	gotCustom, _ := got["custom"].(map[string]any)
	if got["type"] != "custom" || got["id"] != "call_custom" || gotCustom["name"] != "shell" || gotCustom["input"] != "pwd" || got["function"] != nil {
		t.Fatalf("standard custom tool call changed: %+v", got)
	}
}

func TestEnsureOpenAIStreamUsageDoesNotOverrideCallerChoice(t *testing.T) {
	body := map[string]any{"stream_options": map[string]any{"include_usage": false, "include_obfuscation": false}}
	ensureOpenAIStreamUsage(body, "chat.completions", true)
	options, _ := body["stream_options"].(map[string]any)
	if options["include_usage"] != false || options["include_obfuscation"] != false {
		t.Fatalf("caller stream options were changed: %+v", options)
	}
}
