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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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
#!/usr/bin/env python3
"""TEXT lane — CONTENT/OUTPUT strings an interaction PRODUCES for the Aegis
Authenticator app (TOTP/HOTP 2FA). Sole owner of exact-string equality.

Every test drives the app to a working state via the portable resource-id path,
performs the interaction that PRODUCES the string, and reads it back out of a
FRESH ui(). The discriminating half is the CHANGE: the count string flips
singular->plural, a summary flips 'System default'->'Light theme', a title flips
'Add new entry'->'Edit entry'. Nothing is keyed on the package / paths /
coordinates — the same file scores a from-scratch recreation at a different
package name. Every asserted string was OBSERVED on the running original; no
version/build/copyright string is ever asserted (source-derived, unfair).

VLM budget = 4 records, all pointed at TEXT that does NOT reach the view tree:
the canvas-drawn avatar letter (two distinct issuers), the pink error-bar
styling, and the bold count digit.

Run:
  python3 test_android_text.py <PACKAGE> <RESULTS_DIR>
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from android_testgen_kit import *          # noqa: F403,E402

# Valid base32 secrets (produce a live TOTP row); distinctive markers so a
# read-back cannot accidentally match pre-existing data.
SEC_A = "JBSWY3DPEHPK3PXP"


# ══════════════════════════════════════════════════════════════════════════════
# Shared plumbing (own copies of the proven interaction/navigation helpers — the
# kit is imported, never re-implemented; these are app-specific orchestration).
# ══════════════════════════════════════════════════════════════════════════════

def _kb_off():
    """Lower the soft keyboard on the edit form WITHOUT navigating. The kit's
    hide_keyboard() falls back to BACK, which on EditEntryActivity raises the
    discard dialog; KEYCODE_ESCAPE lowers the IME with no navigation."""
    if keyboard_visible():
        press_key("KEYCODE_ESCAPE")
        settle("keyboard")


def and_enter_main(clear=False):
    """Get to MainActivity. clear=True wipes the vault first (virgin DB).

    Runs the 4-tap onboarding skip by resource-id only, choosing rb_none so the
    vault opens directly on every relaunch (no unlock screen). Returns the last
    fresh node list, or None if Main was never reached."""
    if clear:
        clear_data()
    restart_app()
    wait_for_foreground()
    n = ui()
    if node_by_id(n, "btnNext"):
        for rid in ("btnNext", "rb_none", "btnNext", "btnNext"):
            t = node_by_id(n, rid)
            if t is None or not tap_node(t):
                return None
            n = ui()
    if node_by_id(n, "fab") is None:
        return None
    return n


def _count_text(nodes=None):
    nodes = ui() if nodes is None else nodes
    c = node_by_id(nodes, "entries_shown_count")
    return (c or {}).get("text")


def and_enter_editor():
    """Main -> FAB menu -> Enter manually -> EditEntryActivity. Backs depth via
    the and_enter_* NAME + an and_enter() call once the surface changes."""
    n = ui()
    fab = node_by_id(n, "fab")
    if fab is None or not tap_node(fab):
        return False
    n = ui()
    enter = node_by_id(n, "fab_menu_item_enter")
    if enter is None or not tap_node(enter):
        return False
    settle("tap")
    if not get_current_activity().endswith("EditEntryActivity"):
        return False
    and_enter("editor")
    return True


def and_create_entry(name, issuer, secret=SEC_A):
    """FAB -> Enter manually -> fill name/issuer/secret -> SAVE. Returns True only
    when we land back on Main with the new issuer visible."""
    if not and_enter_editor():
        return False
    n = ui()
    nm = node_by_id(n, "text_name")
    if nm is None or not type_text(nm, name):
        return False
    _kb_off()
    n = ui()
    iss = node_by_id(n, "text_issuer")
    if iss is None or not type_text(iss, issuer):
        return False
    _kb_off()
    n = ui()
    sec = node_by_id(n, "text_secret")
    if sec is None or not type_text(sec, secret):
        return False
    _kb_off()
    n = ui()
    save = node_by_id(n, "action_save")
    if save is None or not tap_node(save):
        return False
    n = ui()
    if find_node_ci(n, "Error saving profile"):
        return False
    if find_node_ci(n, "Your changes have not been saved"):
        sv = find_node(n, text="Save")
        if sv:
            tap_node(sv)
            n = ui()
    if not get_current_activity().endswith("MainActivity"):
        return False
    return find_node_ci(ui(), issuer) is not None


def and_open_action_mode(issuer=None):
    """Long-press a row (the one with `issuer`, else the first) to enter the
    contextual action mode. Returns True once action_mode_close_button appears."""
    n = ui()
    row = None
    if issuer:
        for x in n:
            if (x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_issuer"
                    and x.get("text") == issuer):
                row = x
                break
    if row is None:
        row = node_by_id(n, "profile_issuer")
    if row is None or not long_press(row):
        return False
    settle("tap")
    if node_by_id(ui(), "action_mode_close_button") is None:
        return False
    and_enter("action_mode")
    return True


def and_reach_settings_root():
    """Main -> overflow -> Settings root. Confirms arrival by the 'Settings' title
    plus category rows. Counts one surface via and_enter()."""
    mo = find_node(ui(), content_desc="More options")
    if mo is None or not tap_node(mo):
        return False
    settle("tap")
    item = find_node_ci(ui(), "Settings")
    if item is None or not tap_node(item):
        return False
    settle("tap")
    n = ui()
    if find_node(n, text="Settings") is None or find_node_ci(n, "Appearance") is None:
        return False
    and_enter("settings")
    return True


def and_reach_section(label, child):
    """From the Settings ROOT, tap a category row and confirm the sub-screen:
    `child` (a section-only element) is present and the root is left. `label` is
    matched by the row `title` prefix so 'Import &amp; Export' resolves from
    'Import'. Counts one surface via and_enter()."""
    trigger = None
    for n in ui():
        if n.get("resource-id", "").rsplit("/", 1)[-1] == "title" and \
                n.get("text", "").lower().startswith(label.lower()):
            trigger = n
            break
    if trigger is None:
        trigger = find_node_ci(ui(), label)
    if trigger is None or not tap_node(trigger):
        return False
    settle("tap")
    if find_node_ci(ui(), child) is None:
        return False
    and_enter(label)
    return True


def and_reach_about():
    """Main -> overflow -> About. Confirms arrival by the 'Aegis Authenticator'
    heading. Counts one surface via and_enter()."""
    mo = find_node(ui(), content_desc="More options")
    if mo is None or not tap_node(mo):
        return False
    settle("tap")
    item = find_node_ci(ui(), "About")
    if item is None or not tap_node(item):
        return False
    settle("tap")
    if find_node_ci(ui(), "Aegis Authenticator") is None:
        return False
    and_enter("about")
    return True


def _summary_under(nodes, title_text):
    """The `summary` string of the preference row whose `title` == title_text.
    Rows are (title, summary) sibling pairs stacked vertically; pick the summary
    whose y sits just below the matching title and above the next title."""
    titles = sorted(
        [(x["_bounds"][1], x.get("text", "")) for x in nodes
         if x.get("resource-id", "").rsplit("/", 1)[-1] == "title"
         and "_bounds" in x],
        key=lambda p: p[0])
    summaries = sorted(
        [(x["_bounds"][1], x.get("text", "")) for x in nodes
         if x.get("resource-id", "").rsplit("/", 1)[-1] == "summary"
         and "_bounds" in x],
        key=lambda p: p[0])
    ty = None
    next_ty = None
    for i, (y, t) in enumerate(titles):
        if t == title_text:
            ty = y
            next_ty = titles[i + 1][0] if i + 1 < len(titles) else 10 ** 9
            break
    if ty is None:
        return None
    for y, s in summaries:
        if ty <= y < next_ty:
            return s
    return None


def _norm(s):
    return (s or "").strip().casefold()


# ══════════════════════════════════════════════════════════════════════════════
# 1. entries_shown_count reflects entry count: empty-state -> 1 (singular) ->
#    2 (plural). The singular/plural switch is a real content behavior.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_count_empty_state",))
def test_count_empty_state():
    """A virgin vault shows NO 'Showing N entries' bar; it shows the empty-state
    message instead. Assert the exact empty-state wording observed."""
    if and_enter_main(clear=True) is None:
        record("text_count_empty_state", False,
               "setup_failed: could not reach MainActivity",
               depth=0, jump_kind="value", expect="'No entries found' empty state")
        return
    n = ui()
    # No count bar on an empty vault; the empty-state heading is present instead.
    no_count = _count_text(n) is None
    heading = find_node_ci(n, "No entries found") is not None
    ok = no_count and heading
    record("text_count_empty_state", ok,
           "" if ok else f"behavior_wrong: empty vault count={_count_text(n)!r} "
                         f"heading_present={heading} (expected no count + 'No entries found')",
           depth=0, jump_kind="value", expect="'No entries found' + no count bar")


@and_test(expects=("text_count_singular_one",))
def test_count_singular_one():
    if and_enter_main(clear=True) is None:
        record("text_count_singular_one", False,
               "setup_failed: could not reach MainActivity",
               depth=0, jump_kind="value", expect="count 'Showing 1 entry'")
        return
    absent = _count_text() is None
    if not and_create_entry("nOne", "iOne"):
        record("text_count_singular_one", False,
               "feature_missing: could not create an entry",
               depth=0, jump_kind="value", expect="count 'Showing 1 entry'")
        return
    got = _count_text()
    ok = absent and _norm(got) == _norm("Showing 1 entry")
    record("text_count_singular_one", ok,
           "" if ok else f"behavior_wrong: count={got!r} (expected 'Showing 1 entry')",
           depth=0, jump_kind="value", expect="count 'Showing 1 entry' (singular)")


@and_test(expects=("text_count_plural_two",))
def test_count_plural_two():
    """Discriminator: singular 'entry' -> plural 'entries' as the count crosses 1."""
    if and_enter_main(clear=True) is None:
        record("text_count_plural_two", False,
               "setup_failed: could not reach MainActivity",
               depth=0, jump_kind="value", expect="count 'Showing 2 entries'")
        return
    if not and_create_entry("nA", "iA"):
        record("text_count_plural_two", False,
               "feature_missing: could not create the first entry",
               depth=0, jump_kind="value", expect="count 'Showing 2 entries'")
        return
    singular = _count_text()
    if not and_create_entry("nB", "iB"):
        record("text_count_plural_two", False,
               "behavior_wrong: could not create the second entry",
               depth=0, jump_kind="value", expect="count 'Showing 2 entries'")
        return
    plural = _count_text()
    ok = (_norm(singular) == _norm("Showing 1 entry")
          and _norm(plural) == _norm("Showing 2 entries"))
    record("text_count_plural_two", ok,
           "" if ok else f"behavior_wrong: count {singular!r}->{plural!r} "
                         f"(expected 'Showing 1 entry' then 'Showing 2 entries')",
           depth=0, jump_kind="value", expect="count 'Showing 2 entries' (plural)")


# ══════════════════════════════════════════════════════════════════════════════
# 2. A new entry's issuer/name strings appear verbatim on its row.
#    Observed format: profile_issuer=='TextCheckIssuer', profile_account_name=='(TextCheckName)'
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_new_entry_issuer_name",))
def test_new_entry_issuer_name():
    if and_enter_main(clear=True) is None:
        record("text_new_entry_issuer_name", False,
               "setup_failed: could not reach MainActivity",
               depth=0, jump_kind="value",
               expect="row 'TextCheckIssuer' + '(TextCheckName)'")
        return
    absent = find_node_ci(ui(), "TextCheckIssuer") is None
    if not and_create_entry("TextCheckName", "TextCheckIssuer"):
        record("text_new_entry_issuer_name", False,
               "feature_missing: could not create the entry",
               depth=0, jump_kind="value",
               expect="row 'TextCheckIssuer' + '(TextCheckName)'")
        return
    n = ui()
    issuer = (node_by_id(n, "profile_issuer") or {}).get("text")
    acct = (node_by_id(n, "profile_account_name") or {}).get("text")
    ok = (absent and issuer == "TextCheckIssuer" and acct == "(TextCheckName)")
    record("text_new_entry_issuer_name", ok,
           "" if ok else f"behavior_wrong: issuer={issuer!r} account={acct!r} "
                         f"(expected 'TextCheckIssuer' and '(TextCheckName)')",
           depth=0, jump_kind="value",
           expect="profile_issuer 'TextCheckIssuer', profile_account_name '(TextCheckName)'")


# ══════════════════════════════════════════════════════════════════════════════
# 3. Search PRODUCES count strings: a matching query -> 'Showing 1 entry',
#    a non-matching query 'ZZZQQ' -> 'Showing 0 entries'.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_search_count_strings",))
def test_search_count_strings():
    if and_enter_main(clear=True) is None:
        record("text_search_count_strings", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value",
               expect="'Showing 1 entry' (match) / 'Showing 0 entries' (no match)")
        return
    if not and_create_entry("SrchName", "SrchIssuer"):
        record("text_search_count_strings", False,
               "feature_missing: could not create an entry to search",
               depth=1, jump_kind="value",
               expect="'Showing 1 entry' (match) / 'Showing 0 entries' (no match)")
        return
    sb = node_by_id(ui(), "search_button")
    if sb is None or not tap_node(sb):
        record("text_search_count_strings", False,
               "feature_missing: no Search control on the toolbar",
               depth=1, jump_kind="value",
               expect="'Showing 1 entry' (match) / 'Showing 0 entries' (no match)")
        return
    and_enter("search")
    sst = node_by_id(ui(), "search_src_text")
    if sst is None or not type_text(sst, "Srch"):
        record("text_search_count_strings", False,
               "setup_failed: search field not typable",
               depth=1, jump_kind="value",
               expect="'Showing 1 entry' (match) / 'Showing 0 entries' (no match)")
        return
    settle("text")
    match_cnt = _count_text()
    # Clear the field, then a non-matching query.
    sst = node_by_id(ui(), "search_src_text")
    tap_node(sst)
    press_key("KEYCODE_MOVE_END")
    for _ in range(20):
        press_key("KEYCODE_DEL")
    settle("text")
    sst = node_by_id(ui(), "search_src_text")
    type_text(sst, "ZZZQQ")
    settle("text")
    nomatch_cnt = _count_text()
    ok = (_norm(match_cnt) == _norm("Showing 1 entry")
          and _norm(nomatch_cnt) == _norm("Showing 0 entries"))
    record("text_search_count_strings", ok,
           "" if ok else f"behavior_wrong: match={match_cnt!r} nomatch={nomatch_cnt!r} "
                         f"(expected 'Showing 1 entry' / 'Showing 0 entries')",
           depth=1, jump_kind="value",
           expect="match 'Showing 1 entry', no-match 'Showing 0 entries'")


# ══════════════════════════════════════════════════════════════════════════════
# 4. Editor title strings: create form title 'Add new entry'; long-press ->
#    Edit -> title 'Edit entry'. Assert both exact titles (depth>=1, backed).
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_title_add_new_entry",))
def test_title_add_new_entry():
    if and_enter_main(clear=True) is None:
        record("text_title_add_new_entry", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value", expect="editor title 'Add new entry'")
        return
    absent = find_node_ci(ui(), "Add new entry") is None
    if not and_enter_editor():
        record("text_title_add_new_entry", False,
               "feature_missing: could not open the create form",
               depth=1, jump_kind="value", expect="editor title 'Add new entry'")
        return
    present = find_node_ci(ui(), "Add new entry") is not None
    ok = absent and present
    record("text_title_add_new_entry", ok,
           "" if ok else "behavior_wrong: create form title is not 'Add new entry'",
           depth=1, jump_kind="value", expect="editor title 'Add new entry'")


@and_test(expects=("text_title_edit_entry",))
def test_title_edit_entry():
    if and_enter_main(clear=True) is None or not and_create_entry("nEd", "iEd"):
        record("text_title_edit_entry", False,
               "setup_failed: could not create an entry to edit",
               depth=2, jump_kind="value", expect="editor title 'Edit entry'")
        return
    absent = find_node_ci(ui(), "Edit entry") is None
    if not and_open_action_mode("iEd"):
        record("text_title_edit_entry", False,
               "feature_missing: long-press did not open action mode",
               depth=2, jump_kind="value", expect="editor title 'Edit entry'")
        return
    ed = node_by_id(ui(), "action_edit")
    if ed is None or not tap_node(ed):
        record("text_title_edit_entry", False,
               "feature_missing: no Edit control in action mode",
               depth=2, jump_kind="value", expect="editor title 'Edit entry'")
        return
    and_enter("editor")
    present = find_node_ci(ui(), "Edit entry") is not None
    ok = absent and present
    record("text_title_edit_entry", ok,
           "" if ok else "behavior_wrong: edit form title is not 'Edit entry'",
           depth=2, jump_kind="value", expect="editor title 'Edit entry'")


# ══════════════════════════════════════════════════════════════════════════════
# 5. Theme selected-summary string (Appearance -> Theme dialog -> Light) ->
#    the summary under 'Theme' becomes 'Selected: Light theme'.
#    NOTE theme selection recreates the activity — re-dump.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_theme_summary",))
def test_theme_summary():
    if and_enter_main(clear=True) is None:
        record("text_theme_summary", False,
               "setup_failed: could not reach MainActivity",
               depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'")
        return
    if not (and_reach_settings_root()
            and and_reach_section("Appearance", "Dynamic colors")):
        record("text_theme_summary", False,
               "setup_failed: could not reach Appearance settings",
               depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'")
        return
    before = _summary_under(ui(), "Theme")
    th = find_node_ci(ui(), "Theme")
    if th is None or not tap_node(th):
        record("text_theme_summary", False,
               "feature_missing: no Theme preference row",
               depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'")
        return
    settle("tap")
    if find_node_ci(ui(), "Select your desired theme") is None:
        record("text_theme_summary", False,
               "feature_missing: Theme dialog did not open",
               depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'")
        return
    lt = find_node_ci(ui(), "Light theme")
    if lt is None or not tap_node(lt):
        record("text_theme_summary", False,
               "behavior_wrong: no 'Light theme' option in the dialog",
               depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'")
        return
    settle("launch")  # activity recreated after selecting a theme
    after = _summary_under(ui(), "Theme")
    ok = (_norm(before) == _norm("Selected: System default")
          and _norm(after) == _norm("Selected: Light theme"))
    # Reset to System default so later launches repaint normally.
    th = find_node_ci(ui(), "Theme")
    if th and tap_node(th):
        settle("tap")
        sd = find_node_ci(ui(), "System default")
        if sd:
            tap_node(sd)
            settle("launch")
    record("text_theme_summary", ok,
           "" if ok else f"behavior_wrong: Theme summary {before!r}->{after!r} "
                         f"(expected 'Selected: System default'->'Selected: Light theme')",
           depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'")


# ══════════════════════════════════════════════════════════════════════════════
# 6. View mode summary string (Appearance): default 'Selected: Normal'.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_view_mode_summary",))
def test_view_mode_summary():
    if and_enter_main(clear=True) is None:
        record("text_view_mode_summary", False,
               "setup_failed: could not reach MainActivity",
               depth=2, jump_kind="value", expect="View mode summary 'Selected: Normal'")
        return
    if not (and_reach_settings_root()
            and and_reach_section("Appearance", "View mode")):
        record("text_view_mode_summary", False,
               "setup_failed: could not reach Appearance settings",
               depth=2, jump_kind="value", expect="View mode summary 'Selected: Normal'")
        return
    got = _summary_under(ui(), "View mode")
    ok = _norm(got) == _norm("Selected: Normal")
    record("text_view_mode_summary", ok,
           "" if ok else f"behavior_wrong: View mode summary={got!r} "
                         f"(expected 'Selected: Normal')",
           depth=2, jump_kind="value", expect="View mode summary 'Selected: Normal'")


# ══════════════════════════════════════════════════════════════════════════════
# 7. Copy-tokens summary (Behavior): default 'Selected: Never'.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_copy_tokens_summary",))
def test_copy_tokens_summary():
    if and_enter_main(clear=True) is None:
        record("text_copy_tokens_summary", False,
               "setup_failed: could not reach MainActivity",
               depth=2, jump_kind="value",
               expect="'Copy tokens to the clipboard' summary 'Selected: Never'")
        return
    if not (and_reach_settings_root()
            and and_reach_section("Behavior", "Haptic feedback")):
        record("text_copy_tokens_summary", False,
               "setup_failed: could not reach Behavior settings",
               depth=2, jump_kind="value",
               expect="'Copy tokens to the clipboard' summary 'Selected: Never'")
        return
    got = _summary_under(ui(), "Copy tokens to the clipboard")
    ok = _norm(got) == _norm("Selected: Never")
    record("text_copy_tokens_summary", ok,
           "" if ok else f"behavior_wrong: Copy-tokens summary={got!r} "
                         f"(expected 'Selected: Never')",
           depth=2, jump_kind="value",
           expect="Copy-tokens summary 'Selected: Never'")


# ══════════════════════════════════════════════════════════════════════════════
# 8. Advanced-accordion default strings (EditEntry): the form PRODUCES
#    dropdown_type='TOTP', dropdown_algo='SHA1', period='30', digits='6', usage='0'.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_advanced_defaults",))
def test_advanced_defaults():
    if and_enter_main(clear=True) is None:
        record("text_advanced_defaults", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value",
               expect="Advanced defaults TOTP/SHA1/30/6/0")
        return
    if not and_enter_editor():
        record("text_advanced_defaults", False,
               "feature_missing: could not open the create form",
               depth=1, jump_kind="value",
               expect="Advanced defaults TOTP/SHA1/30/6/0")
        return
    # Expand the Advanced accordion to reveal the type/algo/period/digits/usage fields.
    adv = None
    for x in ui():
        if _norm(x.get("text", "")) == _norm("Advanced"):
            adv = x
            break
    if adv is None or not tap_node(adv):
        record("text_advanced_defaults", False,
               "feature_missing: no Advanced accordion in the create form",
               depth=1, jump_kind="value",
               expect="Advanced defaults TOTP/SHA1/30/6/0")
        return
    settle("tap")
    n = ui()
    got = {rid: (node_by_id(n, rid) or {}).get("text") for rid in
           ("dropdown_type", "dropdown_algo", "text_period_counter",
            "text_digits", "text_usage_count")}
    want = {"dropdown_type": "TOTP", "dropdown_algo": "SHA1",
            "text_period_counter": "30", "text_digits": "6",
            "text_usage_count": "0"}
    ok = all(_norm(got[k]) == _norm(v) for k, v in want.items())
    record("text_advanced_defaults", ok,
           "" if ok else f"behavior_wrong: advanced defaults {got!r} (expected {want!r})",
           depth=1, jump_kind="value",
           expect="TOTP / SHA1 / 30 / 6 / 0 in the Advanced section")


# ══════════════════════════════════════════════════════════════════════════════
# 9. Group field default + dialog strings (EditEntry): text_group='No group';
#    tapping it opens a dialog titled 'Groups' with a 'New group…' item.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_group_default_and_dialog",))
def test_group_default_and_dialog():
    if and_enter_main(clear=True) is None:
        record("text_group_default_and_dialog", False,
               "setup_failed: could not reach MainActivity",
               depth=2, jump_kind="value",
               expect="group 'No group' + dialog 'Groups'/'New group…'")
        return
    if not and_enter_editor():
        record("text_group_default_and_dialog", False,
               "feature_missing: could not open the create form",
               depth=2, jump_kind="value",
               expect="group 'No group' + dialog 'Groups'/'New group…'")
        return
    grp = node_by_id(ui(), "text_group")
    default = (grp or {}).get("text")
    if grp is None or not tap_node(grp):
        record("text_group_default_and_dialog", False,
               "feature_missing: no group field in the create form",
               depth=2, jump_kind="value",
               expect="group 'No group' + dialog 'Groups'/'New group…'")
        return
    settle("tap")
    and_enter("group_dialog")
    n = ui()
    title = find_node_ci(n, "Groups") is not None
    new_group = find_node_ci(n, "New group…") is not None
    ok = (_norm(default) == _norm("No group") and title and new_group)
    record("text_group_default_and_dialog", ok,
           "" if ok else f"behavior_wrong: group default={default!r} "
                         f"dialog_title={title} new_group_item={new_group} "
                         f"(expected 'No group' + 'Groups'/'New group…')",
           depth=2, jump_kind="value",
           expect="text_group 'No group'; dialog title 'Groups'; item 'New group…'")


# ══════════════════════════════════════════════════════════════════════════════
# 10. Field LABELS the form produces (EditEntry): the floating labels render as
#     the row text 'Name'/'Issuer'/'Secret' (app-unique static strings a
#     recreation must get right).
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_field_labels",))
def test_field_labels():
    if and_enter_main(clear=True) is None:
        record("text_field_labels", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value", expect="labels 'Name'/'Issuer'/'Secret'")
        return
    absent = find_node_ci(ui(), "Secret") is None
    if not and_enter_editor():
        record("text_field_labels", False,
               "feature_missing: could not open the create form",
               depth=1, jump_kind="value", expect="labels 'Name'/'Issuer'/'Secret'")
        return
    n = ui()
    name = (node_by_id(n, "text_name") or {}).get("text")
    issuer = (node_by_id(n, "text_issuer") or {}).get("text")
    secret = (node_by_id(n, "text_secret") or {}).get("text")
    ok = (absent and _norm(name) == _norm("Name")
          and _norm(issuer) == _norm("Issuer")
          and _norm(secret) == _norm("Secret"))
    record("text_field_labels", ok,
           "" if ok else f"behavior_wrong: labels name={name!r} issuer={issuer!r} "
                         f"secret={secret!r} (expected 'Name'/'Issuer'/'Secret')",
           depth=1, jump_kind="value",
           expect="field labels 'Name', 'Issuer', 'Secret'")


# ══════════════════════════════════════════════════════════════════════════════
# 11. About-screen strings: 'Aegis Authenticator', 'GitHub', 'License',
#     'Beem Development', 'Write an email', 'Visit our website'. (Version string
#     is source-derived — NOT asserted.)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_about_strings",))
def test_about_strings():
    if and_enter_main(clear=True) is None:
        record("text_about_strings", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value",
               expect="About shows GitHub/License/Beem Development/Write an email")
        return
    absent = find_node_ci(ui(), "Beem Development") is None
    if not and_reach_about():
        record("text_about_strings", False,
               "feature_missing: could not reach the About screen",
               depth=1, jump_kind="value",
               expect="About shows GitHub/License/Beem Development/Write an email")
        return
    n = ui()
    want = ["Aegis Authenticator", "GitHub", "License", "Beem Development",
            "Write an email", "Visit our website"]
    missing = [w for w in want if find_node_ci(n, w) is None]
    ok = absent and not missing
    record("text_about_strings", ok,
           "" if ok else f"behavior_wrong: About missing {missing!r}",
           depth=1, jump_kind="value",
           expect="'Aegis Authenticator','GitHub','License','Beem Development',"
                  "'Write an email','Visit our website'")


# ══════════════════════════════════════════════════════════════════════════════
# 12. Sort-popup option strings: the popup shows 'Custom', 'Account (A to Z)',
#     'Issuer (A to Z)', 'Usage count', 'Last used', etc.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_sort_options",))
def test_sort_options():
    if and_enter_main(clear=True) is None or not and_create_entry("nSort", "iSort"):
        record("text_sort_options", False,
               "setup_failed: could not create an entry to sort",
               depth=1, jump_kind="value",
               expect="sort options Custom/Account (A to Z)/Issuer (A to Z)/Usage count")
        return
    absent = find_node_ci(ui(), "Account (A to Z)") is None
    srt = find_node(ui(), content_desc="Sort")
    if srt is None or not tap_node(srt):
        record("text_sort_options", False,
               "feature_missing: no Sort control on the toolbar",
               depth=1, jump_kind="value",
               expect="sort options Custom/Account (A to Z)/Issuer (A to Z)/Usage count")
        return
    and_enter("sort_popup")
    n = ui()
    want = ["Custom", "Account (A to Z)", "Account (Z to A)", "Issuer (A to Z)",
            "Issuer (Z to A)", "Usage count", "Last used"]
    missing = [w for w in want if find_node_ci(n, w) is None]
    ok = absent and not missing
    back()  # dismiss the popup without changing the sort
    record("text_sort_options", ok,
           "" if ok else f"behavior_wrong: sort popup missing {missing!r}",
           depth=1, jump_kind="value",
           expect="Custom / Account (A to Z) / Issuer (A to Z) / Usage count / Last used")


# ══════════════════════════════════════════════════════════════════════════════
# 13. Action-mode content-desc strings an interaction reveals: 'Done', 'Copy',
#     'Edit', 'Transfer' — plus the always-present FAB desc 'Add new entry'.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_action_mode_descs",))
def test_action_mode_descs():
    if and_enter_main(clear=True) is None or not and_create_entry("nDesc", "iDesc"):
        record("text_action_mode_descs", False,
               "setup_failed: could not create an entry to long-press",
               depth=1, jump_kind="value",
               expect="content-desc 'Done'/'Copy'/'Edit'/'Transfer'")
        return
    absent = find_node(ui(), content_desc="Done") is None
    if not and_open_action_mode("iDesc"):
        record("text_action_mode_descs", False,
               "feature_missing: long-press did not open action mode",
               depth=1, jump_kind="value",
               expect="content-desc 'Done'/'Copy'/'Edit'/'Transfer'")
        return
    n = ui()
    want = ["Done", "Copy", "Edit", "Transfer", "Favorite"]
    missing = [w for w in want if find_node(n, content_desc=w) is None]
    ok = absent and not missing
    # leave action mode cleanly
    done = node_by_id(ui(), "action_mode_close_button")
    if done:
        tap_node(done)
    record("text_action_mode_descs", ok,
           "" if ok else f"behavior_wrong: action-mode content-desc missing {missing!r}",
           depth=1, jump_kind="value",
           expect="content-desc 'Done','Copy','Edit','Transfer','Favorite'")


@and_test(expects=("text_fab_content_desc",))
def test_fab_content_desc():
    """The add-entry FAB carries content-desc 'Add new entry' (an icon-only
    control a recreation must label correctly)."""
    if and_enter_main(clear=True) is None:
        record("text_fab_content_desc", False,
               "setup_failed: could not reach MainActivity",
               depth=0, jump_kind="value", expect="FAB content-desc 'Add new entry'")
        return
    fab = node_by_id(ui(), "fab")
    desc = (fab or {}).get("content-desc")
    ok = _norm(desc) == _norm("Add new entry")
    record("text_fab_content_desc", ok,
           "" if ok else f"behavior_wrong: FAB content-desc={desc!r} "
                         f"(expected 'Add new entry')",
           depth=0, jump_kind="value", expect="FAB content-desc 'Add new entry'")


# ══════════════════════════════════════════════════════════════════════════════
# 14. Persistent info-bar string: the app renders 'Changes are not backed up'.
#     It is ABSENT on the empty-onboarding-only surface? — it renders on Main
#     regardless, so assert its exact wording (content the app produces).
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_error_bar_string",))
def test_error_bar_string():
    if and_enter_main(clear=True) is None:
        record("text_error_bar_string", False,
               "setup_failed: could not reach MainActivity",
               depth=0, jump_kind="value", expect="info bar 'Changes are not backed up'")
        return
    n = ui()
    bar = node_by_id(n, "text_error_bar")
    got = (bar or {}).get("text") if bar else \
        (find_node_ci(n, "Changes are not backed up") or {}).get("text")
    ok = _norm(got) == _norm("Changes are not backed up")
    record("text_error_bar_string", ok,
           "" if ok else f"behavior_wrong: info bar text={got!r} "
                         f"(expected 'Changes are not backed up')",
           depth=0, jump_kind="value", expect="info bar 'Changes are not backed up'")


# ══════════════════════════════════════════════════════════════════════════════
# ── VLM cluster (budget = 4): TEXT that does NOT reach the view tree ──────────
# The avatar tile letter is canvas-drawn (no TextView carries it), so it is a
# legitimate opaque-text target; the error-bar colour and the bold count digit
# are rendered properties of strings that the dump cannot expose.
# ══════════════════════════════════════════════════════════════════════════════

# VLM #1 — canvas-drawn avatar letter 'T' for issuer 'Tango' (opaque content)
@and_test(expects=("text_avatar_letter_tango_vlm",))
def test_avatar_letter_tango_vlm():
    if and_enter_main(clear=True) is None or not and_create_entry("Tango", "Tango"):
        record("text_avatar_letter_tango_vlm", False,
               "setup_failed: could not create the 'Tango' entry",
               depth=0, jump_kind="value", tag="content")
        return
    vlm_assert("text_avatar_letter_tango",
               "This authenticator list has a single entry whose issuer is "
               "'Tango'. Inside the round coloured avatar circle on the left of "
               "that row, is the capital letter 'T' shown?",
               RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="content")


# VLM #2 — canvas-drawn avatar letter 'Q' for issuer 'Quartz' (opaque content)
@and_test(expects=("text_avatar_letter_quartz_vlm",))
def test_avatar_letter_quartz_vlm():
    if and_enter_main(clear=True) is None or not and_create_entry("Quartz", "Quartz"):
        record("text_avatar_letter_quartz_vlm", False,
               "setup_failed: could not create the 'Quartz' entry",
               depth=0, jump_kind="value", tag="content")
        return
    vlm_assert("text_avatar_letter_quartz",
               "This authenticator list has a single entry whose issuer is "
               "'Quartz'. Inside the round coloured avatar circle on the left of "
               "that row, is the capital letter 'Q' shown (NOT 'T' or any other "
               "letter)?",
               RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="content")


# VLM #3 — the 'Changes are not backed up' text sits in a pink/red banner (color)
@and_test(expects=("text_error_bar_color_vlm",))
def test_error_bar_color_vlm():
    if and_enter_main(clear=True) is None or not and_create_entry("nBar", "iBar"):
        record("text_error_bar_color_vlm", False,
               "setup_failed: could not create an entry",
               depth=0, jump_kind="value", tag="color")
        return
    # Confirm the words are actually present before asking about their styling.
    if find_node_ci(ui(), "Changes are not backed up") is None:
        record("text_error_bar_color_vlm", False,
               "behavior_wrong: the 'Changes are not backed up' bar is absent",
               depth=0, jump_kind="value", tag="color")
        return
    vlm_assert("text_error_bar_color",
               "Near the top of this authenticator screen, is the text 'Changes "
               "are not backed up' displayed inside a pink / light-red rounded "
               "banner (a coloured warning bar), rather than as plain text on the "
               "white background?",
               RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="color")


# VLM #4 — the count digit in 'Showing 1 entry' is emphasised/bold (size/weight)
@and_test(expects=("text_count_bold_digit_vlm",))
def test_count_bold_digit_vlm():
    if and_enter_main(clear=True) is None or not and_create_entry("nBold", "iBold"):
        record("text_count_bold_digit_vlm", False,
               "setup_failed: could not create an entry",
               depth=0, jump_kind="value", tag="size")
        return
    if _norm(_count_text()) != _norm("Showing 1 entry"):
        record("text_count_bold_digit_vlm", False,
               "behavior_wrong: count is not 'Showing 1 entry' before the styling check",
               depth=0, jump_kind="value", tag="size")
        return
    vlm_assert("text_count_bold_digit",
               "At the bottom of the entry list is the line 'Showing 1 entry'. "
               "Is the number '1' rendered noticeably bolder / heavier in weight "
               "than the surrounding words 'Showing' and 'entry'?",
               RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="size")


TESTS = [
    test_count_empty_state,
    test_count_singular_one,
    test_count_plural_two,
    test_new_entry_issuer_name,
    test_search_count_strings,
    test_title_add_new_entry,
    test_title_edit_entry,
    test_theme_summary,
    test_view_mode_summary,
    test_copy_tokens_summary,
    test_advanced_defaults,
    test_group_default_and_dialog,
    test_field_labels,
    test_about_strings,
    test_sort_options,
    test_action_mode_descs,
    test_fab_content_desc,
    test_error_bar_string,
    test_avatar_letter_tango_vlm,
    test_avatar_letter_quartz_vlm,
    test_error_bar_color_vlm,
    test_count_bold_digit_vlm,
]


if __name__ == "__main__":
    if not device_online():
        print("device offline — aborting")
        sys.exit(2)
    run_suite(TESTS, "text")