File size: 40,611 Bytes
966ca88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
#!/usr/bin/env python3
"""TEXT lane for NextPlayer (dev.anilbeesetti.nextplayer.debug).

This lane owns CONTENT / OUTPUT strings that a user action PRODUCES, and it is
the sole owner of exact-string equality. Every test performs an interaction and
then reads the resulting string out of a FRESH ui() and asserts it matches what
the original renders. The discriminating half is the CHANGE: the string is
ABSENT before the trigger and PRESENT after — a hardcoded label present at launch
would pass on a dead shell, so the dynamic ones are asserted absent-then-present.

Ground truth (observed live on the running original before authoring):
  * Home folder row: name "Download", count chip "3 Videos", parent path
    "/storage/emulated/0" (folder-level). Title bar "Next Player Debug".
  * Inside the Download folder every video row shows the FULL path
    "/storage/emulated/0/Download"; titles have NO extension (alpha_clip,
    beta_movie, gamma_reel); folder title bar reads "Download".
  * Search (top-bar "Search"): typing "beta" -> header EXACTLY "Videos (1)" and a
    result row "beta_movie"; "gamma" -> "Videos (1)" + "gamma_reel"; "movie" ->
    "Videos (1)" + "beta_movie"; "zzznope" -> the empty-state "No results found"
    (NO "Videos (N)" header at all).
  * PlayerActivity title bar shows the filename WITH extension: "beta_movie.mp4"
    / "gamma_reel.mp4" / "alpha_clip.mp4". The Loop button content-desc is one of
    "Loop: Off"/"Loop: One"/"Loop: All" and advances Off->One->All->Off on tap
    (the setting PERSISTS across restarts, so we read the CURRENT desc and assert
    the NEXT one, never a fixed start value).
  * Settings > Player: row "Controller timeout" subtitle "4 seconds"; row
    "Default playback speed" subtitle "1.0". Settings > Appearance: row
    "Dark theme" subtitle "System Default". Settings > About: "by anilbeesetti",
    "Libraries", "Github", "UPI" + "anilbeesetti10@oksbi". (The version number
    "0.16.3 (56)" is a BUILD CONSTANT and is deliberately NOT asserted.)
  * FAB -> "Open network stream" opens the "Network Stream" dialog with label
    "Enter a network URL:" and a placeholder text "http://example.com/example.mp4"
    (rendered as its own TextView; the EditText's own text is empty). Typing into
    the field reads back from a fresh dump; we dismiss with "Cancel" (NOT BACK,
    which would close the whole dialog).

CEDES (per lane contract): a computed/derived number -> computation (the folder
"00:16" total, the search COUNT as a number); a checked bit -> states; whether a
label's screen is reachable -> navigation (a label tapped to navigate is nav's
trigger, not our assertion); a widget class present -> structure; the content of
a record the user created -> interaction. Here we assert only the exact WORDS an
interaction produced.

Fixtures: the 3 sample videos are authored into fixtures/ and mirrored to the
device by push_fixtures() (run_suite() calls it once); reached through
fixture_on_device(name), never a hand-pushed path.
"""
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 strings (observed on the running original) ─────────────────────
FOLDER_NAME = "Download"
FOLDER_COUNT = "3 Videos"                       # Home-only count chip
FOLDER_PATH = "/storage/emulated/0/Download"    # shown on each video row INSIDE
NAV_UP = "Navigate up"
PLAYER_MARKER = "Play/Pause"                    # content-desc unique to the player
POPULAR = "Popular folders"                     # Search screen section
SEARCH_EMPTY = "No results found"               # zero-match empty state
LOOP_DESCS = ("Loop: Off", "Loop: One", "Loop: All")
SETTINGS_SIBLING = "Media library"              # a Settings-root row, gone on subs

# 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")


def next_loop(cur):
    """The desc that a Loop tap should produce next (Off->One->All->Off)."""
    if cur in LOOP_DESCS:
        return LOOP_DESCS[(LOOP_DESCS.index(cur) + 1) % len(LOOP_DESCS)]
    return None


def all_text(nodes):
    """All non-empty visible text, joined — a cheap 'does this string appear'."""
    return " | ".join(n.get("text", "") for n in nodes if n.get("text", "").strip())


def has_text(nodes, s):
    """Exact-match on any node's text attribute (this lane's specialty)."""
    return any(n.get("text", "").strip() == s for n in nodes)


def sub_of(nodes, label):
    """The subtitle string that renders directly BELOW a settings row `label`.

    Settings rows are title-over-subtitle: the subtitle is the text node whose
    x overlaps the label's and whose top edge sits just below the label's. Return
    the closest such node's text, or "" if none."""
    row = find_node(nodes, text=label)
    if not row or "_bounds" not in row:
        return ""
    lx1, ly1, lx2, ly2 = row["_bounds"]
    best, best_dy = "", 10 ** 9
    for n in nodes:
        if n is row or not n.get("text", "").strip() or "_bounds" not in n:
            continue
        x1, y1, x2, y2 = n["_bounds"]
        # horizontal overlap with the label + starts below it
        if x2 <= lx1 or x1 >= lx2 or y1 < ly2 - 5:
            continue
        dy = y1 - ly2
        if 0 <= dy < best_dy:
            best, best_dy = n.get("text", "").strip(), dy
    return best


# ══════════════════════════════════════════════════════════════════════════════
# 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 top-bar icon by content-desc. The desc node itself is not clickable
    — its wrapping View is — so tap the tightest clickable ancestor whose bounds
    contain 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 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="beta_movie"))
    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


# ── Depth-family reach helpers (named and_enter_*/and_reach_* so the depth audit
# finds a backing call for every declared depth>=1). Each opens a surface and
# increments the surface counter via and_enter(). ──────────────────────────────

def and_reach_search():
    """Home -> Search screen. Returns fresh search nodes (with the EditText) or []."""
    nodes = home_ready()
    if not nodes:
        return []
    tap_topbar(nodes, "Search")
    settle("tap")
    after = ui()
    if find_node(after, text=POPULAR) or find_by_class(after, "EditText"):
        and_enter("search")
        return after
    return []


def and_search_for(query):
    """Open Search, type `query`, and return the fresh result nodes (or []).

    The Search EditText auto-focuses; we still route through type_text so focus is
    verified. We do NOT press ENTER — results filter live as characters arrive."""
    nodes = and_reach_search()
    if not nodes:
        return []
    field = find_by_class(nodes, "EditText")
    if not field:
        return []
    type_text(field[0], query)
    settle("keyboard")
    return ui()


def and_enter_folder(name=FOLDER_NAME):
    """Home -> the named folder. Returns fresh folder nodes (video rows) or []."""
    nodes = home_ready()
    row = find_node(nodes, text=name)
    if not row:
        return []
    if not tap_node(row):
        return []
    settle("tap")
    after = ui()
    if find_node(after, content_desc=NAV_UP) or has_text(after, FOLDER_PATH):
        and_enter("folder")
        return after
    return []


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


def and_reach_settings_sub(row, marker):
    """Home -> Settings -> the `row` subscreen (confirmed by `marker` text).
    Counts a second surface (depth 2 from Home). Returns fresh sub nodes or []."""
    settings = and_reach_settings()
    if not settings:
        return []
    node = find_node(settings, text=row) or scroll_into_view(row)
    if not node:
        return []
    if not tap_node(node):
        return []
    after = ui()
    for _ in range(3):
        if find_node(after, text=marker):
            break
        settle("tap")
        after = ui()
    if find_node(after, text=marker):
        and_enter(row.lower())
        return after
    return []


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 (the landscape player window reports portrait via `wm size`)."""
    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)
                or any(n.get("text", "").endswith(".mp4") for n in nodes))


def _in_player():
    return "PlayerActivity" in get_current_activity()


def and_enter_player(title="beta_movie"):
    """Home -> Download -> tap the video row -> PlayerActivity, then REVEAL the
    auto-hiding controls and install landscape geometry. Returns fresh player
    nodes with controls up, or [].

    Backs depth=2 (Home->folder->player). The fixtures are SHORT (3-8 s), so we do
    NOT pre-sleep the full launch settle before revealing — we tap the frame
    centre in a tight loop and, if the clip ended and popped back to the folder,
    re-tap the row. `title` is the picker title WITHOUT extension."""
    folder = and_enter_folder()
    if not folder:
        return []
    row = find_node(folder, text=title)
    if not row:
        return []
    if not tap_node(row):
        return []
    time.sleep(1.0)
    kit._screen_info = None                       # drop the stale portrait cache
    and_enter("player")
    nodes = []
    for _ in range(5):
        if not _in_player():
            # clip ended / popped back to the folder — restart it from the row
            folder = ui()
            r = find_node(folder, text=title)
            if r:
                tap_node(r)
                time.sleep(1.0)
                kit._screen_info = None
            continue
        nodes = ui()
        if _controls_up(nodes):
            _use_landscape_geom(nodes)
            return nodes
        cx, cy = _dump_center(nodes)
        if not cx:
            break
        tap(cx, cy)
        time.sleep(0.4)
    nodes = ui()
    if _controls_up(nodes):
        _use_landscape_geom(nodes)
        return nodes
    return []


# ══════════════════════════════════════════════════════════════════════════════
# (A) Search result header + row strings. depth=1, transition.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_search_beta_header", "text_search_beta_header_vlm"))
def test_search_beta_header():
    search = and_reach_search()
    if not search:
        record("text_search_beta_header", False,
               "setup_failed: Search screen not reached from the Home search icon",
               depth=1, jump_kind="transition", expect="header reads 'Videos (1)'")
        vlm_assert("text_search_beta_header",
                   "Does a header reading exactly 'Videos (1)' appear near the top "
                   "of the search results, above a single result row?",
                   RESULTS_DIR, expect="NO", depth=1, jump_kind="transition",
                   tag="content")
        return
    absent = not has_text(search, "Videos (1)")
    field = find_by_class(search, "EditText")
    if not field:
        record("text_search_beta_header", False,
               "setup_failed: no search EditText on the Search screen",
               depth=1, jump_kind="transition", expect="header reads 'Videos (1)'")
        return
    type_text(field[0], "beta")
    settle("keyboard")
    after = ui()
    header_ok = has_text(after, "Videos (1)")
    row_ok = has_text(after, "beta_movie")
    ok = absent and header_ok and row_ok
    record("text_search_beta_header", ok,
           "" if ok else "behavior_wrong: searching 'beta' did not yield header "
           "'Videos (1)' + row 'beta_movie'",
           depth=1, jump_kind="transition",
           expect="header 'Videos (1)' and result row 'beta_movie' after typing 'beta'")

    vlm_assert("text_search_beta_header",
               "Is a header reading exactly 'Videos (1)' shown near the top of the "
               "search results, directly above one result row?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
               tag="content")


@and_test(expects=("text_search_gamma_row",))
def test_search_gamma_row():
    after = and_search_for("gamma")
    if not after:
        record("text_search_gamma_row", False,
               "setup_failed: Search screen not reached / no EditText",
               depth=1, jump_kind="transition",
               expect="header 'Videos (1)' + row 'gamma_reel'")
        return
    ok = has_text(after, "Videos (1)") and has_text(after, "gamma_reel")
    record("text_search_gamma_row", ok,
           "" if ok else "behavior_wrong: searching 'gamma' did not yield "
           "'Videos (1)' + row 'gamma_reel'",
           depth=1, jump_kind="transition",
           expect="header 'Videos (1)' and result row 'gamma_reel' after typing 'gamma'")


@and_test(expects=("text_search_substring_movie",))
def test_search_substring_movie():
    after = and_search_for("movie")
    if not after:
        record("text_search_substring_movie", False,
               "setup_failed: Search screen not reached / no EditText",
               depth=1, jump_kind="transition",
               expect="header 'Videos (1)' + row 'beta_movie'")
        return
    # 'movie' is a substring of only beta_movie -> exactly one match.
    ok = has_text(after, "Videos (1)") and has_text(after, "beta_movie")
    record("text_search_substring_movie", ok,
           "" if ok else "behavior_wrong: substring 'movie' did not match exactly "
           "beta_movie (expected header 'Videos (1)')",
           depth=1, jump_kind="transition",
           expect="header 'Videos (1)' and row 'beta_movie' after typing 'movie'")


@and_test(expects=("text_search_empty_state",))
def test_search_empty_state():
    search = and_reach_search()
    if not search:
        record("text_search_empty_state", False,
               "setup_failed: Search screen not reached",
               depth=1, jump_kind="transition", expect="empty state 'No results found'")
        return
    absent = not has_text(search, SEARCH_EMPTY)
    field = find_by_class(search, "EditText")
    if not field:
        record("text_search_empty_state", False,
               "setup_failed: no search EditText on the Search screen",
               depth=1, jump_kind="transition", expect="empty state 'No results found'")
        return
    type_text(field[0], "zzznope")
    settle("keyboard")
    after = ui()
    # A non-matching query renders the empty-state string AND no 'Videos (' header.
    present = has_text(after, SEARCH_EMPTY)
    no_header = not any(n.get("text", "").startswith("Videos (") for n in after)
    ok = absent and present and no_header
    record("text_search_empty_state", ok,
           "" if ok else "behavior_wrong: a non-matching query did not render the "
           "'No results found' empty state",
           depth=1, jump_kind="transition",
           expect="'No results found' shown (and no 'Videos (N)' header) for a non-matching query")


# ══════════════════════════════════════════════════════════════════════════════
# (B) Player title-bar filename (WITH extension). depth=2, transition.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_player_title_beta", "text_player_title_beta_vlm"))
def test_player_title_beta():
    player = and_enter_player("beta_movie")
    if not player:
        record("text_player_title_beta", False,
               "setup_failed: could not reveal PlayerActivity controls for beta_movie",
               depth=2, jump_kind="transition", expect="title bar reads 'beta_movie.mp4'")
        vlm_assert("text_player_title_beta",
                   "Is the text 'beta_movie.mp4' shown as a title in the top bar of "
                   "the video player, to the right of a back arrow?",
                   RESULTS_DIR, expect="NO", depth=2, jump_kind="transition",
                   tag="content")
        return
    ok = has_text(player, "beta_movie.mp4")
    record("text_player_title_beta", ok,
           "" if ok else "behavior_wrong: player top bar did not show 'beta_movie.mp4'",
           depth=2, jump_kind="transition",
           expect="player top-bar title reads 'beta_movie.mp4' (with the .mp4 extension)")

    vlm_assert("text_player_title_beta",
               "Is the text 'beta_movie.mp4' shown as a title in the top bar of the "
               "video player, to the right of a back arrow?",
               RESULTS_DIR, expect="YES", depth=2, jump_kind="transition",
               tag="content")


@and_test(expects=("text_player_title_gamma",))
def test_player_title_gamma():
    player = and_enter_player("gamma_reel")
    if not player:
        record("text_player_title_gamma", False,
               "setup_failed: could not reveal PlayerActivity controls for gamma_reel",
               depth=2, jump_kind="transition", expect="title bar reads 'gamma_reel.mp4'")
        return
    ok = has_text(player, "gamma_reel.mp4")
    record("text_player_title_gamma", ok,
           "" if ok else "behavior_wrong: player top bar did not show 'gamma_reel.mp4'",
           depth=2, jump_kind="transition",
           expect="player top-bar title reads 'gamma_reel.mp4' (with the .mp4 extension)")


@and_test(expects=("text_player_title_alpha",))
def test_player_title_alpha():
    player = and_enter_player("alpha_clip")
    if not player:
        record("text_player_title_alpha", False,
               "setup_failed: could not reveal PlayerActivity controls for alpha_clip",
               depth=2, jump_kind="transition", expect="title bar reads 'alpha_clip.mp4'")
        return
    ok = has_text(player, "alpha_clip.mp4")
    record("text_player_title_alpha", ok,
           "" if ok else "behavior_wrong: player top bar did not show 'alpha_clip.mp4'",
           depth=2, jump_kind="transition",
           expect="player top-bar title reads 'alpha_clip.mp4' (with the .mp4 extension)")


# ══════════════════════════════════════════════════════════════════════════════
# (C) Player Loop content-desc string advances on tap. depth=2, transition.
#     The Loop setting PERSISTS across restarts, so read the CURRENT desc, tap
#     once, and assert it became the correct NEXT desc — never a fixed start.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_loop_desc_advances",))
def test_loop_desc_advances():
    player = and_enter_player("beta_movie")
    if not player:
        record("text_loop_desc_advances", False,
               "setup_failed: could not reveal PlayerActivity controls",
               depth=2, jump_kind="transition", expect="Loop desc advances to the next value")
        return
    loop = None
    cur = None
    for d in LOOP_DESCS:
        n = find_node(player, content_desc=d)
        if n:
            loop, cur = n, d
            break
    if not loop:
        record("text_loop_desc_advances", False,
               "feature_missing: no 'Loop: Off/One/All' button in the player",
               depth=2, jump_kind="transition", expect="Loop desc advances to the next value")
        return
    want = next_loop(cur)
    tap_node(loop)
    settle("tap")
    after = _reveal_after_action(player)
    ok = bool(want) and bool(find_node(after, content_desc=want))
    record("text_loop_desc_advances", ok,
           "" if ok else f"behavior_wrong: Loop desc did not advance '{cur}' -> '{want}'",
           depth=2, jump_kind="transition",
           expect=f"Loop button content-desc changed from '{cur}' to '{want}' after one tap")


def _reveal_after_action(prev_nodes):
    """After a player-control tap the overlay may have started to fade; re-reveal
    and re-install geometry, then return a fresh dump."""
    _use_landscape_geom(prev_nodes)
    for _ in range(4):
        nodes = ui()
        if _controls_up(nodes):
            _use_landscape_geom(nodes)
            return nodes
        cx, cy = _dump_center(nodes)
        if not cx:
            break
        tap(cx, cy)
        time.sleep(0.35)
    return ui()


# ══════════════════════════════════════════════════════════════════════════════
# (D) Folder row strings. Home-level "Download"/"3 Videos" (depth 0) and the
#     video-row path produced by entering the folder (depth 1).
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_home_folder_labels", "text_home_folder_labels_vlm"))
def test_home_folder_labels():
    nodes = home_ready()
    if not nodes:
        record("text_home_folder_labels", False,
               "setup_failed: Home picker did not render its folder list",
               depth=0, jump_kind="value",
               expect="folder row shows 'Download' and count chip '3 Videos'")
        vlm_assert("text_home_folder_labels",
                   "Is a folder entry labeled 'Download' shown together with a small "
                   "badge/chip reading '3 Videos' on the same row?",
                   RESULTS_DIR, expect="NO", depth=0, jump_kind="value", tag="content")
        return
    name_ok = has_text(nodes, FOLDER_NAME)
    count_ok = has_text(nodes, FOLDER_COUNT)
    ok = name_ok and count_ok
    record("text_home_folder_labels", ok,
           "" if ok else "behavior_wrong: Home folder row missing 'Download' and/or "
           "the '3 Videos' count chip",
           depth=0, jump_kind="value",
           expect="Home folder row shows 'Download' and count chip '3 Videos'")

    vlm_assert("text_home_folder_labels",
               "Is a folder entry labeled 'Download' shown together with a small "
               "badge/chip reading '3 Videos' on the same row?",
               RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="content")


@and_test(expects=("text_folder_video_path",))
def test_folder_video_path():
    folder = and_enter_folder()
    if not folder:
        record("text_folder_video_path", False,
               "setup_failed: Download folder contents not reached",
               depth=1, jump_kind="transition",
               expect="video row shows path '/storage/emulated/0/Download'")
        return
    # The full path string only renders on the video rows INSIDE the folder.
    ok = has_text(folder, FOLDER_PATH)
    record("text_folder_video_path", ok,
           "" if ok else "behavior_wrong: video rows did not show the path "
           "'/storage/emulated/0/Download'",
           depth=1, jump_kind="transition",
           expect="each video row shows the path '/storage/emulated/0/Download'")


@and_test(expects=("text_folder_titles_no_extension",))
def test_folder_titles_no_extension():
    folder = and_enter_folder()
    if not folder:
        record("text_folder_titles_no_extension", False,
               "setup_failed: Download folder contents not reached",
               depth=1, jump_kind="transition",
               expect="picker rows read 'beta_movie' (no extension)")
        return
    # In the picker the titles carry NO extension; the .mp4 form is player-only.
    plain = has_text(folder, "beta_movie")
    no_ext = not has_text(folder, "beta_movie.mp4")
    ok = plain and no_ext
    record("text_folder_titles_no_extension", ok,
           "" if ok else "behavior_wrong: picker row title was not the bare "
           "'beta_movie' (without the .mp4 extension)",
           depth=1, jump_kind="transition",
           expect="picker row reads 'beta_movie' (no extension), unlike the player's 'beta_movie.mp4'")


# ══════════════════════════════════════════════════════════════════════════════
# (E) Settings subtitle strings. depth=2, transition.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_settings_controller_timeout",))
def test_settings_controller_timeout():
    sub = and_reach_settings_sub("Player", "Material You controls")
    if not sub:
        record("text_settings_controller_timeout", False,
               "setup_failed: Player settings subscreen not reached",
               depth=2, jump_kind="transition",
               expect="'Controller timeout' subtitle reads '4 seconds'")
        return
    label_ok = has_text(sub, "Controller timeout")
    subtitle = sub_of(sub, "Controller timeout")
    ok = label_ok and subtitle == "4 seconds"
    record("text_settings_controller_timeout", ok,
           "" if ok else f"behavior_wrong: 'Controller timeout' subtitle was "
           f"{subtitle!r}, expected '4 seconds'",
           depth=2, jump_kind="transition",
           expect="the 'Controller timeout' row's subtitle reads '4 seconds'")


@and_test(expects=("text_settings_default_speed",))
def test_settings_default_speed():
    sub = and_reach_settings_sub("Player", "Material You controls")
    if not sub:
        record("text_settings_default_speed", False,
               "setup_failed: Player settings subscreen not reached",
               depth=2, jump_kind="transition",
               expect="'Default playback speed' subtitle reads '1.0'")
        return
    label_ok = has_text(sub, "Default playback speed")
    subtitle = sub_of(sub, "Default playback speed")
    ok = label_ok and subtitle == "1.0"
    record("text_settings_default_speed", ok,
           "" if ok else f"behavior_wrong: 'Default playback speed' subtitle was "
           f"{subtitle!r}, expected '1.0'",
           depth=2, jump_kind="transition",
           expect="the 'Default playback speed' row's subtitle reads '1.0'")


@and_test(expects=("text_settings_dark_theme_subtitle",))
def test_settings_dark_theme_subtitle():
    sub = and_reach_settings_sub("Appearance", "Dark theme")
    if not sub:
        record("text_settings_dark_theme_subtitle", False,
               "setup_failed: Appearance settings subscreen not reached",
               depth=2, jump_kind="transition",
               expect="'Dark theme' subtitle reads 'System Default'")
        return
    label_ok = has_text(sub, "Dark theme")
    subtitle = sub_of(sub, "Dark theme")
    ok = label_ok and subtitle == "System Default"
    record("text_settings_dark_theme_subtitle", ok,
           "" if ok else f"behavior_wrong: 'Dark theme' subtitle was {subtitle!r}, "
           f"expected 'System Default'",
           depth=2, jump_kind="transition",
           expect="the 'Dark theme' row's subtitle reads 'System Default' (default)")


# ══════════════════════════════════════════════════════════════════════════════
# (F) About subscreen label strings (stable, recreation-required; NOT the version).
#     depth=2, transition.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_about_credit_and_rows",))
def test_about_credit_and_rows():
    sub = and_reach_settings_sub("About", "by anilbeesetti")
    if not sub:
        record("text_about_credit_and_rows", False,
               "setup_failed: About subscreen not reached",
               depth=2, jump_kind="transition",
               expect="'by anilbeesetti', 'Libraries', 'Github' all present")
        return
    # Deliberately NOT asserting the version number "0.16.3 (56)" — a build
    # constant the recreation cannot know.
    credit = has_text(sub, "by anilbeesetti")
    libs = has_text(sub, "Libraries")
    github = has_text(sub, "Github")
    ok = credit and libs and github
    missing = [s for s, present in
               (("by anilbeesetti", credit), ("Libraries", libs), ("Github", github))
               if not present]
    record("text_about_credit_and_rows", ok,
           "" if ok else f"behavior_wrong: About screen missing {missing}",
           depth=2, jump_kind="transition",
           expect="About shows the credit 'by anilbeesetti' and rows 'Libraries' and 'Github'")


@and_test(expects=("text_about_upi_handle",))
def test_about_upi_handle():
    sub = and_reach_settings_sub("About", "by anilbeesetti")
    if not sub:
        record("text_about_upi_handle", False,
               "setup_failed: About subscreen not reached",
               depth=2, jump_kind="transition",
               expect="UPI row subtitle 'anilbeesetti10@oksbi'")
        return
    label_ok = has_text(sub, "UPI")
    handle_ok = has_text(sub, "anilbeesetti10@oksbi")
    ok = label_ok and handle_ok
    record("text_about_upi_handle", ok,
           "" if ok else "behavior_wrong: About screen missing the 'UPI' row and/or "
           "its 'anilbeesetti10@oksbi' handle",
           depth=2, jump_kind="transition",
           expect="About shows a 'UPI' row with the handle 'anilbeesetti10@oksbi'")


# ══════════════════════════════════════════════════════════════════════════════
# (G) Network Stream dialog: label + placeholder, and typed-back text.
#     depth=2, transition. Do NOT hide_keyboard in this dialog (BACK closes it);
#     read the field from a fresh ui() and dismiss with Cancel.
# ══════════════════════════════════════════════════════════════════════════════

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_reach_network_dialog():
    """Home -> FAB -> 'Open network stream' -> Network Stream dialog. Counts two
    surfaces (depth 2 from Home). Returns fresh dialog nodes or []."""
    nodes = home_ready()
    fab = _find_fab(nodes)
    if not fab:
        return []
    if not tap_node(fab):
        return []
    settle("tap")
    menu = ui()
    and_enter("fab_menu")
    pill = find_node(menu, text="Open network stream")
    if not pill:
        return []
    if not tap_node(pill):
        return []
    settle("tap")
    dlg = ui()
    if find_node(dlg, text="Network Stream"):
        and_enter("network_dialog")
        return dlg
    return []


@and_test(expects=("text_network_dialog_label_placeholder",))
def test_network_dialog_label_placeholder():
    dlg = and_reach_network_dialog()
    if not dlg:
        record("text_network_dialog_label_placeholder", False,
               "setup_failed: Network Stream dialog not reached via the FAB",
               depth=2, jump_kind="transition",
               expect="label 'Enter a network URL:' + placeholder 'http://example.com/example.mp4'")
        return
    label_ok = has_text(dlg, "Enter a network URL:")
    placeholder_ok = has_text(dlg, "http://example.com/example.mp4")
    ok = label_ok and placeholder_ok
    # Dismiss with Cancel (NOT BACK, which closes the whole dialog and could pop
    # further); keep the surface clean for later tests.
    cancel = find_node(dlg, text="Cancel")
    if cancel:
        tap_node(cancel)
        settle("tap")
    record("text_network_dialog_label_placeholder", ok,
           "" if ok else "behavior_wrong: dialog missing the label 'Enter a network "
           "URL:' and/or placeholder 'http://example.com/example.mp4'",
           depth=2, jump_kind="transition",
           expect="dialog shows label 'Enter a network URL:' and placeholder "
                  "'http://example.com/example.mp4'")


@and_test(expects=("text_network_url_reads_back",))
def test_network_url_reads_back():
    dlg = and_reach_network_dialog()
    if not dlg:
        record("text_network_url_reads_back", False,
               "setup_failed: Network Stream dialog not reached via the FAB",
               depth=2, jump_kind="transition", expect="field reads back the typed URL")
        return
    field = find_by_class(dlg, "EditText")
    if not field:
        record("text_network_url_reads_back", False,
               "setup_failed: no EditText in the Network Stream dialog",
               depth=2, jump_kind="transition", expect="field reads back the typed URL")
        return
    typed = "http://test.mp4"
    absent = typed not in all_text(dlg)
    type_text(field[0], typed)
    settle("text")
    # Read directly from a fresh dump — do NOT hide the keyboard here (BACK would
    # dismiss the dialog).
    after = ui()
    et = find_by_class(after, "EditText")
    field_text = et[0].get("text", "") if et else ""
    present = typed in field_text or typed in all_text(after)
    ok = absent and present
    cancel = find_node(after, text="Cancel")
    if cancel:
        tap_node(cancel)
        settle("tap")
    record("text_network_url_reads_back", ok,
           "" if ok else f"behavior_wrong: URL field did not read back {typed!r} "
           f"(got {field_text!r})",
           depth=2, jump_kind="transition",
           expect=f"the URL EditText reads back the typed text {typed!r}")


TESTS = [
    test_search_beta_header,
    test_search_gamma_row,
    test_search_substring_movie,
    test_search_empty_state,
    test_player_title_beta,
    test_player_title_gamma,
    test_player_title_alpha,
    test_loop_desc_advances,
    test_home_folder_labels,
    test_folder_video_path,
    test_folder_titles_no_extension,
    test_settings_controller_timeout,
    test_settings_default_speed,
    test_settings_dark_theme_subtitle,
    test_about_credit_and_rows,
    test_about_upi_handle,
    test_network_dialog_label_placeholder,
    test_network_url_reads_back,
]

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