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
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
import asyncio
import os
from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch

import pytest
from playwright.async_api import Error as PlaywrightAsyncError

from browser_utils.initialization import (
    _close_page_logic,
    _initialize_page_logic,
    enable_temporary_chat_mode,
    signal_camoufox_shutdown,
)

# --- Existing Tests (Preserved) ---


@pytest.mark.asyncio
async def test_initialize_page_logic_success(
    mock_browser,
    mock_browser_context,
    mock_page,
    mock_env,
    mock_expect,
    mock_server_state,
):
    # Mock state
    mock_server_state.PLAYWRIGHT_PROXY_SETTINGS = None
    with (
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
    ):
        # Mock page finding logic
        mock_page.url = "https://aistudio.google.com/prompts/new_chat"
        mock_page.is_closed = MagicMock(return_value=False)
        mock_browser_context.pages = [mock_page]

        # Mock locators for verification
        mock_page.locator.return_value.first.inner_text = AsyncMock(
            return_value="Gemini 1.5 Pro"
        )

        page, ready = await _initialize_page_logic(mock_browser)

        assert page == mock_page
        assert ready is True
        mock_browser.new_context.assert_called()


@pytest.mark.asyncio
async def test_initialize_page_logic_new_page(
    mock_browser,
    mock_browser_context,
    mock_page,
    mock_env,
    mock_expect,
    mock_server_state,
):
    mock_server_state.PLAYWRIGHT_PROXY_SETTINGS = None
    with (
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page
        mock_page.url = "https://aistudio.google.com/prompts/new_chat"

        mock_page.locator.return_value.first.inner_text = AsyncMock(
            return_value="Gemini 1.5 Pro"
        )

        page, ready = await _initialize_page_logic(mock_browser)

        assert page == mock_page
        assert ready is True
        mock_page.goto.assert_called()


@pytest.mark.asyncio
async def test_close_page_logic_success():
    mock_page = AsyncMock()
    mock_page.is_closed = MagicMock(return_value=False)

    from api_utils.server_state import state

    original_page = state.page_instance
    original_ready = state.is_page_ready

    try:
        state.page_instance = mock_page
        state.is_page_ready = True

        await _close_page_logic()

        mock_page.close.assert_called()
        assert state.page_instance is None
        assert state.is_page_ready is False
    finally:
        state.page_instance = original_page
        state.is_page_ready = original_ready


@pytest.mark.asyncio
async def test_close_page_logic_already_closed():
    from api_utils.server_state import state

    original_page = state.page_instance

    try:
        mock_page = AsyncMock()
        mock_page.is_closed = MagicMock(return_value=True)
        state.page_instance = mock_page

        await _close_page_logic()

        mock_page.close.assert_not_called()
        assert state.page_instance is None
    finally:
        state.page_instance = original_page


@pytest.mark.asyncio
async def test_initialize_page_logic_headless_auth_missing(
    mock_browser, mock_env, mock_server_state
):
    """Test that headless mode raises when ACTIVE_AUTH_JSON_PATH is empty."""
    with (
        patch.dict(
            os.environ,
            {
                "LAUNCH_MODE": "headless",
                "ACTIVE_AUTH_JSON_PATH": "",
                "AUTO_AUTH_ROTATION_ON_STARTUP": "false",
            },
        ),
    ):
        with pytest.raises(RuntimeError) as exc:
            await _initialize_page_logic(mock_browser)
        assert "ACTIVE_AUTH_JSON_PATH" in str(exc.value)


@pytest.mark.asyncio
async def test_initialize_page_logic_proxy_settings(
    mock_browser,
    mock_browser_context,
    mock_page,
    mock_env,
    mock_expect,
    mock_server_state,
):
    with (
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
    ):
        mock_server_state.PLAYWRIGHT_PROXY_SETTINGS = {"server": "http://proxy:8080"}

        mock_browser_context.pages = [mock_page]
        mock_page.url = "https://aistudio.google.com/prompts/new_chat"
        mock_page.is_closed.return_value = False

        mock_page.locator.return_value.first.inner_text = AsyncMock(
            return_value="Gemini 1.5 Pro"
        )

        await _initialize_page_logic(mock_browser)

        call_args = mock_browser.new_context.call_args
        assert call_args is not None
        assert call_args[1]["proxy"] == {"server": "http://proxy:8080"}


# --- New Tests ---

# 1. Storage State & Launch Modes


@pytest.mark.asyncio
async def test_init_storage_state_explicit_exists(
    mock_browser, mock_browser_context, mock_page, mock_expect, mock_server_state
):
    with (
        patch("os.path.exists", return_value=True),
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page
        mock_page.url = "https://aistudio.google.com/prompts/new_chat"
        mock_page.locator.return_value.first.inner_text = AsyncMock(
            return_value="Model"
        )

        await _initialize_page_logic(
            mock_browser, storage_state_path="/path/to/auth.json"
        )

        call_args = mock_browser.new_context.call_args
        assert call_args[1]["storage_state"] == "/path/to/auth.json"


@pytest.mark.asyncio
async def test_init_storage_state_explicit_missing(mock_browser):
    with patch("os.path.exists", return_value=False):
        with pytest.raises(RuntimeError, match="Specified auth file does not exist"):
            await _initialize_page_logic(
                mock_browser, storage_state_path="/path/to/missing.json"
            )


@pytest.mark.asyncio
async def test_init_headless_auth_exists(
    mock_browser, mock_browser_context, mock_page, mock_expect, mock_server_state
):
    with (
        patch.dict(
            os.environ,
            {
                "LAUNCH_MODE": "headless",
                "ACTIVE_AUTH_JSON_PATH": "/env/auth.json",
                "AUTO_AUTH_ROTATION_ON_STARTUP": "false",
            },
        ),
        patch("os.path.exists", return_value=True),
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page
        mock_page.url = "https://aistudio.google.com/prompts/new_chat"
        mock_page.locator.return_value.first.inner_text = AsyncMock(
            return_value="Model"
        )

        await _initialize_page_logic(mock_browser)
        call_args = mock_browser.new_context.call_args
        assert call_args[1]["storage_state"] == "/env/auth.json"


@pytest.mark.asyncio
async def test_init_headless_auth_invalid(mock_browser):
    with (
        patch.dict(
            os.environ,
            {
                "LAUNCH_MODE": "headless",
                "ACTIVE_AUTH_JSON_PATH": "/env/invalid.json",
                "AUTO_AUTH_ROTATION_ON_STARTUP": "false",
            },
        ),
        patch("os.path.exists", return_value=False),
    ):
        with pytest.raises(RuntimeError, match="headless mode auth file invalid"):
            await _initialize_page_logic(mock_browser)


@pytest.mark.asyncio
async def test_init_debug_auth_exists(
    mock_browser, mock_browser_context, mock_page, mock_expect, mock_server_state
):
    with (
        patch.dict(
            os.environ,
            {"LAUNCH_MODE": "debug", "ACTIVE_AUTH_JSON_PATH": "/env/debug.json"},
        ),
        patch("os.path.exists", return_value=True),
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page
        mock_page.url = "https://aistudio.google.com/prompts/new_chat"
        mock_page.locator.return_value.first.inner_text = AsyncMock(
            return_value="Model"
        )

        await _initialize_page_logic(mock_browser)
        call_args = mock_browser.new_context.call_args
        assert call_args[1]["storage_state"] == "/env/debug.json"


@pytest.mark.asyncio
async def test_init_debug_auth_missing_file(
    mock_browser, mock_browser_context, mock_page, mock_expect, mock_server_state
):
    with (
        patch.dict(
            os.environ,
            {"LAUNCH_MODE": "debug", "ACTIVE_AUTH_JSON_PATH": "/env/missing.json"},
        ),
        patch("os.path.exists", return_value=False),
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page
        mock_page.url = "https://aistudio.google.com/prompts/new_chat"
        mock_page.locator.return_value.first.inner_text = AsyncMock(
            return_value="Model"
        )

        await _initialize_page_logic(mock_browser)
        call_args = mock_browser.new_context.call_args
        assert "storage_state" not in call_args[1]


@pytest.mark.asyncio
async def test_init_direct_debug_no_browser(
    mock_browser, mock_browser_context, mock_page, mock_expect, mock_server_state
):
    with (
        patch.dict(os.environ, {"LAUNCH_MODE": "direct_debug_no_browser"}),
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page
        mock_page.url = "https://aistudio.google.com/prompts/new_chat"
        mock_page.locator.return_value.first.inner_text = AsyncMock(
            return_value="Model"
        )

        await _initialize_page_logic(mock_browser)
        call_args = mock_browser.new_context.call_args
        assert "storage_state" not in call_args[1]


@pytest.mark.asyncio
async def test_init_unknown_launch_mode(
    mock_browser, mock_browser_context, mock_page, mock_expect, mock_server_state
):
    with (
        patch.dict(os.environ, {"LAUNCH_MODE": "unknown_mode"}),
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page
        mock_page.url = "https://aistudio.google.com/prompts/new_chat"
        mock_page.locator.return_value.first.inner_text = AsyncMock(
            return_value="Model"
        )

        await _initialize_page_logic(mock_browser)
        call_args = mock_browser.new_context.call_args
        assert "storage_state" not in call_args[1]


# 2. Page Discovery & Navigation Errors


@pytest.mark.asyncio
async def test_init_page_discovery_errors(
    mock_browser, mock_browser_context, mock_page, mock_expect, mock_server_state
):
    """Test error handling during iteration of existing pages."""
    with (
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
    ):
        # Create 3 pages:
        # 1. Raises PlaywrightAsyncError
        # 2. Raises AttributeError
        # 3. Raises generic Exception
        # 4. Valid page (to ensure loop continues or finishes)

        page1 = AsyncMock()
        page1.is_closed = MagicMock(return_value=False)
        type(page1).url = PropertyMock(side_effect=PlaywrightAsyncError("PW Error"))

        page2 = AsyncMock()
        page2.is_closed = MagicMock(return_value=False)
        type(page2).url = PropertyMock(side_effect=AttributeError("Attr Error"))

        page3 = AsyncMock()
        page3.is_closed = MagicMock(return_value=False)
        type(page3).url = PropertyMock(side_effect=Exception("Generic Error"))

        # We need to mock the pages property to return these
        mock_browser_context.pages = [page1, page2, page3]

        # It should fall through to creating a new page
        mock_browser_context.new_page.return_value = mock_page
        mock_page.url = "https://aistudio.google.com/prompts/new_chat"
        mock_page.locator.return_value.first.inner_text = AsyncMock(
            return_value="Model"
        )

        await _initialize_page_logic(mock_browser)

        # Should have tried to create a new page since no existing one was found
        mock_browser_context.new_page.assert_called()


@pytest.mark.asyncio
async def test_init_new_page_nav_error_generic(
    mock_browser, mock_browser_context, mock_page, mock_server_state
):
    with (
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
        patch(
            "browser_utils.operations.save_error_snapshot", new_callable=AsyncMock
        ) as mock_snapshot,
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page
        mock_page.goto.side_effect = Exception("Navigation Failed")

        with pytest.raises(RuntimeError):
            await _initialize_page_logic(mock_browser)

        mock_snapshot.assert_any_call("init_new_page_nav_fail")


@pytest.mark.asyncio
async def test_init_new_page_nav_error_net_interrupt(
    mock_browser, mock_browser_context, mock_page, mock_server_state
):
    with (
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
        patch(
            "browser_utils.operations.save_error_snapshot", new_callable=AsyncMock
        ) as mock_snapshot,
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page
        mock_page.goto.side_effect = Exception("NS_ERROR_NET_INTERRUPT")

        with pytest.raises(RuntimeError):
            await _initialize_page_logic(mock_browser)

        mock_snapshot.assert_any_call("init_new_page_nav_fail")


# 3. Login Logic


@pytest.mark.asyncio
async def test_init_login_headless_fail(
    mock_browser, mock_browser_context, mock_page, mock_server_state
):
    # Ensure ACTIVE_AUTH_JSON_PATH is set so we pass the initial check
    with (
        patch.dict(
            "os.environ",
            {"LAUNCH_MODE": "headless", "ACTIVE_AUTH_JSON_PATH": "/path/to/auth.json"},
        ),
        patch("os.path.exists", return_value=True),
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page

        # First URL check (after goto) returns login URL
        mock_page.url = "https://accounts.google.com/signin"
        mock_page.goto = AsyncMock()

        with pytest.raises(RuntimeError) as exc:
            await _initialize_page_logic(mock_browser)
        assert "Auth failed in headless mode" in str(exc.value)


@pytest.mark.asyncio
async def test_init_login_interactive_success(
    mock_browser, mock_browser_context, mock_page, mock_expect, mock_server_state
):
    with (
        patch.dict("os.environ", {"LAUNCH_MODE": "debug", "SUPPRESS_LOGIN_WAIT": "0"}),
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
        patch(
            "browser_utils.initialization.core.wait_for_model_list_and_handle_auth_save",
            new_callable=AsyncMock,
        ),
        patch("builtins.input", return_value=""),
        patch("builtins.print"),
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page

        # Sequence of URLs:
        # 1. After goto -> signin
        # 2. After wait_for_url -> new_chat
        type(mock_page).url = PropertyMock(
            side_effect=[
                "https://accounts.google.com/signin",
                "https://aistudio.google.com/prompts/new_chat",
                "https://aistudio.google.com/prompts/new_chat",
                "https://aistudio.google.com/prompts/new_chat",
            ]
        )

        mock_page.wait_for_url = AsyncMock()
        mock_page.locator.return_value.first.inner_text = AsyncMock(
            return_value="Model"
        )

        await _initialize_page_logic(mock_browser)

        mock_page.wait_for_url.assert_called()


@pytest.mark.asyncio
async def test_init_login_interactive_suppress_wait(
    mock_browser, mock_browser_context, mock_page, mock_expect, mock_server_state
):
    with (
        patch.dict(
            "os.environ", {"LAUNCH_MODE": "debug", "SUPPRESS_LOGIN_WAIT": "true"}
        ),
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
        patch(
            "browser_utils.initialization.core.wait_for_model_list_and_handle_auth_save",
            new_callable=AsyncMock,
        ),
        patch("builtins.input") as mock_input,
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page

        type(mock_page).url = PropertyMock(
            side_effect=[
                "https://accounts.google.com/signin",
                "https://aistudio.google.com/prompts/new_chat",
                "https://aistudio.google.com/prompts/new_chat",
                "https://aistudio.google.com/prompts/new_chat",
            ]
        )

        mock_page.locator.return_value.first.inner_text = AsyncMock(
            return_value="Model"
        )

        await _initialize_page_logic(mock_browser)

        mock_input.assert_not_called()


@pytest.mark.asyncio
async def test_init_login_interactive_fail_still_login_page(
    mock_browser, mock_browser_context, mock_page, mock_server_state
):
    with (
        patch.dict("os.environ", {"LAUNCH_MODE": "debug"}),
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
        patch("builtins.input", return_value=""),
        patch("browser_utils.operations.save_error_snapshot", new_callable=AsyncMock),
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page

        type(mock_page).url = PropertyMock(
            return_value="https://accounts.google.com/signin"
        )

        with pytest.raises(
            RuntimeError, match="Still on login page after manual login attempt"
        ):
            await _initialize_page_logic(mock_browser)


@pytest.mark.asyncio
async def test_init_login_wait_exception(
    mock_browser, mock_browser_context, mock_page, mock_server_state
):
    with (
        patch.dict("os.environ", {"LAUNCH_MODE": "debug"}),
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
        patch("builtins.input", return_value=""),
        patch(
            "browser_utils.operations.save_error_snapshot", new_callable=AsyncMock
        ) as mock_snapshot,
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page

        type(mock_page).url = PropertyMock(
            return_value="https://accounts.google.com/signin"
        )
        mock_page.wait_for_url.side_effect = Exception("Wait Timeout")

        with pytest.raises(RuntimeError):
            await _initialize_page_logic(mock_browser)

        mock_snapshot.assert_any_call("init_login_wait_fail")


# 4. Unexpected Page & Model Name Error


@pytest.mark.asyncio
async def test_init_unexpected_page_url(
    mock_browser, mock_browser_context, mock_page, mock_server_state
):
    with (
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
        patch(
            "browser_utils.operations.save_error_snapshot", new_callable=AsyncMock
        ) as mock_snapshot,
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page

        # Not login, but not target either
        type(mock_page).url = PropertyMock(return_value="https://google.com")

        with pytest.raises(RuntimeError):
            await _initialize_page_logic(mock_browser)

        mock_snapshot.assert_any_call("init_unexpected_page")


@pytest.mark.asyncio
async def test_init_model_name_error(
    mock_browser, mock_browser_context, mock_page, mock_server_state
):
    with (
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page
        mock_page.url = "https://aistudio.google.com/prompts/new_chat"

        mock_expect = MagicMock()
        mock_expect.return_value.to_be_visible = AsyncMock()

        # Override the locator to fail for model-name
        original_locator = mock_page.locator.side_effect

        def failing_locator_factory(selector):
            loc = original_locator()
            if '[data-test-id="model-name"]' in selector:
                loc.first.inner_text = AsyncMock(
                    side_effect=PlaywrightAsyncError("Locator Fail")
                )
            return loc

        mock_page.locator = MagicMock(side_effect=failing_locator_factory)

        with patch("browser_utils.initialization.core.expect_async", mock_expect):
            # The PlaywrightAsyncError is caught and re-raised as RuntimeError
            with pytest.raises(RuntimeError):
                await _initialize_page_logic(mock_browser)


@pytest.mark.asyncio
async def test_init_input_visible_timeout(
    mock_browser, mock_browser_context, mock_page, mock_server_state
):
    with (
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch("browser_utils.initialization.core.setup_debug_listeners"),
        patch(
            "browser_utils.operations.save_error_snapshot", new_callable=AsyncMock
        ) as mock_snapshot,
    ):
        mock_browser_context.pages = []
        mock_browser_context.new_page.return_value = mock_page
        mock_page.url = "https://aistudio.google.com/prompts/new_chat"

        mock_expect = MagicMock()
        # expect_async raises error (timeout)
        mock_expect.return_value.to_be_visible.side_effect = Exception(
            "Timeout waiting for input"
        )

        with patch("browser_utils.initialization.core.expect_async", mock_expect):
            with pytest.raises(RuntimeError):
                await _initialize_page_logic(mock_browser)

            mock_snapshot.assert_any_call("init_fail_input_timeout")


# 5. Cancellation & Generic Errors


@pytest.mark.asyncio
async def test_init_cancelled(mock_browser, mock_browser_context, mock_server_state):
    with (
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
    ):
        mock_browser.new_context.side_effect = asyncio.CancelledError()

        with pytest.raises(asyncio.CancelledError):
            await _initialize_page_logic(mock_browser)


@pytest.mark.asyncio
async def test_init_generic_exception_cleanup(
    mock_browser, mock_browser_context, mock_server_state
):
    with (
        patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            new_callable=AsyncMock,
        ),
        patch(
            "browser_utils.operations.save_error_snapshot", new_callable=AsyncMock
        ) as mock_snapshot,
    ):
        # Fail at setup_network_interception_and_scripts
        with patch(
            "browser_utils.initialization.core.setup_network_interception_and_scripts",
            side_effect=Exception("Setup Fail"),
        ):
            with pytest.raises(
                RuntimeError, match="Unexpected page initialization error"
            ):
                await _initialize_page_logic(mock_browser)

            # Verify context was closed
            mock_browser_context.close.assert_called()
            mock_snapshot.assert_called_with("init_unexpected_error")


# 6. Close Page Logic Errors


@pytest.mark.asyncio
async def test_close_page_logic_errors():
    from api_utils.server_state import state

    original_page = state.page_instance

    try:
        mock_page = AsyncMock()
        # is_closed must be a MagicMock returning bool, not AsyncMock returning coroutine
        mock_page.is_closed = MagicMock(return_value=False)

        # 1. PlaywrightAsyncError
        mock_page.close.side_effect = PlaywrightAsyncError("PW Error")
        state.page_instance = mock_page
        await _close_page_logic()  # Should not raise

        # 2. TimeoutError
        mock_page.close.side_effect = asyncio.TimeoutError("Timeout")
        state.page_instance = mock_page
        await _close_page_logic()  # Should not raise

        # 3. Generic Exception
        mock_page.close.side_effect = Exception("Generic")
        state.page_instance = mock_page
        await _close_page_logic()  # Should not raise

        # 4. CancelledError
        mock_page.close.side_effect = asyncio.CancelledError()
        state.page_instance = mock_page
        with pytest.raises(asyncio.CancelledError):
            await _close_page_logic()
    finally:
        state.page_instance = original_page


# 7. Signal Camoufox Shutdown


@pytest.mark.asyncio
async def test_signal_camoufox_shutdown_no_env():
    with patch.dict("os.environ", {}, clear=True):
        await signal_camoufox_shutdown()
        # Should just return


@pytest.mark.asyncio
async def test_signal_camoufox_shutdown_no_browser(mock_server_state):
    with (
        patch.dict("os.environ", {"CAMOUFOX_WS_ENDPOINT": "ws://test"}),
    ):
        mock_server_state.browser_instance = None
        await signal_camoufox_shutdown()
        # Should just return


@pytest.mark.asyncio
async def test_signal_camoufox_shutdown_success(mock_server_state):
    with (
        patch.dict("os.environ", {"CAMOUFOX_WS_ENDPOINT": "ws://test"}),
        patch("asyncio.sleep", side_effect=AsyncMock()),
    ):
        mock_browser = MagicMock()
        mock_browser.is_connected.return_value = True
        mock_server_state.browser_instance = mock_browser

        await signal_camoufox_shutdown()


@pytest.mark.asyncio
async def test_signal_camoufox_shutdown_exception(mock_server_state):
    with (
        patch.dict("os.environ", {"CAMOUFOX_WS_ENDPOINT": "ws://test"}),
        patch("asyncio.sleep", side_effect=Exception("Sleep Fail")),
    ):
        mock_browser = MagicMock()
        mock_browser.is_connected.return_value = True
        mock_server_state.browser_instance = mock_browser

        # Should catch exception and log error
        await signal_camoufox_shutdown()


# 8. Enable Temporary Chat Mode


@pytest.mark.asyncio
async def test_enable_temporary_chat_mode_already_active(mock_page):
    locator = MagicMock()
    locator.wait_for = AsyncMock()
    locator.get_attribute = AsyncMock(return_value="ms-button-active")
    mock_page.locator.return_value = locator

    await enable_temporary_chat_mode(mock_page)

    locator.click.assert_not_called()


@pytest.mark.asyncio
async def test_enable_temporary_chat_mode_activate_success(mock_page):
    locator = MagicMock()
    locator.wait_for = AsyncMock()
    locator.click = AsyncMock()
    # First inactive, then active
    locator.get_attribute = AsyncMock(side_effect=["", "ms-button-active"])
    # Use side_effect to override the factory
    mock_page.locator = MagicMock(return_value=locator)

    await enable_temporary_chat_mode(mock_page)

    locator.click.assert_called()


@pytest.mark.asyncio
async def test_enable_temporary_chat_mode_activate_fail(mock_page):
    locator = MagicMock()
    locator.wait_for = AsyncMock()
    locator.click = AsyncMock()
    # Always inactive
    locator.get_attribute = AsyncMock(return_value="")
    # Use side_effect to override the factory
    mock_page.locator = MagicMock(return_value=locator)

    await enable_temporary_chat_mode(mock_page)

    locator.click.assert_called()


@pytest.mark.asyncio
async def test_enable_temporary_chat_mode_exception(mock_page):
    mock_page.locator.side_effect = Exception("Locator Fail")

    # Should catch exception and log warning
    await enable_temporary_chat_mode(mock_page)


@pytest.mark.asyncio
async def test_enable_temporary_chat_mode_cancelled(mock_page):
    mock_page.locator.side_effect = asyncio.CancelledError()

    with pytest.raises(asyncio.CancelledError):
        await enable_temporary_chat_mode(mock_page)