File size: 27,368 Bytes
93c9664
 
 
 
29ed661
93c9664
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29ed661
93c9664
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29ed661
93c9664
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29ed661
93c9664
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29ed661
93c9664
 
 
 
29ed661
 
 
 
 
 
 
 
93c9664
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdb8925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29ed661
 
fdb8925
 
 
 
 
 
 
 
 
 
 
 
 
29ed661
fdb8925
29ed661
fdb8925
 
 
 
 
29ed661
fdb8925
29ed661
fdb8925
29ed661
 
fdb8925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29ed661
fdb8925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29ed661
 
fdb8925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29ed661
 
 
fdb8925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29ed661
 
 
 
 
 
 
 
 
 
 
fdb8925
 
 
29ed661
fdb8925
 
 
 
29ed661
 
fdb8925
 
 
 
 
 
 
 
 
 
29ed661
fdb8925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29ed661
 
fdb8925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29ed661
fdb8925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
"""
Tests for V4 Structured Summarization API endpoints.
"""

import contextlib
import json
from unittest.mock import patch

import pytest
from fastapi.testclient import TestClient


def test_v4_scrape_and_summarize_stream_success(client: TestClient):
    """Test successful V4 scrape-and-summarize flow with structured output."""
    # Mock article scraping
    with patch(
        "app.services.article_scraper.article_scraper_service.scrape_article"
    ) as mock_scrape:
        mock_scrape.return_value = {
            "text": "This is a test article about artificial intelligence and machine learning. "
            * 20,
            "title": "AI Revolution",
            "author": "Tech Writer",
            "date": "2024-11-26",
            "site_name": "Tech News",
            "url": "https://example.com/ai-article",
            "method": "static",
            "scrape_time_ms": 350.5,
        }

        # Mock V4 structured summarization streaming
        async def mock_stream(*args, **kwargs):
            # Stream JSON tokens
            yield {"content": '{"title": "', "done": False, "tokens_used": 2}
            yield {"content": "AI Revolution", "done": False, "tokens_used": 5}
            yield {"content": '", "main_summary": "', "done": False, "tokens_used": 8}
            yield {
                "content": "AI is transforming industries",
                "done": False,
                "tokens_used": 15,
            }
            yield {
                "content": '", "key_points": ["AI", "ML", "Data"],',
                "done": False,
                "tokens_used": 25,
            }
            yield {
                "content": ' "category": "Tech", "sentiment": "positive", "read_time_min": 5}',
                "done": False,
                "tokens_used": 35,
            }
            yield {
                "content": "",
                "done": True,
                "tokens_used": 35,
                "latency_ms": 3500.0,
            }

        with patch(
            "app.services.structured_summarizer.structured_summarizer_service.summarize_structured_stream",
            side_effect=mock_stream,
        ):
            response = client.post(
                "/api/v4/scrape-and-summarize/stream",
                json={
                    "url": "https://example.com/ai-article",
                    "style": "executive",
                    "max_tokens": 1024,
                    "include_metadata": True,
                },
            )

            assert response.status_code == 200
            assert (
                response.headers["content-type"] == "text/event-stream; charset=utf-8"
            )

            # Parse SSE stream
            events = []
            for line in response.text.split("\n"):
                if line.startswith("data: "):
                    with contextlib.suppress(json.JSONDecodeError):
                        events.append(json.loads(line[6:]))

            assert len(events) > 0

            # Check metadata event
            metadata_events = [e for e in events if e.get("type") == "metadata"]
            assert len(metadata_events) == 1
            metadata = metadata_events[0]["data"]
            assert metadata["title"] == "AI Revolution"
            assert metadata["style"] == "executive"
            assert "scrape_latency_ms" in metadata

            # Check content events
            content_events = [
                e for e in events if "content" in e and not e.get("done", False)
            ]
            assert len(content_events) >= 5

            # Check done event
            done_events = [e for e in events if e.get("done") is True]
            assert len(done_events) == 1


def test_v4_text_mode_success(client: TestClient):
    """Test V4 with direct text input (no scraping)."""

    async def mock_stream(*args, **kwargs):
        yield {
            "content": '{"title": "Summary", "main_summary": "Test"}',
            "done": False,
            "tokens_used": 10,
        }
        yield {"content": "", "done": True, "tokens_used": 10, "latency_ms": 2000.0}

    with patch(
        "app.services.structured_summarizer.structured_summarizer_service.summarize_structured_stream",
        side_effect=mock_stream,
    ):
        response = client.post(
            "/api/v4/scrape-and-summarize/stream",
            json={
                "text": "This is a test article about technology. " * 10,
                "style": "skimmer",
                "include_metadata": True,
            },
        )

        assert response.status_code == 200

        # Parse SSE stream
        events = []
        for line in response.text.split("\n"):
            if line.startswith("data: "):
                with contextlib.suppress(json.JSONDecodeError):
                    events.append(json.loads(line[6:]))

        # Check metadata event for text mode
        metadata_events = [e for e in events if e.get("type") == "metadata"]
        assert len(metadata_events) == 1
        metadata = metadata_events[0]["data"]
        assert metadata["input_type"] == "text"
        assert metadata["style"] == "skimmer"


def test_v4_invalid_url(client: TestClient):
    """Test V4 error handling for invalid URL."""
    response = client.post(
        "/api/v4/scrape-and-summarize/stream",
        json={"url": "not-a-valid-url", "style": "executive"},
    )

    assert response.status_code == 422  # Validation error


def test_v4_localhost_blocked(client: TestClient):
    """Test V4 SSRF protection - localhost blocked."""
    response = client.post(
        "/api/v4/scrape-and-summarize/stream",
        json={"url": "http://localhost:8000/secret", "style": "executive"},
    )

    assert response.status_code == 422
    assert "localhost" in response.text.lower()


def test_v4_private_ip_blocked(client: TestClient):
    """Test V4 SSRF protection - private IPs blocked."""
    response = client.post(
        "/api/v4/scrape-and-summarize/stream",
        json={"url": "http://10.0.0.1/secret", "style": "executive"},
    )

    assert response.status_code == 422
    assert "private" in response.text.lower()


def test_v4_insufficient_content(client: TestClient):
    """Test V4 error when extracted content is insufficient."""
    with patch(
        "app.services.article_scraper.article_scraper_service.scrape_article"
    ) as mock_scrape:
        mock_scrape.return_value = {
            "text": "Too short",  # Less than 100 chars
            "title": "Test",
            "url": "https://example.com/short",
            "method": "static",
            "scrape_time_ms": 100.0,
        }

        response = client.post(
            "/api/v4/scrape-and-summarize/stream",
            json={"url": "https://example.com/short"},
        )

        assert response.status_code == 422
        assert "insufficient" in response.text.lower()


def test_v4_scrape_failure(client: TestClient):
    """Test V4 error handling when scraping fails."""
    with patch(
        "app.services.article_scraper.article_scraper_service.scrape_article"
    ) as mock_scrape:
        mock_scrape.side_effect = Exception("Connection timeout")

        response = client.post(
            "/api/v4/scrape-and-summarize/stream",
            json={"url": "https://example.com/timeout"},
        )

        assert response.status_code == 502


def test_v4_style_validation(client: TestClient):
    """Test V4 style parameter validation."""
    # Valid styles should work (validated by Pydantic enum)
    response = client.post(
        "/api/v4/scrape-and-summarize/stream",
        json={
            "text": "Test article content. " * 10,
            "style": "eli5",  # Valid
        },
    )
    # Will fail because model not loaded, but validation passes
    assert response.status_code in [200, 500]

    # Invalid style should fail validation
    response = client.post(
        "/api/v4/scrape-and-summarize/stream",
        json={
            "text": "Test article content. " * 10,
            "style": "invalid_style",  # Invalid
        },
    )
    assert response.status_code == 422


def test_v4_missing_url_and_text(client: TestClient):
    """Test V4 validation requires either URL or text."""
    response = client.post(
        "/api/v4/scrape-and-summarize/stream",
        json={"style": "executive"},  # Missing both url and text
    )

    assert response.status_code == 422
    assert "url" in response.text.lower() or "text" in response.text.lower()


def test_v4_both_url_and_text(client: TestClient):
    """Test V4 validation rejects both URL and text."""
    response = client.post(
        "/api/v4/scrape-and-summarize/stream",
        json={
            "url": "https://example.com/test",
            "text": "Test content",  # Both provided - invalid
            "style": "executive",
        },
    )

    assert response.status_code == 422


def test_v4_max_tokens_validation(client: TestClient):
    """Test V4 max_tokens parameter validation."""
    # Valid range (128-2048)
    response = client.post(
        "/api/v4/scrape-and-summarize/stream",
        json={
            "text": "Test article. " * 10,
            "max_tokens": 512,  # Valid
        },
    )
    assert response.status_code in [200, 500]

    # Below minimum
    response = client.post(
        "/api/v4/scrape-and-summarize/stream",
        json={
            "text": "Test article. " * 10,
            "max_tokens": 50,  # Below 128
        },
    )
    assert response.status_code == 422

    # Above maximum
    response = client.post(
        "/api/v4/scrape-and-summarize/stream",
        json={
            "text": "Test article. " * 10,
            "max_tokens": 3000,  # Above 2048
        },
    )
    assert response.status_code == 422


def test_v4_text_length_validation(client: TestClient):
    """Test V4 text length validation."""
    # Too short
    response = client.post(
        "/api/v4/scrape-and-summarize/stream",
        json={
            "text": "Short",  # Less than 50 chars
            "style": "executive",
        },
    )
    assert response.status_code == 422

    # Valid length
    response = client.post(
        "/api/v4/scrape-and-summarize/stream",
        json={
            "text": "This is a valid length article for testing purposes. " * 2,
            "style": "executive",
        },
    )
    assert response.status_code in [200, 500]


@pytest.mark.asyncio
async def test_v4_sse_headers(client: TestClient):
    """Test V4 SSE response headers."""

    async def mock_stream(*args, **kwargs):
        yield {"content": "test", "done": False, "tokens_used": 1}
        yield {"content": "", "done": True, "latency_ms": 1000.0}

    with (
        patch(
            "app.services.article_scraper.article_scraper_service.scrape_article"
        ) as mock_scrape,
        patch(
            "app.services.structured_summarizer.structured_summarizer_service.summarize_structured_stream",
            side_effect=mock_stream,
        ),
    ):
        mock_scrape.return_value = {
            "text": "Test article content. " * 20,
            "title": "Test",
            "url": "https://example.com",
            "method": "static",
            "scrape_time_ms": 100.0,
        }

        response = client.post(
            "/api/v4/scrape-and-summarize/stream",
            json={"url": "https://example.com/test"},
        )

        # Check SSE headers
        assert response.headers["content-type"] == "text/event-stream; charset=utf-8"
        assert response.headers["cache-control"] == "no-cache"
        assert response.headers["connection"] == "keep-alive"
        assert "x-request-id" in response.headers


# ============================================================================
# Tests for /api/v4/scrape-and-summarize/stream-json endpoint
# ============================================================================


def test_v4_stream_json_url_mode_success(client: TestClient):
    """Test stream-json endpoint with URL input (successful scraping and JSON streaming)."""
    with patch(
        "app.services.article_scraper.article_scraper_service.scrape_article"
    ) as mock_scrape:
        mock_scrape.return_value = {
            "text": "Artificial intelligence is transforming modern technology. "
            "Machine learning algorithms are becoming more sophisticated. "
            "Deep learning models can now process vast amounts of data efficiently."
            * 10,
            "title": "AI Revolution 2024",
            "author": "Dr. Jane Smith",
            "date": "2024-11-30",
            "site_name": "Tech Insights",
            "url": "https://techinsights.com/ai-2024",
            "method": "static",
            "scrape_time_ms": 425.8,
        }

        # Mock JSON streaming from Outlines
        async def mock_json_stream(*args, **kwargs):
            # Yield raw JSON token fragments (simulating Outlines output)
            yield '{"title": "'
            yield "AI Revolution"
            yield '", "main_summary": "'
            yield "Artificial intelligence is rapidly evolving"
            yield '", "key_points": ['
            yield '"AI is transforming technology"'
            yield ', "ML algorithms are improving"'
            yield ', "Deep learning processes data efficiently"'
            yield '], "category": "'
            yield "Technology"
            yield '", "sentiment": "'
            yield "positive"
            yield '", "read_time_min": '
            yield "3"
            yield "}"

        with patch(
            "app.services.structured_summarizer.structured_summarizer_service.summarize_structured_stream_json",
            side_effect=mock_json_stream,
        ):
            response = client.post(
                "/api/v4/scrape-and-summarize/stream-json",
                json={
                    "url": "https://techinsights.com/ai-2024",
                    "style": "executive",
                    "max_tokens": 512,
                    "include_metadata": True,
                },
            )

            assert response.status_code == 200
            assert (
                response.headers["content-type"] == "text/event-stream; charset=utf-8"
            )

            # Parse SSE stream
            events = []
            for line in response.text.split("\n"):
                if line.startswith("data: "):
                    events.append(line[6:])  # Keep raw data

            # First event should be metadata JSON
            metadata_event = json.loads(events[0])
            assert metadata_event["type"] == "metadata"
            assert metadata_event["data"]["input_type"] == "url"
            assert metadata_event["data"]["url"] == "https://techinsights.com/ai-2024"
            assert metadata_event["data"]["title"] == "AI Revolution 2024"
            assert metadata_event["data"]["author"] == "Dr. Jane Smith"
            assert metadata_event["data"]["style"] == "executive"
            assert "scrape_latency_ms" in metadata_event["data"]

            # Rest should be raw JSON tokens
            json_tokens = events[1:]
            complete_json = "".join(json_tokens)

            # Verify it's valid JSON
            parsed_json = json.loads(complete_json)
            assert parsed_json["title"] == "AI Revolution"
            assert "AI is transforming technology" in parsed_json["key_points"]
            assert parsed_json["category"] == "Technology"
            assert parsed_json["sentiment"] == "positive"
            assert parsed_json["read_time_min"] == 3


def test_v4_stream_json_text_mode_success(client: TestClient):
    """Test stream-json endpoint with direct text input (no scraping)."""
    test_text = (
        "Climate change poses significant challenges to global ecosystems. "
        "Rising temperatures affect weather patterns worldwide. "
        "Scientists emphasize the need for immediate action."
    )

    async def mock_json_stream(*args, **kwargs):
        yield '{"title": "Climate Change Impact", '
        yield '"main_summary": "Climate change affects global ecosystems", '
        yield '"key_points": ["Rising temperatures", "Weather patterns"], '
        yield '"category": "Environment", '
        yield '"sentiment": "neutral", '
        yield '"read_time_min": 1}'

    with patch(
        "app.services.structured_summarizer.structured_summarizer_service.summarize_structured_stream_json",
        side_effect=mock_json_stream,
    ):
        response = client.post(
            "/api/v4/scrape-and-summarize/stream-json",
            json={
                "text": test_text,
                "style": "skimmer",
                "max_tokens": 256,
                "include_metadata": True,
            },
        )

        assert response.status_code == 200

        # Parse events
        events = []
        for line in response.text.split("\n"):
            if line.startswith("data: "):
                events.append(line[6:])

        # Check metadata for text mode
        metadata_event = json.loads(events[0])
        assert metadata_event["type"] == "metadata"
        assert metadata_event["data"]["input_type"] == "text"
        assert metadata_event["data"]["text_length"] == len(test_text)
        assert metadata_event["data"]["style"] == "skimmer"
        assert "url" not in metadata_event["data"]  # URL mode fields not present

        # Verify JSON output
        complete_json = "".join(events[1:])
        parsed_json = json.loads(complete_json)
        assert parsed_json["title"] == "Climate Change Impact"
        assert parsed_json["category"] == "Environment"


def test_v4_stream_json_no_metadata(client: TestClient):
    """Test stream-json endpoint with include_metadata=false."""

    async def mock_json_stream(*args, **kwargs):
        yield '{"title": "Test", '
        yield '"main_summary": "Summary", '
        yield '"key_points": ["A"], '
        yield '"category": "Test", '
        yield '"sentiment": "neutral", '
        yield '"read_time_min": 1}'

    with patch(
        "app.services.structured_summarizer.structured_summarizer_service.summarize_structured_stream_json",
        side_effect=mock_json_stream,
    ):
        response = client.post(
            "/api/v4/scrape-and-summarize/stream-json",
            json={
                "text": "Test article content for summary generation with enough characters to pass validation."
                * 2,
                "style": "eli5",
                "include_metadata": False,
            },
        )

        assert response.status_code == 200

        # Parse events
        events = []
        for line in response.text.split("\n"):
            if line.startswith("data: "):
                events.append(line[6:])

        # Should NOT have metadata event (check first event)
        # Metadata events are complete JSON with "type": "metadata"
        if events and events[0]:
            try:
                first_event = json.loads(events[0])
                assert first_event.get("type") != "metadata", (
                    "Metadata should not be included"
                )
            except json.JSONDecodeError:
                # First event is not complete JSON, so it's raw tokens (good!)
                pass

        # All events should be JSON tokens that combine to valid JSON
        complete_json = "".join(events)
        parsed_json = json.loads(complete_json)
        assert parsed_json["title"] == "Test"


def test_v4_stream_json_different_styles(client: TestClient):
    """Test stream-json endpoint with different summarization styles."""
    styles_to_test = ["skimmer", "executive", "eli5"]

    for style in styles_to_test:
        # Capture loop variable in closure
        def make_mock_stream(style_name: str):
            async def mock_json_stream(*args, **kwargs):
                yield f'{{"title": "{style_name.upper()}", '
                yield '"main_summary": "Test", '
                yield '"key_points": ["A"], '
                yield '"category": "Test", '
                yield '"sentiment": "positive", '
                yield '"read_time_min": 1}'

            return mock_json_stream

        with patch(
            "app.services.structured_summarizer.structured_summarizer_service.summarize_structured_stream_json",
            side_effect=make_mock_stream(style),
        ):
            response = client.post(
                "/api/v4/scrape-and-summarize/stream-json",
                json={
                    "text": "Test content for different styles with sufficient character count to pass validation requirements."
                    * 2,
                    "style": style,
                    "include_metadata": False,
                },
            )

            assert response.status_code == 200, f"Failed for style: {style}"


def test_v4_stream_json_custom_max_tokens(client: TestClient):
    """Test stream-json endpoint with custom max_tokens parameter."""

    async def mock_json_stream(text, style, max_tokens=None):
        # Verify max_tokens is passed through
        assert max_tokens == 1536
        yield '{"title": "Custom Tokens", '
        yield '"main_summary": "Test", '
        yield '"key_points": ["A"], '
        yield '"category": "Test", '
        yield '"sentiment": "neutral", '
        yield '"read_time_min": 1}'

    with patch(
        "app.services.structured_summarizer.structured_summarizer_service.summarize_structured_stream_json",
        side_effect=mock_json_stream,
    ):
        response = client.post(
            "/api/v4/scrape-and-summarize/stream-json",
            json={
                "text": "Test content with custom max tokens that meets minimum character requirements."
                * 3,
                "style": "executive",
                "max_tokens": 1536,
                "include_metadata": False,
            },
        )

        assert response.status_code == 200


def test_v4_stream_json_scraping_failure(client: TestClient):
    """Test stream-json endpoint when article scraping fails."""
    with patch(
        "app.services.article_scraper.article_scraper_service.scrape_article"
    ) as mock_scrape:
        mock_scrape.side_effect = Exception("Network timeout")

        response = client.post(
            "/api/v4/scrape-and-summarize/stream-json",
            json={
                "url": "https://example.com/unreachable",
                "style": "executive",
            },
        )

        assert response.status_code == 502
        assert "detail" in response.json()
        assert "scrape" in response.json()["detail"].lower()


def test_v4_stream_json_content_too_short(client: TestClient):
    """Test stream-json endpoint when scraped content is too short."""
    with patch(
        "app.services.article_scraper.article_scraper_service.scrape_article"
    ) as mock_scrape:
        mock_scrape.return_value = {
            "text": "Too short",  # Less than 100 characters
            "title": "Short Article",
            "url": "https://example.com/short",
            "method": "static",
            "scrape_time_ms": 200.0,
        }

        response = client.post(
            "/api/v4/scrape-and-summarize/stream-json",
            json={
                "url": "https://example.com/short",
                "style": "executive",
            },
        )

        assert response.status_code == 422
        assert "detail" in response.json()
        assert "insufficient" in response.json()["detail"].lower()


def test_v4_stream_json_ssrf_protection(client: TestClient):
    """Test stream-json endpoint blocks SSRF attempts."""
    ssrf_urls = [
        "http://localhost/admin",
        "http://127.0.0.1/secrets",
        "http://192.168.1.1/internal",
        "http://10.0.0.1/private",
    ]

    for url in ssrf_urls:
        response = client.post(
            "/api/v4/scrape-and-summarize/stream-json",
            json={
                "url": url,
                "style": "executive",
            },
        )

        assert response.status_code == 422, f"SSRF not blocked for: {url}"
        # FastAPI validation errors return detail array
        assert "detail" in response.json()


def test_v4_stream_json_validation_errors(client: TestClient):
    """Test stream-json endpoint input validation."""
    # Missing both url and text
    response = client.post(
        "/api/v4/scrape-and-summarize/stream-json",
        json={"style": "executive"},
    )
    assert response.status_code == 422

    # Both url and text provided
    response = client.post(
        "/api/v4/scrape-and-summarize/stream-json",
        json={
            "url": "https://example.com",
            "text": "Some text",
            "style": "executive",
        },
    )
    assert response.status_code == 422

    # Text too short
    response = client.post(
        "/api/v4/scrape-and-summarize/stream-json",
        json={
            "text": "Short",
            "style": "executive",
        },
    )
    assert response.status_code == 422

    # Invalid style
    response = client.post(
        "/api/v4/scrape-and-summarize/stream-json",
        json={
            "text": "Valid length text for testing validation" * 5,
            "style": "invalid_style",
        },
    )
    assert response.status_code == 422


def test_v4_stream_json_response_headers(client: TestClient):
    """Test stream-json endpoint returns correct SSE headers."""

    async def mock_json_stream(*args, **kwargs):
        yield '{"title": "Test", "main_summary": "Test", "key_points": [], '
        yield '"category": "Test", "sentiment": "neutral", "read_time_min": 1}'

    with patch(
        "app.services.structured_summarizer.structured_summarizer_service.summarize_structured_stream_json",
        side_effect=mock_json_stream,
    ):
        response = client.post(
            "/api/v4/scrape-and-summarize/stream-json",
            json={
                "text": "Test content for header validation." * 10,
                "style": "executive",
            },
        )

        # Verify SSE headers
        assert response.headers["content-type"] == "text/event-stream; charset=utf-8"
        assert response.headers["cache-control"] == "no-cache"
        assert response.headers["connection"] == "keep-alive"
        assert response.headers["x-accel-buffering"] == "no"
        assert "x-request-id" in response.headers


def test_v4_stream_json_request_id_tracking(client: TestClient):
    """Test stream-json endpoint respects X-Request-ID header."""
    custom_request_id = "test-request-12345"

    async def mock_json_stream(*args, **kwargs):
        yield '{"title": "Test", "main_summary": "Test", "key_points": [], '
        yield '"category": "Test", "sentiment": "neutral", "read_time_min": 1}'

    with patch(
        "app.services.structured_summarizer.structured_summarizer_service.summarize_structured_stream_json",
        side_effect=mock_json_stream,
    ):
        response = client.post(
            "/api/v4/scrape-and-summarize/stream-json",
            json={
                "text": "Test content for request ID tracking." * 10,
                "style": "executive",
            },
            headers={"X-Request-ID": custom_request_id},
        )

        assert response.headers["x-request-id"] == custom_request_id