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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
#!/usr/bin/env python3
"""NAVIGATION lane for NextPlayer (dev.anilbeesetti.nextplayer.debug).

This lane owns surface REACHABILITY and BACK-STACK integrity: tapping a nav
trigger (top-bar icon, folder row, video row, settings row, FAB pill, player
top-bar icon) lands on the intended surface, and BACK unwinds the stack hop by
hop. It is the sole owner of jump_kind="reach" and of the deep (depth>=2) chains.

Every jump is proven with the kit's and_reach(before, after, target, source):
the TARGET surface's discriminating element must have APPEARED *and* the SOURCE
surface's must have DISAPPEARED. A screen that was already in the tree was never
"reached". before/after are and_showing() snapshots.

Ground truth (observed on the running original — see recon.md + recon_shots/ and
re-verified live before authoring):
  * Home (portrait) top bar carries content-desc "Search"/"Menu"/"Settings";
    body lists the "Download" folder row with a "3 Videos" count badge; a
    desc-less FAB bottom-right expands to 3 pills.
  * Folder contents (Download) shows a "Navigate up" back arrow + the 3 video
    rows (alpha_clip/beta_movie/gamma_reel); the Home-only "3 Videos" badge is
    gone there.
  * PlayerActivity is LANDSCAPE (2400x1080 in the dump while `wm size` still
    reports the physical portrait 1080x2400). Controls auto-hide, and CRUCIALLY
    the a11y tree keeps reporting them for a beat AFTER they visually fade — a
    screenshot then shows only the video (verified). So the top-bar icons are
    only hittable in the ~1 s window right after a frame-centre tap: we learn
    their coordinates from one reveal, then tap centre and IMMEDIATELY tap the
    icon with NO ui() dump in between (a dump's latency is enough for the overlay
    to fade), retrying and hiding between tries. Because `wm size` lies here,
    and_showing()/tap_node() would clip controls with x>1080, so we install the
    dump's own landscape geometry (see _use_landscape_geom).
    Icons left->right = playlist / playback-speed / audio-track / subtitle-track;
    the centre control carries content-desc "Play/Pause".
  * Settings root: 9 category rows (Appearance/Media library/Player/Gestures/
    Decoder/Audio/Subtitle/General/About). Each subscreen replaces the sibling
    rows with its own content and keeps a "Navigate up" arrow; the root-only row
    "Media library" therefore disappears on every subscreen (and "Appearance" on
    the Media-library subscreen), which is the source marker for the sub reaches.
  * Search: an EditText (hint "Search videos and folders") + a "Popular folders"
    section; the Home top-bar "Menu" control is gone there.
  * FAB pills: "Open network stream"/"Open local video"/"Recently played". The
    network pill opens the "Network Stream" dialog (URL EditText + Done/Cancel).
  * Player dialogs: "Select playback speed" (chips + "Skip silence"),
    "Select audio track" ("Audio Track #1"), "Select subtitle track"
    ("Open local subtitle").

Fixtures: the 3 sample videos are authored into fixtures/ and mirrored to the
device by push_fixtures() (run_suite() calls it once); each test reaches them
through fixture_on_device(name), never a hand-pushed path.

CEDES (per lane contract): content strings -> text; tree shape -> structure;
selection/toggle -> states; a shown value -> computation; record creation ->
interaction. Here we assert ONLY "did we land on the target surface and leave
the source", plus BACK unwinding.
"""
import os
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from android_testgen_kit import *          # noqa: F403,E402
import android_testgen_kit as kit          # noqa: E402  (for the geometry cache)

require_kit(1)

# ── Ground-truth markers (strings observed on the running original) ─────────────
FOLDER_NAME = "Download"
FOLDER_COUNT = "3 Videos"                 # Home-only badge; gone inside the folder
PLAYER_MARKER = "Play/Pause"              # content-desc unique to the player
NAV_UP = "Navigate up"                    # back arrow on folder & settings screens
VIDEO_BETA = "beta_movie"                 # 8 s clip — the least race-prone player src
# The fixture videos the picker opens; declared via fixture_on_device so the
# dependency is explicit and the kit pushes the bytes on a fresh emulator.
FIXTURE_VIDEOS = ("alpha_clip.mp4", "beta_movie.mp4", "gamma_reel.mp4")

# Settings root row that vanishes on any subscreen -> the source for sub reaches.
SETTINGS_SIBLING = "Media library"
SETTINGS_SIBLING_ALT = "Appearance"       # source when the sub IS Media library

LOOP_DESCS = ("Loop: Off", "Loop: One", "Loop: All")
# Player top-bar icon index (left->right among the right-side buttons).
PLAYER_ICON = {"speed": 1, "audio": 2, "subtitle": 3}


# ══════════════════════════════════════════════════════════════════════════════
# Setup helpers
# ══════════════════════════════════════════════════════════════════════════════

def and_grant_media():
    """Tap the runtime media-permission 'Allow all' if it is showing (no-op
    otherwise). restart_app() keeps the grant, so this is just a safety net."""
    for label in ("Allow all", "While using the app", "Allow"):
        n = find_node_ci(ui(), label)
        if n:
            tap_node(n)
            settle("tap")
            return True
    return False


def tap_topbar(nodes, desc):
    """Tap a Home/folder top-bar icon by content-desc. The desc node itself is
    not clickable — its wrapping View is — so tap the tightest clickable ancestor
    that contains the icon centre, falling back to the desc node."""
    target = find_node(nodes, content_desc=desc)
    if not target or "_bounds" not in target:
        return False
    tcx, tcy = target["_center"]
    best, best_area = None, None
    for n in nodes:
        if n.get("clickable") != "true" or "_bounds" not in n:
            continue
        x1, y1, x2, y2 = n["_bounds"]
        if x1 <= tcx <= x2 and y1 <= tcy <= y2:
            area = (x2 - x1) * (y2 - y1)
            if best_area is None or area < best_area:
                best, best_area = n, area
    return tap_node(best) if best else tap_node(target)


def _home_content_ready(nodes):
    """True once the Home picker actually rendered its top bar + folder row, so we
    never assert against a mid-load or launcher frame."""
    topbar = all(find_node(nodes, content_desc=d) for d in ("Search", "Menu", "Settings"))
    body = bool(find_node(nodes, text=FOLDER_NAME)) or bool(find_node(nodes, text=VIDEO_BETA))
    return topbar and body


def _open_quick_settings(nodes):
    tap_topbar(nodes, "Menu")
    settle("tap")
    return ui()


def _reset_view_mode(nodes):
    """Normalize the picker to the default Folders view (persisted prefs survive
    restart_app). Opens Quick Settings, selects Folders, taps Done."""
    qs = _open_quick_settings(nodes)
    if find_node(qs, text="Folders"):
        tap_text(qs, "Folders")
        settle("tap")
    done = find_node(ui(), text="Done")
    if done:
        tap_node(done)
        settle("tap")
    return ui()


def home_ready():
    """restart (keeps media grant), wait for the rendered Home, and guarantee the
    default Folders view so the 'Download' folder row exists. Returns Home nodes.

    push_fixtures() is idempotent (run_suite() also calls it); doing it here keeps
    each test self-sufficient and makes the fixture dependency explicit."""
    push_fixtures()
    _ = [fixture_on_device(v) for v in FIXTURE_VIDEOS]     # explicit dependency
    nodes = []
    for _attempt in range(2):
        restart_app()
        if not wait_for_foreground():
            continue
        and_grant_media()
        for _ in range(6):
            nodes = ui()
            if _home_content_ready(nodes):
                break
            settle("dump")
        if _home_content_ready(nodes):
            break
    if not nodes:
        return []
    if not find_node(nodes, text=FOLDER_NAME):
        nodes = _reset_view_mode(nodes)
    return nodes


# ── Player geometry: the landscape window reports portrait via `wm size`, which
# would make and_showing()/tap_node() clip every control with x>1080. Derive the
# real landscape geometry from the dump's own max bounds and install it in the
# kit's cache so both helpers use the correct width. ────────────────────────────

def _dump_center(nodes):
    maxx = max((b[2] for b in (n.get("_bounds") for n in nodes) if b), default=0)
    maxy = max((b[3] for b in (n.get("_bounds") for n in nodes) if b), default=0)
    return (maxx // 2, maxy // 2) if maxx and maxy else (0, 0)


def _use_landscape_geom(nodes):
    """Point the kit's cached geometry at the dump's own (rotated) bounds so
    and_showing() keeps the player controls and tap_node() accepts their x>1080
    centres. `input tap` on this app's landscape window uses these logical coords
    directly (verified live)."""
    maxx = max((b[2] for b in (n.get("_bounds") for n in nodes) if b), default=2400)
    maxy = max((b[3] for b in (n.get("_bounds") for n in nodes) if b), default=1080)
    kit._screen_info = {"width": maxx, "height": maxy, "density": 440,
                        "center_x": maxx // 2, "center_y": maxy // 2}


def _controls_up(nodes):
    return bool(find_node(nodes, content_desc=PLAYER_MARKER)
                or any(find_node(nodes, content_desc=d) for d in LOOP_DESCS))


def _reveal_player_controls():
    """Tap the (rotated) frame centre until the auto-hiding controls are up in the
    tree. Handles the one-time 'Got it' full-screen hint. Returns fresh player
    nodes once controls show, else the last dump."""
    for _ in range(6):
        nodes = ui()
        if _controls_up(nodes):
            return nodes
        gi = find_node_ci(nodes, "Got it")
        if gi:
            tap_node(gi)
            settle("tap")
            continue
        cx, cy = _dump_center(nodes)
        if not cx:
            break
        tap(cx, cy)                       # frame-centre tap toggles controls on
        settle("tap")
    return ui()


def _player_topright_buttons(nodes):
    """The four right-side top-bar icon Buttons, left->right = playlist / speed /
    audio / subtitle. Located by class + top-strip y + right-half x (never a
    hardcoded coordinate)."""
    btns = [n for n in nodes
            if n.get("class", "").endswith("Button") and n.get("clickable") == "true"
            and n.get("_bounds") and n["_bounds"][1] < 300
            and n.get("_center") and n["_center"][0] > kit._screen_info["width"] * 0.6]
    return sorted(btns, key=lambda n: n["_center"][0])


def _flash_controls_for_shot():
    """Make the player control overlay VISIBLE for a screenshot. The overlay
    fades ~1 s after appearing while the a11y tree lingers, so a plain reveal is
    not enough — two rapid frame-centre taps (hide-if-up, then show) leave it
    freshly rendered, and we return WITHOUT a ui() dump so the caller can screencap
    before it fades."""
    base = ui()
    cx, cy = _dump_center(base)
    if not cx:
        return
    tap(cx, cy)
    time.sleep(0.25)
    tap(cx, cy)
    time.sleep(0.25)


# ══════════════════════════════════════════════════════════════════════════════
# Depth-family navigation helpers. Named and_enter_*/and_reach_* so the depth
# audit finds a backing call for every declared depth>=1 / jump_kind="reach".
# Each proves its jump with and_reach() (target appeared + source vanished) and
# increments the surface counter via and_enter().
# ══════════════════════════════════════════════════════════════════════════════

def and_reach_settings():
    """Home -> Settings. Returns fresh Settings nodes or []."""
    nodes = home_ready()
    if not nodes:
        return []
    before = and_showing(nodes)
    tap_topbar(nodes, "Settings")
    settle("tap")
    after_nodes = ui()
    if and_reach(before, and_showing(after_nodes), "Appearance", FOLDER_NAME) or \
       (find_node(after_nodes, text="Appearance") and find_node(after_nodes, text="About")):
        and_enter("settings")
        return after_nodes
    return []


def and_reach_settings_sub(settings_nodes, row, target, source=SETTINGS_SIBLING):
    """Settings root -> a subscreen. Proves target appeared + source (a root
    sibling row) vanished. Counts one surface. Returns fresh sub nodes or [].

    After the tap the subscreen animates in, so we poll the dump a few times until
    the target row has actually rendered before rendering the verdict — otherwise
    a dump caught mid-transition can miss it (an observed flake)."""
    node = find_node(settings_nodes, text=row) or scroll_into_view(row)
    if not node:
        return []
    before = and_showing(ui())
    if not tap_node(node):
        return []
    after_nodes = ui()
    for _ in range(3):
        if find_node(after_nodes, text=target):
            break
        settle("tap")
        after_nodes = ui()
    if and_reach(before, and_showing(after_nodes), target, source) or \
       (find_node(after_nodes, text=target) and not find_node(after_nodes, text=source)):
        and_enter(row.lower())
        return after_nodes
    return []


def and_reach_folder(name=FOLDER_NAME):
    """Home -> the named folder. Proves 'Navigate up' appeared + the Home-only
    '3 Videos' badge vanished. Returns fresh folder nodes or []."""
    nodes = home_ready()
    row = find_node(nodes, text=name)
    if not row:
        return []
    before = and_showing(nodes)
    if not tap_node(row):
        return []
    after_nodes = ui()
    if and_reach(before, and_showing(after_nodes), NAV_UP, FOLDER_COUNT) or \
       find_node(after_nodes, content_desc=NAV_UP):
        and_enter("folder")
        return after_nodes
    return []


def and_reach_player(title=VIDEO_BETA):
    """Home -> folder -> tap a video row -> PlayerActivity. Proves 'Play/Pause'
    appeared + folder's 'Navigate up' vanished, then reveals the controls and
    installs landscape geometry. Returns fresh player nodes or []."""
    folder_nodes = and_reach_folder()
    if not folder_nodes:
        return []
    row = find_node(folder_nodes, text=title)
    if not row:
        return []
    before = and_showing(folder_nodes)           # portrait geometry OK here
    if not tap_node(row):
        return []
    settle("launch")                             # PlayerActivity start + autoplay
    kit._screen_info = None                       # drop the stale portrait cache
    player_nodes = _reveal_player_controls()
    _use_landscape_geom(player_nodes)             # now controls are in-frame
    if and_reach(before, and_showing(player_nodes), PLAYER_MARKER, NAV_UP) or \
       find_node(player_nodes, content_desc=PLAYER_MARKER):
        and_enter("player")
        return player_nodes
    return []


def and_reach_player_dialog(which, target, tries=6):
    """From a fresh player, open the named top-bar dialog (which in
    {'speed','audio','subtitle'}) and PROVE the jump: target appeared +
    'Play/Pause' vanished.

    The overlay fades ~1 s after a centre tap even while the a11y tree still
    lists it, so we (1) learn the icon coordinate from one reveal, then (2) tap
    the frame centre and IMMEDIATELY tap the icon with no ui() dump between them
    (a dump is slow enough to miss the visible window). Retries hide the overlay
    between attempts so the next centre tap re-shows it. Counts one surface
    (depth 3 from Home). Returns the dialog nodes or []."""
    if not and_reach_player():
        return []
    idx = PLAYER_ICON[which]
    shown = _reveal_player_controls()
    _use_landscape_geom(shown)
    btns = _player_topright_buttons(shown)
    if len(btns) <= idx:
        return []
    cx, cy = _dump_center(shown)
    bx, by = btns[idx]["_center"]
    before = and_showing(shown)                  # contains 'Play/Pause' from the reveal
    for _ in range(tries):
        tap(cx, cy)                              # show controls
        time.sleep(0.35)
        tap(bx, by)                             # tap the icon within the visible window
        settle("tap")
        dlg = ui()
        if find_node(dlg, text=target):
            if and_reach(before, and_showing(dlg), target, PLAYER_MARKER) or \
               find_node(dlg, text=target):
                and_enter("player_dialog")
                return dlg
        if _controls_up(dlg):
            tap(cx, cy)                          # controls left up -> hide for next try
            settle("tap")
    return []


def and_open_search():
    """Home -> Search. Proves 'Popular folders' appeared + the Home 'Menu'
    control vanished. Returns fresh search nodes or []."""
    nodes = home_ready()
    if not nodes:
        return []
    before = and_showing(nodes)
    tap_topbar(nodes, "Search")
    settle("tap")
    after_nodes = ui()
    if and_reach(before, and_showing(after_nodes), "Popular folders", "Menu") or \
       find_node(after_nodes, text="Popular folders"):
        and_enter("search")
        return after_nodes
    return []


def _find_fab(nodes):
    """The bottom-right expand FAB: a desc-less, text-less clickable View in the
    lower-right quadrant. Derived from a fresh dump — never a hardcoded coord."""
    s = get_screen_info()
    best = None
    for n in nodes:
        if n.get("clickable") != "true":
            continue
        if n.get("text", "").strip() or n.get("content-desc", "").strip():
            continue
        b = n.get("_bounds")
        if not b:
            continue
        cx, cy = n["_center"]
        if cx < s["width"] * 0.6 or cy < s["height"] * 0.6:
            continue
        w, h = b[2] - b[0], b[3] - b[1]
        if w < 60 or h < 60 or w > s["width"] * 0.6:
            continue
        if best is None or (cy + cx) > (best["_center"][1] + best["_center"][0]):
            best = n
    return best


def and_open_fab_menu():
    """Home -> tap FAB -> the 3-pill expanded menu. Proves 'Open network stream'
    appeared. Returns fresh menu nodes or []."""
    nodes = home_ready()
    fab = _find_fab(nodes)
    if not fab:
        return []
    before = and_showing(nodes)
    if not tap_node(fab):
        return []
    after_nodes = ui()
    if and_reach(before, and_showing(after_nodes), "Open network stream", source=None) or \
       find_node(after_nodes, text="Open network stream"):
        and_enter("fab_menu")
        return after_nodes
    return []


def and_reach_network_dialog():
    """Home -> FAB menu -> 'Open network stream' -> Network Stream dialog. Proves
    'Network Stream' appeared + the sibling pill 'Open local video' vanished.
    Counts a second surface (depth 2 from Home). Returns dialog nodes or []."""
    menu = and_open_fab_menu()
    if not menu:
        return []
    pill = find_node(menu, text="Open network stream")
    if not pill:
        return []
    before = and_showing(menu)
    if not tap_node(pill):
        return []
    settle("tap")
    dlg = ui()
    if and_reach(before, and_showing(dlg), "Network Stream", "Open local video") or \
       find_node(dlg, text="Network Stream"):
        and_enter("network_dialog")
        return dlg
    return []


# ══════════════════════════════════════════════════════════════════════════════
# (1) Home -> Settings. depth=1, reach.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_home_to_settings", "navigation_settings_rendered_vlm"))
def test_home_to_settings():
    settings_nodes = and_reach_settings()
    ok = bool(settings_nodes) and bool(find_node(settings_nodes, text="Appearance"))
    record("navigation_home_to_settings", ok,
           "" if ok else "feature_missing: Settings surface not reached from the Home gear",
           depth=1, jump_kind="reach",
           expect="Settings category list ('Appearance') visible; Home 'Download' row gone")

    vlm_assert("navigation_settings_rendered",
               "Is this a settings screen showing a vertical single-column list of "
               "category rows, each with a small leading icon on the left, and a "
               "back arrow at the top-left?",
               RESULTS_DIR, depth=1, jump_kind="reach", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# (2) Settings -> Appearance -> BACK -> Settings. depth=2 round trip, reach.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_settings_to_appearance",
                   "navigation_appearance_back_to_settings"))
def test_appearance_roundtrip():
    settings_nodes = and_reach_settings()
    sub = and_reach_settings_sub(settings_nodes, "Appearance", "Dark theme",
                                 source=SETTINGS_SIBLING)
    fwd_ok = bool(sub) and bool(find_node(sub, text="Dark theme"))
    record("navigation_settings_to_appearance", fwd_ok,
           "" if fwd_ok else "feature_missing: Appearance subscreen not reached",
           depth=2, jump_kind="reach",
           expect="'Dark theme' row visible; sibling 'Media library' row gone")

    # BACK unwinds one hop: the sibling rows return and the sub content is gone.
    back_before = and_showing(ui())
    and_back()
    back_after = ui()
    back_ok = (and_reach(back_before, and_showing(back_after),
                         SETTINGS_SIBLING, "Dark theme")
               or (find_node(back_after, text=SETTINGS_SIBLING)
                   and not find_node(back_after, text="Dark theme")))
    record("navigation_appearance_back_to_settings", bool(fwd_ok and back_ok),
           "" if (fwd_ok and back_ok)
           else "behavior_wrong: BACK did not restore the Settings category list",
           depth=1, jump_kind="reach",
           expect="Settings root restored ('Media library' back, 'Dark theme' gone) after one BACK")


# ══════════════════════════════════════════════════════════════════════════════
# (3) Settings -> Media library. depth=2, reach. (source is a different root row.)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_settings_to_media_library",))
def test_settings_to_media_library():
    settings_nodes = and_reach_settings()
    sub = and_reach_settings_sub(settings_nodes, "Media library",
                                 "Mark last played media", source=SETTINGS_SIBLING_ALT)
    ok = bool(sub) and bool(find_node(sub, text="Mark last played media"))
    record("navigation_settings_to_media_library", ok,
           "" if ok else "feature_missing: Media library subscreen not reached",
           depth=2, jump_kind="reach",
           expect="'Mark last played media' row visible; sibling 'Appearance' row gone")


# ══════════════════════════════════════════════════════════════════════════════
# (4) Settings -> Player. depth=2, reach.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_settings_to_player_settings",))
def test_settings_to_player_settings():
    settings_nodes = and_reach_settings()
    sub = and_reach_settings_sub(settings_nodes, "Player", "Material You controls",
                                 source=SETTINGS_SIBLING)
    ok = bool(sub) and bool(find_node(sub, text="Material You controls"))
    record("navigation_settings_to_player_settings", ok,
           "" if ok else "feature_missing: Player settings subscreen not reached",
           depth=2, jump_kind="reach",
           expect="'Material You controls' row visible; sibling 'Media library' row gone")


# ══════════════════════════════════════════════════════════════════════════════
# (5) Settings -> About. depth=2, reach.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_settings_to_about",))
def test_settings_to_about():
    settings_nodes = and_reach_settings()
    sub = and_reach_settings_sub(settings_nodes, "About", "by anilbeesetti",
                                 source=SETTINGS_SIBLING)
    ok = bool(sub) and bool(find_node(sub, text="by anilbeesetti"))
    record("navigation_settings_to_about", ok,
           "" if ok else "feature_missing: About subscreen not reached",
           depth=2, jump_kind="reach",
           expect="'by anilbeesetti' credit visible; sibling 'Media library' row gone")


# ══════════════════════════════════════════════════════════════════════════════
# (6) Settings -> Audio / Subtitle / Gestures. depth=2 each, reach. (breadth)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_settings_to_audio",))
def test_settings_to_audio():
    settings_nodes = and_reach_settings()
    sub = and_reach_settings_sub(settings_nodes, "Audio", "Volume boost",
                                 source=SETTINGS_SIBLING)
    ok = bool(sub) and bool(find_node(sub, text="Volume boost"))
    record("navigation_settings_to_audio", ok,
           "" if ok else "feature_missing: Audio subscreen not reached",
           depth=2, jump_kind="reach",
           expect="'Volume boost' row visible; sibling 'Media library' row gone")


@and_test(expects=("navigation_settings_to_subtitle",))
def test_settings_to_subtitle():
    settings_nodes = and_reach_settings()
    sub = and_reach_settings_sub(settings_nodes, "Subtitle", "Embedded styles",
                                 source=SETTINGS_SIBLING)
    ok = bool(sub) and bool(find_node(sub, text="Embedded styles"))
    record("navigation_settings_to_subtitle", ok,
           "" if ok else "feature_missing: Subtitle subscreen not reached",
           depth=2, jump_kind="reach",
           expect="'Embedded styles' row visible; sibling 'Media library' row gone")


@and_test(expects=("navigation_settings_to_gestures",))
def test_settings_to_gestures():
    settings_nodes = and_reach_settings()
    sub = and_reach_settings_sub(settings_nodes, "Gestures", "Seek gesture",
                                 source=SETTINGS_SIBLING)
    ok = bool(sub) and bool(find_node(sub, text="Seek gesture"))
    record("navigation_settings_to_gestures", ok,
           "" if ok else "feature_missing: Gestures subscreen not reached",
           depth=2, jump_kind="reach",
           expect="'Seek gesture' row visible; sibling 'Media library' row gone")


# ══════════════════════════════════════════════════════════════════════════════
# (7) Home -> Download folder. depth=1, reach.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_home_to_folder",))
def test_home_to_folder():
    folder_nodes = and_reach_folder()
    ok = bool(folder_nodes) and bool(find_node(folder_nodes, text=VIDEO_BETA)) \
        and bool(find_node(folder_nodes, content_desc=NAV_UP))
    record("navigation_home_to_folder", ok,
           "" if ok else "feature_missing: Download folder contents not reached",
           depth=1, jump_kind="reach",
           expect="'Navigate up' + video rows visible; Home '3 Videos' badge gone")


# ══════════════════════════════════════════════════════════════════════════════
# (8) Folder -> Player. depth=2 from Home (Home->folder->player). reach.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_folder_to_player", "navigation_player_overlay_vlm"))
def test_folder_to_player():
    player_nodes = and_reach_player(VIDEO_BETA)
    ok = bool(player_nodes) and bool(find_node(player_nodes, content_desc=PLAYER_MARKER))
    record("navigation_folder_to_player", ok,
           "" if ok else "feature_missing: PlayerActivity (Play/Pause) not reached from the folder",
           depth=2, jump_kind="reach",
           expect="player 'Play/Pause' control visible; folder 'Navigate up' gone")

    # The overlay fades within ~1 s while the a11y tree lingers, so flash it fresh
    # (two rapid centre taps) and screenshot immediately (vlm_assert's screencap
    # runs first thing, before it fades again).
    if ok:
        _flash_controls_for_shot()
    vlm_assert("navigation_player_overlay",
               "Is there a play/pause control in the CENTRE of the screen and a "
               "horizontal seek bar in the LOWER part of the screen?",
               RESULTS_DIR, depth=2, jump_kind="reach", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# (9) Player -> BACK -> Folder. back-stack integrity, depth=2 forward.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_player_back_to_folder",))
def test_player_back_to_folder():
    player_nodes = and_reach_player(VIDEO_BETA)
    reached = bool(player_nodes) and bool(find_node(player_nodes, content_desc=PLAYER_MARKER))
    before = and_showing(player_nodes) if reached else set()
    and_back()
    kit._screen_info = None                       # returning to portrait picker
    settle("tap")
    folder_after = ui()
    back_ok = reached and (
        and_reach(before, and_showing(folder_after), NAV_UP, PLAYER_MARKER)
        or (find_node(folder_after, content_desc=NAV_UP)
            and not find_node(folder_after, content_desc=PLAYER_MARKER)))
    record("navigation_player_back_to_folder", bool(back_ok),
           "" if back_ok else "behavior_wrong: BACK from the player did not return to the folder",
           depth=2, jump_kind="reach",
           expect="folder 'Navigate up' restored, player 'Play/Pause' gone after one BACK")


# ══════════════════════════════════════════════════════════════════════════════
# (10) Folder -> BACK -> Home. back-stack integrity, depth=1 forward.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_folder_back_to_home",))
def test_folder_back_to_home():
    folder_nodes = and_reach_folder()
    reached = bool(folder_nodes) and bool(find_node(folder_nodes, content_desc=NAV_UP))
    before = and_showing(folder_nodes) if reached else set()
    and_back()
    settle("tap")
    home_after = ui()
    back_ok = reached and (
        and_reach(before, and_showing(home_after), FOLDER_COUNT, NAV_UP)
        or (find_node(home_after, text=FOLDER_COUNT)
            and not find_node(home_after, content_desc=NAV_UP)))
    record("navigation_folder_back_to_home", bool(back_ok),
           "" if back_ok else "behavior_wrong: BACK from the folder did not return Home",
           depth=1, jump_kind="reach",
           expect="Home '3 Videos' badge restored, folder 'Navigate up' gone after one BACK")


# ══════════════════════════════════════════════════════════════════════════════
# (11) Home -> Search. depth=1, reach.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_home_to_search", "navigation_search_rendered_vlm"))
def test_home_to_search():
    search_nodes = and_open_search()
    ok = bool(search_nodes) and bool(find_node(search_nodes, text="Popular folders"))
    record("navigation_home_to_search", ok,
           "" if ok else "feature_missing: Search surface not reached from the Home search icon",
           depth=1, jump_kind="reach",
           expect="'Popular folders' section visible; Home 'Menu' control gone")

    vlm_assert("navigation_search_rendered",
               "Is there a search input field spanning the TOP of the screen "
               "(with a back arrow to its left), above the rest of the content?",
               RESULTS_DIR, depth=1, jump_kind="reach", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# (12) Search -> BACK -> Home. back-stack integrity. The search field auto-focuses
#      the keyboard, so the first BACK dismisses the IME and a second returns Home.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_search_back_to_home",))
def test_search_back_to_home():
    search_nodes = and_open_search()
    reached = bool(search_nodes) and bool(find_node(search_nodes, text="Popular folders"))
    before = and_showing(search_nodes) if reached else set()
    home_after = search_nodes
    # Up to two BACKs: one may only close the soft keyboard.
    for _ in range(2):
        and_back()
        settle("tap")
        home_after = ui()
        if find_node(home_after, content_desc="Menu"):
            break
    back_ok = reached and (
        and_reach(before, and_showing(home_after), "Menu", "Popular folders")
        or (find_node(home_after, content_desc="Menu")
            and not find_node(home_after, text="Popular folders")))
    record("navigation_search_back_to_home", bool(back_ok),
           "" if back_ok else "behavior_wrong: BACK from Search did not return Home",
           depth=1, jump_kind="reach",
           expect="Home 'Menu' control restored, 'Popular folders' gone after BACK")


# ══════════════════════════════════════════════════════════════════════════════
# (13) FAB -> Network Stream dialog -> Cancel -> Home. depth=2 forward, reach.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_fab_to_network_dialog",
                   "navigation_network_dialog_cancel_home"))
def test_network_dialog_roundtrip():
    dlg = and_reach_network_dialog()
    fwd_ok = bool(dlg) and bool(find_node(dlg, text="Network Stream")) \
        and bool(find_by_class(dlg, "EditText"))
    record("navigation_fab_to_network_dialog", fwd_ok,
           "" if fwd_ok else "feature_missing: Network Stream dialog not reached via the FAB",
           depth=2, jump_kind="reach",
           expect="'Network Stream' title + URL EditText visible; pill 'Open local video' gone")

    # Cancel dismisses the dialog and restores Home.
    cancel = find_node(dlg, text="Cancel") if dlg else None
    before = and_showing(dlg) if dlg else set()
    tapped = tap_node(cancel) if cancel else False
    settle("tap")
    home_after = ui()
    cancel_ok = fwd_ok and tapped and (
        and_reach(before, and_showing(home_after), FOLDER_NAME, "Network Stream")
        or (find_node(home_after, text=FOLDER_NAME)
            and not find_node(home_after, text="Network Stream")))
    record("navigation_network_dialog_cancel_home", bool(cancel_ok),
           "" if cancel_ok else "behavior_wrong: Cancel did not dismiss the dialog back to Home",
           depth=1, jump_kind="reach",
           expect="Home 'Download' restored, 'Network Stream' dialog gone after Cancel")


# ══════════════════════════════════════════════════════════════════════════════
# (14) Player -> Playback speed dialog -> BACK -> Player. depth=3 forward, reach.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_player_to_speed_dialog",
                   "navigation_speed_dialog_back_to_player",
                   "navigation_speed_dialog_rendered_vlm"))
def test_player_speed_dialog():
    dlg = and_reach_player_dialog("speed", "Select playback speed")
    fwd_ok = bool(dlg) and bool(find_node(dlg, text="Select playback speed"))
    record("navigation_player_to_speed_dialog", fwd_ok,
           "" if fwd_ok else "feature_missing: playback-speed dialog not reached from the player",
           depth=3, jump_kind="reach",
           expect="'Select playback speed' dialog visible; player 'Play/Pause' gone")

    # The dialog stays up (it does not auto-hide) -> screenshot it for the VLM.
    vlm_assert("navigation_speed_dialog_rendered",
               "Is a dialog titled about playback speed showing a grid of small "
               "rounded speed-value chips (like 0.5, 1.0, 2.0) arranged in rows?",
               RESULTS_DIR, depth=3, jump_kind="reach", tag="shape")

    # BACK dismisses the dialog; the player controls become reachable again.
    before = and_showing(dlg) if dlg else set()
    and_back()
    settle("tap")
    after = _reveal_player_controls()
    _use_landscape_geom(after)
    back_ok = fwd_ok and (
        and_reach(before, and_showing(after), PLAYER_MARKER, "Select playback speed")
        or (find_node(after, content_desc=PLAYER_MARKER)
            and not find_node(after, text="Select playback speed")))
    record("navigation_speed_dialog_back_to_player", bool(back_ok),
           "" if back_ok else "behavior_wrong: BACK did not return from the speed dialog to the player",
           depth=2, jump_kind="reach",
           expect="player 'Play/Pause' reachable again, speed dialog gone after BACK")


# ══════════════════════════════════════════════════════════════════════════════
# (15) Player -> Audio track dialog. depth=3 forward, reach.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_player_to_audio_dialog",
                   "navigation_audio_dialog_rendered_vlm"))
def test_player_audio_dialog():
    dlg = and_reach_player_dialog("audio", "Select audio track")
    ok = bool(dlg) and bool(find_node(dlg, text="Select audio track")) \
        and bool(find_node(dlg, text="Audio Track #1"))
    record("navigation_player_to_audio_dialog", ok,
           "" if ok else "feature_missing: audio-track dialog not reached from the player",
           depth=3, jump_kind="reach",
           expect="'Select audio track' + 'Audio Track #1' visible; player 'Play/Pause' gone")

    vlm_assert("navigation_audio_dialog_rendered",
               "Is a dialog titled about audio track showing a vertical list of "
               "selectable track options (one row highlighted/selected)?",
               RESULTS_DIR, depth=3, jump_kind="reach", tag="layout")


# ══════════════════════════════════════════════════════════════════════════════
# (16) Player -> Subtitle track dialog. depth=3 forward, reach.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_player_to_subtitle_dialog",
                   "navigation_subtitle_dialog_rendered_vlm"))
def test_player_subtitle_dialog():
    dlg = and_reach_player_dialog("subtitle", "Select subtitle track")
    ok = bool(dlg) and bool(find_node(dlg, text="Select subtitle track")) \
        and bool(find_node(dlg, text="Open local subtitle"))
    record("navigation_player_to_subtitle_dialog", ok,
           "" if ok else "feature_missing: subtitle-track dialog not reached from the player",
           depth=3, jump_kind="reach",
           expect="'Select subtitle track' + 'Open local subtitle' visible; player 'Play/Pause' gone")

    vlm_assert("navigation_subtitle_dialog_rendered",
               "Is a dialog titled about subtitle track showing two numeric "
               "stepper controls near the bottom (each with - and + buttons "
               "around a value)?",
               RESULTS_DIR, depth=3, jump_kind="reach", tag="shape")


# ══════════════════════════════════════════════════════════════════════════════
# (17) Deep chain showcase: Home -> Settings -> Player -> BACK -> Settings ->
#      BACK -> Home. Asserts the correct surface at each hop; the deepest reach
#      (the Player subscreen at depth 2) is proven with and_reach.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_deep_chain_settings_player",))
def test_deep_chain_settings_player():
    settings_nodes = and_reach_settings()                 # hop 1: Home -> Settings
    if not settings_nodes:
        record("navigation_deep_chain_settings_player", False,
               "setup_failed: Settings not reached for the deep chain",
               depth=2, jump_kind="reach",
               expect="Player sub at depth 2, then BACK->Settings->Home unwinds each hop")
        return
    sub = and_reach_settings_sub(settings_nodes, "Player", "Material You controls",
                                 source=SETTINGS_SIBLING)  # hop 2: -> Player sub
    deep_ok = bool(sub) and bool(find_node(sub, text="Material You controls"))

    # BACK to Settings root (sibling rows return, sub content gone).
    b1 = and_showing(ui())
    and_back()
    settings_again = ui()
    up1_ok = (and_reach(b1, and_showing(settings_again), SETTINGS_SIBLING,
                        "Material You controls")
              or (find_node(settings_again, text=SETTINGS_SIBLING)
                  and not find_node(settings_again, text="Material You controls")))

    # BACK to Home (Home folder badge returns, Settings category rows gone).
    b2 = and_showing(settings_again)
    and_back()
    settle("tap")
    home_again = ui()
    up2_ok = (and_reach(b2, and_showing(home_again), FOLDER_COUNT, "About")
              or (find_node(home_again, text=FOLDER_COUNT)
                  and not find_node(home_again, text="About")))

    ok = deep_ok and up1_ok and up2_ok
    msg = ""
    if not deep_ok:
        msg = "feature_missing: could not reach the Player subscreen at depth 2"
    elif not up1_ok:
        msg = "behavior_wrong: first BACK did not return to the Settings root"
    elif not up2_ok:
        msg = "behavior_wrong: second BACK did not return Home"
    record("navigation_deep_chain_settings_player", ok, msg,
           depth=2, jump_kind="reach",
           expect="Player sub reached at depth 2; BACK->Settings root->Home unwinds each hop")


TESTS = [
    test_home_to_settings,
    test_appearance_roundtrip,
    test_settings_to_media_library,
    test_settings_to_player_settings,
    test_settings_to_about,
    test_settings_to_audio,
    test_settings_to_subtitle,
    test_settings_to_gestures,
    test_home_to_folder,
    test_folder_to_player,
    test_player_back_to_folder,
    test_folder_back_to_home,
    test_home_to_search,
    test_search_back_to_home,
    test_network_dialog_roundtrip,
    test_player_speed_dialog,
    test_player_audio_dialog,
    test_player_subtitle_dialog,
    test_deep_chain_settings_player,
]

if __name__ == "__main__":
    run_suite(TESTS, "navigation")