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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
package amp

import (
	"bytes"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/gin-gonic/gin"
)

// mockResponseWriter is a test double for gin.ResponseWriter
type mockResponseWriter struct {
	gin.ResponseWriter
	body       *bytes.Buffer
	headers    http.Header
	statusCode int
	flushed    bool
}

func newMockResponseWriter() *mockResponseWriter {
	return &mockResponseWriter{
		body:    &bytes.Buffer{},
		headers: make(http.Header),
	}
}

func (m *mockResponseWriter) Write(data []byte) (int, error) {
	return m.body.Write(data)
}

func (m *mockResponseWriter) WriteString(s string) (int, error) {
	return m.body.WriteString(s)
}

func (m *mockResponseWriter) Header() http.Header {
	return m.headers
}

func (m *mockResponseWriter) WriteHeader(code int) {
	m.statusCode = code
}

func (m *mockResponseWriter) Status() int {
	return m.statusCode
}

// Flush implements http.Flusher
func (m *mockResponseWriter) Flush() {
	m.flushed = true
}

// TestResponseRewriter_SplitJSONTokensAcrossChunks tests handling of JSON tokens split across chunk boundaries
func TestResponseRewriter_SplitJSONTokensAcrossChunks(t *testing.T) {
	tests := []struct {
		name          string
		originalModel string
		chunks        []string
		expected      string
	}{
		{
			name:          "model field split across chunks",
			originalModel: "original-model",
			chunks: []string{
				`{"mod`,
				`el": "mapped-model", "content": "test"}`,
			},
			expected: `{"model": "original-model", "content": "test"}`,
		},
		{
			name:          "modelVersion split across chunks",
			originalModel: "original-model",
			chunks: []string{
				`{"modelVers`,
				`ion": "mapped-version"}`,
			},
			expected: `{"modelVersion": "original-model"}`,
		},
		{
			name:          "multiple fields with splits",
			originalModel: "original-model",
			chunks: []string{
				`{"model": "mapped`,
				`-model", "modelVersion": "mapped`,
				`-version"}`,
			},
			expected: `{"model": "original-model", "modelVersion": "original-model"}`,
		},
		{
			name:          "empty chunks between data",
			originalModel: "original-model",
			chunks: []string{
				`{"model": "`,
				``, // Empty chunk
				`mapped-model"}`,
			},
			expected: `{"model": "original-model"}`,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			mock := newMockResponseWriter()
			rw := NewResponseRewriter(mock, tt.originalModel)

			// Simulate streaming response
			for _, chunk := range tt.chunks {
				rw.Write([]byte(chunk))
			}
			rw.Flush()

			result := mock.body.String()
			if result != tt.expected {
				t.Errorf("got %q, want %q", result, tt.expected)
			}
		})
	}
}

// TestResponseRewriter_InvalidMalformedJSON tests handling of invalid/malformed JSON
func TestResponseRewriter_InvalidMalformedJSON(t *testing.T) {
	tests := []struct {
		name          string
		originalModel string
		input         string
		shouldPass    bool // Whether the data should pass through
	}{
		{
			name:          "incomplete JSON",
			originalModel: "original",
			input:         `{"model": "mapped`,
			shouldPass:    true,
		},
		{
			name:          "invalid JSON structure",
			originalModel: "original",
			input:         `{"model": "mapped", invalid}`,
			shouldPass:    true,
		},
		{
			name:          "unclosed string",
			originalModel: "original",
			input:         `{"model": "mapped`,
			shouldPass:    true,
		},
		{
			name:          "binary garbage",
			originalModel: "original",
			input:         string([]byte{0x00, 0x01, 0x02, 0xFF}),
			shouldPass:    true,
		},
		{
			name:          "null bytes in JSON",
			originalModel: "original",
			input:         `{"model": "mapped\u0000model"}`,
			shouldPass:    true,
		},
		{
			name:          "deeply nested valid JSON",
			originalModel: "original",
			input:         `{"a": {"b": {"c": {"d": {"model": "mapped"}}}}}`,
			shouldPass:    true,
		},
		{
			name:          "valid JSON without model field",
			originalModel: "original",
			input:         `{"content": "test", "other": "data"}`,
			shouldPass:    true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			mock := newMockResponseWriter()
			rw := NewResponseRewriter(mock, tt.originalModel)

			// For non-streaming, we buffer and flush
			rw.Write([]byte(tt.input))
			rw.Flush()

			result := mock.body.String()

			// Should not panic and should produce some output
			if result == "" && tt.shouldPass {
				t.Error("expected output but got empty string")
			}

			// For valid JSON with model field, verify replacement happened
			if strings.Contains(tt.input, `"model"`) && strings.Contains(tt.input, "mapped") {
				if strings.Contains(result, "mapped") && !strings.Contains(result, `"model": "original"`) {
					t.Logf("Model replacement may not have worked for: %s", tt.name)
				}
			}
		})
	}
}

// TestResponseRewriter_MixedContentTypes tests handling of mixed content types
func TestResponseRewriter_MixedContentTypes(t *testing.T) {
	tests := []struct {
		name          string
		contentType   string
		originalModel string
		input         string
		isStreaming   bool
	}{
		{
			name:          "SSE stream",
			contentType:   "text/event-stream",
			originalModel: "original-model",
			input:         `data: {"model": "mapped-model", "content": "hello"}`,
			isStreaming:   true,
		},
		{
			name:          "JSON response",
			contentType:   "application/json",
			originalModel: "original-model",
			input:         `{"model": "mapped-model", "content": "hello"}`,
			isStreaming:   false,
		},
		{
			name:          "plain text",
			contentType:   "text/plain",
			originalModel: "original-model",
			input:         `model: mapped-model`,
			isStreaming:   false,
		},
		{
			name:          "octet stream",
			contentType:   "application/octet-stream",
			originalModel: "original-model",
			input:         `binary data`,
			isStreaming:   false,
		},
		{
			name:          "multipart form",
			contentType:   "multipart/form-data",
			originalModel: "original-model",
			input:         `--boundary\nContent-Type: application/json\n\n{"model": "mapped-model"}`,
			isStreaming:   false,
		},
		{
			name:          "JSON with stream in body",
			contentType:   "application/json",
			originalModel: "original-model",
			input:         `{"stream": true, "model": "mapped-model"}`,
			isStreaming:   false, // Content-Type determines streaming, not body
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			mock := newMockResponseWriter()
			mock.headers.Set("Content-Type", tt.contentType)
			rw := NewResponseRewriter(mock, tt.originalModel)

			// First write triggers streaming detection
			rw.Write([]byte(tt.input))

			if rw.isStreaming != tt.isStreaming {
				t.Errorf("isStreaming = %v, want %v", rw.isStreaming, tt.isStreaming)
			}

			rw.Flush()

			// Verify output exists
			result := mock.body.String()
			if result == "" {
				t.Error("expected output but got empty string")
			}
		})
	}
}

// TestResponseRewriter_FallbackStrategy tests fallback when rewriting fails
func TestResponseRewriter_FallbackStrategy(t *testing.T) {
	tests := []struct {
		name          string
		originalModel string
		input         []string // Chunks for streaming
		expectError   bool
	}{
		{
			name:          "empty original model - pass through",
			originalModel: "",
			input:         []string{`{"model": "mapped-model"}`},
			expectError:   false,
		},
		{
			name:          "single chunk rewrite success",
			originalModel: "original-model",
			input:         []string{`{"model": "mapped-model"}`},
			expectError:   false,
		},
		{
			name:          "multiple chunks with partial data",
			originalModel: "original-model",
			input: []string{
				`{"model": "mapped`,
				`-model", "content": "test"}`,
			},
			expectError: false,
		},
		{
			name:          "chunk with only whitespace",
			originalModel: "original-model",
			input: []string{
				`   `,
				`{"model": "mapped-model"}`,
			},
			expectError: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			mock := newMockResponseWriter()
			rw := NewResponseRewriter(mock, tt.originalModel)

			// Write all chunks
			for _, chunk := range tt.input {
				_, err := rw.Write([]byte(chunk))
				if err != nil && !tt.expectError {
					t.Errorf("unexpected error: %v", err)
				}
			}

			rw.Flush()

			// Should always produce output (fallback to pass-through)
			result := mock.body.String()
			if result == "" && len(tt.input) > 0 {
				t.Error("expected output but got empty string")
			}
		})
	}
}

// TestResponseRewriter_SSEEdgeCases tests Server-Sent Events edge cases
func TestResponseRewriter_SSEEdgeCases(t *testing.T) {
	tests := []struct {
		name          string
		originalModel string
		chunks        []string
		expected      string
	}{
		{
			name:          "SSE with data prefix",
			originalModel: "original-model",
			chunks: []string{
				`data: {"model": "mapped-model"}`,
			},
			expected: `data: {"model": "original-model"}`,
		},
		{
			name:          "SSE multiple data lines",
			originalModel: "original-model",
			chunks: []string{
				"data: {\"model\": \"mapped-model\"}\n\ndata: {\"model\": \"mapped-model2\"}",
			},
			expected: "data: {\"model\": \"original-model\"}\n\ndata: {\"model\": \"original-model\"}",
		},
		{
			name:          "SSE with event and id",
			originalModel: "original-model",
			chunks: []string{
				"id: 1\nevent: message\ndata: {\"model\": \"mapped-model\"}",
			},
			expected: "id: 1\nevent: message\ndata: {\"model\": \"original-model\"}",
		},
		{
			name:          "SSE data split across chunks",
			originalModel: "original-model",
			chunks: []string{
				`data: {"mod`,
				`el": "mapped-model"}`,
			},
			expected: `data: {"model": "original-model"}`,
		},
		{
			name:          "SSE non-JSON data",
			originalModel: "original-model",
			chunks: []string{
				`data: plain text message`,
			},
			expected: `data: plain text message`,
		},
		{
			name:          "SSE empty data line",
			originalModel: "original-model",
			chunks: []string{
				`data:`,
			},
			expected: `data:`,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			mock := newMockResponseWriter()
			mock.headers.Set("Content-Type", "text/event-stream")
			rw := NewResponseRewriter(mock, tt.originalModel)

			for _, chunk := range tt.chunks {
				rw.Write([]byte(chunk))
			}

			result := mock.body.String()
			if result != tt.expected {
				t.Errorf("got %q, want %q", result, tt.expected)
			}
		})
	}
}

// TestResponseRewriter_ThinkingBlockSuppression tests the thinking block suppression feature
func TestResponseRewriter_ThinkingBlockSuppression(t *testing.T) {
	tests := []struct {
		name          string
		originalModel string
		input         string
		shouldFilter  bool
	}{
		{
			name:          "tool_use with thinking - should filter",
			originalModel: "original-model",
			input: `{
				"content": [
					{"type": "thinking", "thinking": "secret"},
					{"type": "tool_use", "name": "calculator"}
				]
			}`,
			shouldFilter: true,
		},
		{
			name:          "thinking without tool_use - should not filter",
			originalModel: "original-model",
			input: `{
				"content": [
					{"type": "thinking", "thinking": "not secret"}
				]
			}`,
			shouldFilter: false,
		},
		{
			name:          "no content field",
			originalModel: "original-model",
			input:         `{"model": "mapped-model"}`,
			shouldFilter:  false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			mock := newMockResponseWriter()
			rw := NewResponseRewriter(mock, tt.originalModel)

			rw.Write([]byte(tt.input))
			rw.Flush()

			result := mock.body.String()

			// Check if thinking blocks were filtered when they should be
			hasThinking := strings.Contains(result, `"type": "thinking"`)
			hasToolUse := strings.Contains(tt.input, `"type": "tool_use"`)

			if tt.shouldFilter && hasThinking {
				t.Error("thinking blocks should have been filtered but are present")
			}

			if !tt.shouldFilter && hasToolUse && !hasThinking {
				// This might be OK if the thinking was legitimately removed
				t.Logf("Note: thinking blocks were removed even though no tool_use detected")
			}
		})
	}
}

// TestResponseRewriter_ConcurrentWrites tests concurrent write operations
func TestResponseRewriter_ConcurrentWrites(t *testing.T) {
	gin.SetMode(gin.TestMode)

	mock := newMockResponseWriter()
	mock.headers.Set("Content-Type", "application/json")
	rw := NewResponseRewriter(mock, "original-model")

	// Write data that simulates concurrent chunks
	chunks := []string{
		`{"model": "`,
		`mapped`,
		`-model", "`,
		`content": "`,
		`test"}`,
	}

	for _, chunk := range chunks {
		rw.Write([]byte(chunk))
	}
	rw.Flush()

	result := mock.body.String()
	expected := `{"model": "original-model", "content": "test"}`
	if result != expected {
		t.Errorf("got %q, want %q", result, expected)
	}
}

// TestResponseRewriter_LargeResponse tests handling of large responses
func TestResponseRewriter_LargeResponse(t *testing.T) {
	mock := newMockResponseWriter()
	rw := NewResponseRewriter(mock, "original-model")

	// Create a large JSON response
	largeContent := strings.Repeat("a", 100000)
	input := `{"model": "mapped-model", "content": "` + largeContent + `"}`

	rw.Write([]byte(input))
	rw.Flush()

	result := mock.body.String()

	// Should contain the original model
	if !strings.Contains(result, `"model": "original-model"`) {
		t.Error("model replacement failed for large response")
	}

	// Should still contain the large content
	if !strings.Contains(result, largeContent) {
		t.Error("large content was lost")
	}
}

// TestResponseRewriter_EmptyAndNilInputs tests edge cases with empty/nil inputs
func TestResponseRewriter_EmptyAndNilInputs(t *testing.T) {
	tests := []struct {
		name  string
		input []byte
	}{
		{
			name:  "nil input",
			input: nil,
		},
		{
			name:  "empty input",
			input: []byte{},
		},
		{
			name:  "whitespace only",
			input: []byte("   \n\t  "),
		},
		{
			name:  "single brace",
			input: []byte("{"),
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			mock := newMockResponseWriter()
			rw := NewResponseRewriter(mock, "original-model")

			// Should not panic
			rw.Write(tt.input)
			rw.Flush()

			// Result should be safe
			_ = mock.body.String()
		})
	}
}

// TestNewResponseRewriter tests the constructor
func TestNewResponseRewriter(t *testing.T) {
	gin.SetMode(gin.TestMode)
	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)

	rw := NewResponseRewriter(c.Writer, "test-model")

	if rw == nil {
		t.Fatal("NewResponseRewriter returned nil")
	}

	if rw.originalModel != "test-model" {
		t.Errorf("originalModel = %q, want %q", rw.originalModel, "test-model")
	}

	if rw.body == nil {
		t.Error("body buffer is nil")
	}
}

// TestResponseRewriter_FlushBehavior tests Flush method behavior
func TestResponseRewriter_FlushBehavior(t *testing.T) {
	tests := []struct {
		name       string
		isStreaming bool
		writeData  string
		expectFlush bool
	}{
		{
			name:       "flush non-streaming",
			isStreaming: false,
			writeData:  `{"model": "mapped"}`,
			expectFlush: true,
		},
		{
			name:       "flush streaming",
			isStreaming: true,
			writeData:  `data: {"model": "mapped"}`,
			expectFlush: true,
		},
		{
			name:       "flush empty body",
			isStreaming: false,
			writeData:  "",
			expectFlush: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			mock := newMockResponseWriter()
			if tt.isStreaming {
				mock.headers.Set("Content-Type", "text/event-stream")
			}
			rw := NewResponseRewriter(mock, "original")

			if tt.writeData != "" {
				rw.Write([]byte(tt.writeData))
			}

			// Reset flushed flag
			mock.flushed = false

			rw.Flush()

			if tt.expectFlush && !mock.flushed {
				t.Error("expected Flush to be called on underlying writer")
			}
		})
	}
}