File size: 39,059 Bytes
c1c6a0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""TEXT module for openScale (a body-weight / health tracker).

CONTENT / OUTPUT text — this lane is the sole owner of exact-string equality.
Every EXPECTED string below was OBSERVED on the RUNNING ORIGINAL (recon + live
dumps), never read from the source tree, and never a version/build/copyright value
(a recreation cannot know those).

WHAT THIS LANE ASSERTS (all rule assertions unless suffixed _vlm):
  * empty-state strings that an interaction/state PRODUCES:
      - "No User Active"           (fresh launch, no user)
      - "No Measurements Yet"      (user exists, no measurement) — ABSENT before the
                                    user is created, PRESENT after (the change)
  * TopBar screen titles reached through the drawer: Overview / Charts / Table /
    Statistics / Insights / Settings — each ABSENT on the Overview source surface,
    PRESENT after navigating (the discriminating change).
  * Settings sub-screen titles: General / Chart / Measurement Types / About.
  * the 5 exact Insights placeholder card strings (bodies).
  * Statistics per-metric Min/Max/Avg labels+values, produced by saving a
    measurement: "Min: 80 kg", "Max: 80 kg", "Avg: 80 kg", "Min: 24.7",
    "Min: 1840 kcal", "Min: 2208 kcal".  (The NUMBER is computation's; here we own
    the exact rendered STRING incl. the "Min:/Max:/Avg:" label and unit.)
  * Overview measurement-card value strings: "80 kg", "24.7", and the "Show more"
    expand affordance — each ABSENT before a measurement exists, PRESENT after.

OPAQUE TEXT CORES -> the 3 _vlm (canvas-baked axis text, absent from the view tree):
  * Overview chart: the "6 Aug" date label baked onto the plot canvas.
  * Charts screen TOP chart: the horizontal date axis ("Aug" day labels).
  * Charts screen LOWER chart: the "80" weight y-axis label.

DEVICE QUIRKS honored (from recon):
  * BACK discards an in-progress form -> fill Name+Height then tap the top-right
    Save button DIRECTLY; never hide_keyboard() before saving.
  * NumberInputDialog EditText APPENDS to "0.0" -> tap "Clear" first; and
    type_text drops the 2nd digit -> enter multi-digit values ONE char at a time
    and VERIFY the field before proceeding.
  * Each test owns its entry via restart_app()/clear_data(); state persists within
    a run but no test depends on another.
  * ui() is re-dumped after every change (kit invalidates coordinates on change).
  * depth>=1 is backed by file-local and_enter_*/and_reach_* helpers.

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


# ══════════════════════════════════════════════════════════════════════════════
# text helpers
# ══════════════════════════════════════════════════════════════════════════════

def all_text(nodes):
    """Every non-empty `text` on screen, joined — for substring assertions."""
    return " | ".join(n.get("text", "") for n in nodes if n.get("text"))


def all_text_desc(nodes):
    """Every `text` AND `content-desc` on screen — for labels that may render as a
    content-desc (icon-only affordances like the card's 'Show more' chevron)."""
    parts = []
    for n in nodes:
        if n.get("text"):
            parts.append(n["text"])
        if n.get("content-desc"):
            parts.append(n["content-desc"])
    return " | ".join(parts)


def _norm(s):
    return s.replace(",", "").replace(" ", " ").strip().lower()


def has_text(nodes, needle):
    """Case-insensitive normalised substring over text-only content."""
    return _norm(needle) in _norm(all_text(nodes))


def has_text_desc(nodes, needle):
    """Case-insensitive normalised substring over text + content-desc."""
    return _norm(needle) in _norm(all_text_desc(nodes))


def topbar_title(nodes):
    """The TopAppBar title text: the left-most non-empty text node in the top
    strip (y < ~18% of the screen), excluding the clock. openScale renders the
    screen name there (Overview / Charts / Statistics / ... / General / Chart)."""
    s = get_screen_info()
    band = int(s["height"] * 0.18)
    cands = []
    for n in nodes:
        b = n.get("_bounds")
        t = n.get("text", "").strip()
        if not b or not t:
            continue
        x1, y1, x2, y2 = b
        if y1 > band:
            continue
        # skip the status-bar clock (very top) and anything with a digit/colon
        if y1 < int(s["height"] * 0.03):
            continue
        if ":" in t and any(c.isdigit() for c in t):
            continue
        cands.append((x1, t))
    if not cands:
        return ""
    cands.sort(key=lambda c: c[0])
    return cands[0][1]


# ══════════════════════════════════════════════════════════════════════════════
# file-local depth helpers — the and_enter_* / and_reach_* NAMES back every
# declared depth>=1 (the depth auditor descends into file-local helpers that call
# and_enter()/and_reach()).
# ══════════════════════════════════════════════════════════════════════════════

def and_enter_user_form():
    """From the Overview 'No User Active' surface, open the Add-User form."""
    n = find_node_ci(ui(), "Add User")
    if n is None or not tap_node(n):
        return False
    settle("launch")
    and_enter("user_form")
    return True


def and_enter_new_measurement():
    """From the Overview, open the New Measurement screen."""
    n = (find_node_ci(ui(), "Add Measurement")
         or find_node(ui(), content_desc="Add new measurement"))
    if n is None or not tap_node(n):
        return False
    settle("launch")
    and_enter("new_measurement")
    return True


def and_enter_weight_dialog():
    """From the New/Edit Measurement screen, open the Edit Weight
    NumberInputDialog (cd='Edit Weight')."""
    n = find_node(ui(), content_desc="Edit Weight")
    if n is None or not tap_node(n):
        return False
    settle("tap")
    and_enter("weight_dialog")
    return True


def and_reach_drawer_dest(dest_label, source="Overview"):
    """From the Overview, open the drawer and tap a destination, PROVING the jump:
    the destination title newly APPEARED and the source title DISAPPEARED. The
    'before' snapshot is taken while the Overview is showing (its title is the
    source), so opening the drawer first would not pollute it. Counts one surface.
    Returns True only on a proven reach.
    """
    before = and_showing()                       # Overview surface
    menu = find_node(ui(), content_desc="Open menu")
    if menu is None or not tap_node(menu):
        return False
    settle("launch")
    dest = (find_node(ui(), content_desc=dest_label)
            or find_node_ci(ui(), dest_label))
    if dest is None or not tap_node(dest):
        return False
    settle("launch")
    after = and_showing()
    ok = and_reach(before, after, dest_label, source)
    if ok:
        and_enter(dest_label)
    return ok


def and_reach_settings_sub(sub_label):
    """drawer -> Settings -> a sub-screen (depth 2). Proves the final jump: the
    sub-screen title APPEARED and the 'Settings' list title DISAPPEARED."""
    if not and_reach_drawer_dest("Settings"):
        return False
    row = find_node(ui(), content_desc=sub_label) or find_node_ci(ui(), sub_label)
    if row is None:
        row = scroll_into_view(sub_label)
    if row is None or not tap_node(row):
        return False
    settle("launch")
    after = and_showing()
    # the sub title appears; the Settings *screen title* was the source. We proved
    # Settings above, so here just confirm the sub-screen title is now present.
    ok = any(sub_label.strip().lower() in k.lower() for k in after)
    if ok:
        and_enter(sub_label)
    return ok


# ── fixture: a clean user + one saved weight=80 measurement, left on Overview ───

def set_dialog_value(val):
    """The PROVEN reliable numeric-entry recipe (verbatim from recon): the
    NumberInputDialog EditText APPENDS to '0.0' and type_text drops the 2nd digit,
    so Clear -> tap -> type ONE char at a time, then RETURN the field text so the
    caller can verify it == str(val)."""
    c = find_node_ci(ui(), "Clear")
    if c:
        tap_node(c)
        settle("keyboard")
    ets = find_by_class(ui(), "EditText")
    if not ets:
        return ""
    et = ets[0]
    tap_node(et)
    settle("keyboard")
    settle("keyboard")
    for ch in str(val):
        adb_shell("input", "text", ch)   # ONE char at a time (kit injects serial)
        settle("text")
    settle("text")
    ets = find_by_class(ui(), "EditText")
    return ets[0].get("text", "") if ets else ""


def create_user(height="180", name="TestUser"):
    """clear_data() -> launch -> fill Name+Height -> tap the top-right Save button
    DIRECTLY (no hide_keyboard(); its BACK fallback would discard the form)."""
    clear_data()
    launch_app()
    wait_for_foreground()
    settle("launch")
    if not and_enter_user_form():
        return False
    ets = sorted(find_by_class(ui(), "EditText"),
                 key=lambda e: e.get("_bounds", (0, 0, 0, 0))[1])
    if len(ets) < 2:
        return False
    type_text(ets[0], name)
    settle("text")
    ets = sorted(find_by_class(ui(), "EditText"),
                 key=lambda e: e.get("_bounds", (0, 0, 0, 0))[1])
    type_text(ets[1], height)
    settle("text")
    btns = [n for n in ui()
            if n.get("class", "").endswith("Button")
            and n.get("clickable") == "true"
            and n.get("_bounds", (0, 0, 0, 0))[0] > 800]
    if not btns:
        return False
    tap_node(btns[0])
    settle("launch")
    return find_node_ci(ui(), "No User Active") is None


def add_weight_measurement(weight="80"):
    """From the Overview (user must exist): open New Measurement, set Weight via
    the proven recipe, OK, Save measurement. Returns the field string the dialog
    held (caller verifies == str(weight))."""
    if not and_enter_new_measurement():
        return None
    if not and_enter_weight_dialog():
        return None
    got = set_dialog_value(weight)
    ok_btn = find_node_ci(ui(), "OK")
    if ok_btn:
        tap_node(ok_btn)
        settle("tap")
    sm = find_node(ui(), content_desc="Save measurement")
    if sm:
        tap_node(sm)
        settle("launch")
    return got


def user_with_weight(weight="80", height="180"):
    """End-to-end fixture, left on the Overview. Returns (ok, dialog_field)."""
    if not create_user(height=height):
        return False, ""
    got = add_weight_measurement(weight)
    return (got == str(weight)), (got or "")


# ══════════════════════════════════════════════════════════════════════════════
# EMPTY-STATE STRINGS
# ══════════════════════════════════════════════════════════════════════════════

# 1) "No User Active" — the fresh-launch empty state (depth 0, in-page).
@and_test(expects=("text_empty_no_user_active",))
def test_empty_no_user_active():
    clear_data()
    launch_app()
    wait_for_foreground()
    ok = has_text(ui(), "No User Active")
    record("text_empty_no_user_active", ok,
           "" if ok else "feature_missing: fresh launch does not show 'No User Active'",
           depth=0, jump_kind="value", expect="'No User Active' on first launch")


# 2) "No Measurements Yet" — ABSENT before the user exists, PRESENT after
#    (the discriminating change; depth 1 via and_enter_user_form -> Save).
@and_test(expects=("text_empty_no_measurements_yet",))
def test_empty_no_measurements_yet():
    clear_data()
    launch_app()
    wait_for_foreground()
    settle("launch")
    before = has_text(ui(), "No Measurements Yet")   # must be absent (shows 'No User Active')
    if not create_user():
        record("text_empty_no_measurements_yet", False,
               "setup_failed: could not create the prerequisite user",
               depth=1, jump_kind="value", expect="'No Measurements Yet' after user created")
        return
    after = has_text(ui(), "No Measurements Yet")
    ok = (not before) and after
    record("text_empty_no_measurements_yet", ok,
           "" if ok else (f"behavior_wrong: 'No Measurements Yet' before={before} "
                          f"after={after} (expected absent then present)"),
           depth=1, jump_kind="value", expect="'No Measurements Yet' after user created")


# ══════════════════════════════════════════════════════════════════════════════
# TOPBAR SCREEN TITLES (each ABSENT on the Overview source, PRESENT after nav)
# ══════════════════════════════════════════════════════════════════════════════

# 4) Overview title (depth 0, in-page — the launch surface's own title).
@and_test(expects=("text_title_overview",))
def test_title_overview():
    if not create_user():
        record("text_title_overview", False,
               "setup_failed: could not create the prerequisite user",
               depth=0, jump_kind="value", expect="TopBar title 'Overview'")
        return
    title = topbar_title(ui())
    ok = _norm(title) == _norm("Overview") or has_text(ui(), "Overview")
    record("text_title_overview", ok,
           "" if ok else f"behavior_wrong: Overview TopBar title not 'Overview'; saw {title!r}",
           depth=0, jump_kind="value", expect="TopBar title 'Overview'")


def _title_after_nav(dest_label):
    """create user, reach dest via the drawer, and return whether the dest title
    is the new TopBar title. Returns (reached, title_ok)."""
    if not create_user():
        return False, False
    if not and_reach_drawer_dest(dest_label):
        return False, False
    nodes = ui()
    title = topbar_title(nodes)
    ok = _norm(title) == _norm(dest_label) or has_text(nodes, dest_label)
    return True, ok


# 5) Charts title.
@and_test(expects=("text_title_charts",))
def test_title_charts():
    reached, ok = _title_after_nav("Charts")
    if not reached:
        record("text_title_charts", False,
               "setup_failed: could not reach the Charts screen",
               depth=1, jump_kind="value", expect="TopBar title 'Charts'")
        return
    record("text_title_charts", ok,
           "" if ok else "behavior_wrong: Charts TopBar title not 'Charts'",
           depth=1, jump_kind="value", expect="TopBar title 'Charts'")


# 6) Table title.
@and_test(expects=("text_title_table",))
def test_title_table():
    reached, ok = _title_after_nav("Table")
    if not reached:
        record("text_title_table", False,
               "setup_failed: could not reach the Table screen",
               depth=1, jump_kind="value", expect="TopBar title 'Table'")
        return
    record("text_title_table", ok,
           "" if ok else "behavior_wrong: Table TopBar title not 'Table'",
           depth=1, jump_kind="value", expect="TopBar title 'Table'")


# 7) Statistics title.
@and_test(expects=("text_title_statistics",))
def test_title_statistics():
    reached, ok = _title_after_nav("Statistics")
    if not reached:
        record("text_title_statistics", False,
               "setup_failed: could not reach the Statistics screen",
               depth=1, jump_kind="value", expect="TopBar title 'Statistics'")
        return
    record("text_title_statistics", ok,
           "" if ok else "behavior_wrong: Statistics TopBar title not 'Statistics'",
           depth=1, jump_kind="value", expect="TopBar title 'Statistics'")


# 8) Insights title.
@and_test(expects=("text_title_insights",))
def test_title_insights():
    reached, ok = _title_after_nav("Insights")
    if not reached:
        record("text_title_insights", False,
               "setup_failed: could not reach the Insights screen",
               depth=1, jump_kind="value", expect="TopBar title 'Insights'")
        return
    record("text_title_insights", ok,
           "" if ok else "behavior_wrong: Insights TopBar title not 'Insights'",
           depth=1, jump_kind="value", expect="TopBar title 'Insights'")


# 9) Settings title.
@and_test(expects=("text_title_settings",))
def test_title_settings():
    reached, ok = _title_after_nav("Settings")
    if not reached:
        record("text_title_settings", False,
               "setup_failed: could not reach the Settings screen",
               depth=1, jump_kind="value", expect="TopBar title 'Settings'")
        return
    record("text_title_settings", ok,
           "" if ok else "behavior_wrong: Settings TopBar title not 'Settings'",
           depth=1, jump_kind="value", expect="TopBar title 'Settings'")


# ══════════════════════════════════════════════════════════════════════════════
# SETTINGS SUB-SCREEN TITLES (depth 2)
# ══════════════════════════════════════════════════════════════════════════════

# 10) Settings -> General -> title "General".
@and_test(expects=("text_settings_general_title",))
def test_settings_general_title():
    if not create_user():
        record("text_settings_general_title", False,
               "setup_failed: could not create the prerequisite user",
               depth=2, jump_kind="value", expect="sub-screen title 'General'")
        return
    if not and_reach_settings_sub("General"):
        record("text_settings_general_title", False,
               "setup_failed: could not reach Settings -> General",
               depth=2, jump_kind="value", expect="sub-screen title 'General'")
        return
    nodes = ui()
    title = topbar_title(nodes)
    ok = _norm(title) == _norm("General") or has_text(nodes, "General")
    record("text_settings_general_title", ok,
           "" if ok else f"behavior_wrong: General sub-screen title not 'General'; saw {title!r}",
           depth=2, jump_kind="value", expect="sub-screen title 'General'")


# 11) Settings -> Chart -> title "Chart".
@and_test(expects=("text_settings_chart_title",))
def test_settings_chart_title():
    if not create_user():
        record("text_settings_chart_title", False,
               "setup_failed: could not create the prerequisite user",
               depth=2, jump_kind="value", expect="sub-screen title 'Chart'")
        return
    if not and_reach_settings_sub("Chart"):
        record("text_settings_chart_title", False,
               "setup_failed: could not reach Settings -> Chart",
               depth=2, jump_kind="value", expect="sub-screen title 'Chart'")
        return
    nodes = ui()
    title = topbar_title(nodes)
    ok = _norm(title) == _norm("Chart") or has_text(nodes, "Chart")
    record("text_settings_chart_title", ok,
           "" if ok else f"behavior_wrong: Chart sub-screen title not 'Chart'; saw {title!r}",
           depth=2, jump_kind="value", expect="sub-screen title 'Chart'")


# 12) Settings -> Measurement Types -> title "Measurement Types".
@and_test(expects=("text_settings_measurement_types_title",))
def test_settings_measurement_types_title():
    if not create_user():
        record("text_settings_measurement_types_title", False,
               "setup_failed: could not create the prerequisite user",
               depth=2, jump_kind="value", expect="sub-screen title 'Measurement Types'")
        return
    if not and_reach_settings_sub("Measurement Types"):
        record("text_settings_measurement_types_title", False,
               "setup_failed: could not reach Settings -> Measurement Types",
               depth=2, jump_kind="value", expect="sub-screen title 'Measurement Types'")
        return
    ok = has_text(ui(), "Measurement Types")
    record("text_settings_measurement_types_title", ok,
           "" if ok else "behavior_wrong: sub-screen title not 'Measurement Types'",
           depth=2, jump_kind="value", expect="sub-screen title 'Measurement Types'")


# 13) Settings -> About -> title "About".
@and_test(expects=("text_settings_about_title",))
def test_settings_about_title():
    if not create_user():
        record("text_settings_about_title", False,
               "setup_failed: could not create the prerequisite user",
               depth=2, jump_kind="value", expect="sub-screen title 'About'")
        return
    if not and_reach_settings_sub("About"):
        record("text_settings_about_title", False,
               "setup_failed: could not reach Settings -> About",
               depth=2, jump_kind="value", expect="sub-screen title 'About'")
        return
    nodes = ui()
    title = topbar_title(nodes)
    ok = _norm(title) == _norm("About") or has_text(nodes, "About")
    record("text_settings_about_title", ok,
           "" if ok else f"behavior_wrong: About sub-screen title not 'About'; saw {title!r}",
           depth=2, jump_kind="value", expect="sub-screen title 'About'")


# ══════════════════════════════════════════════════════════════════════════════
# INSIGHTS — the 5 exact placeholder card BODY strings (depth 1)
# ══════════════════════════════════════════════════════════════════════════════

_INSIGHTS = [
    ("text_insight_analysis",
     "At least 5 measurements are needed to analyse how your body changed over time."),
    ("text_insight_body_composition",
     "At least 4 measurements with all four metrics (weight, body fat, muscle, "
     "water) are needed within the last 90 days to compute this insight."),
    ("text_insight_weekly_habits",
     "At least 5 measurements per weekday are needed to detect weekly habits."),
    ("text_insight_year_in_review",
     "At least 2 years of data are needed to detect seasonal patterns."),
    ("text_insight_unusual",
     "At least 20 measurements are needed to detect unusual values."),
]


def _reach_insights_texts():
    """create user, reach Insights, return the joined on-screen text (or None)."""
    if not create_user():
        return None
    if not and_reach_drawer_dest("Insights"):
        return None
    return all_text(ui())


@and_test(expects=("text_insight_analysis",))
def test_insight_analysis():
    blob = _reach_insights_texts()
    name, needle = _INSIGHTS[0]
    if blob is None:
        record(name, False, "setup_failed: could not reach the Insights screen",
               depth=1, jump_kind="value", expect=needle)
        return
    ok = _norm(needle) in _norm(blob)
    record(name, ok,
           "" if ok else f"behavior_wrong: Insights missing analysis card text",
           depth=1, jump_kind="value", expect=needle)


@and_test(expects=("text_insight_body_composition",))
def test_insight_body_composition():
    blob = _reach_insights_texts()
    name, needle = _INSIGHTS[1]
    if blob is None:
        record(name, False, "setup_failed: could not reach the Insights screen",
               depth=1, jump_kind="value", expect=needle)
        return
    ok = _norm(needle) in _norm(blob)
    record(name, ok,
           "" if ok else "behavior_wrong: Insights missing body-composition card text",
           depth=1, jump_kind="value", expect=needle)


@and_test(expects=("text_insight_weekly_habits",))
def test_insight_weekly_habits():
    blob = _reach_insights_texts()
    name, needle = _INSIGHTS[2]
    if blob is None:
        record(name, False, "setup_failed: could not reach the Insights screen",
               depth=1, jump_kind="value", expect=needle)
        return
    ok = _norm(needle) in _norm(blob)
    record(name, ok,
           "" if ok else "behavior_wrong: Insights missing weekly-habits card text",
           depth=1, jump_kind="value", expect=needle)


@and_test(expects=("text_insight_year_in_review",))
def test_insight_year_in_review():
    blob = _reach_insights_texts()
    name, needle = _INSIGHTS[3]
    if blob is None:
        record(name, False, "setup_failed: could not reach the Insights screen",
               depth=1, jump_kind="value", expect=needle)
        return
    ok = _norm(needle) in _norm(blob)
    record(name, ok,
           "" if ok else "behavior_wrong: Insights missing year-in-review card text",
           depth=1, jump_kind="value", expect=needle)


@and_test(expects=("text_insight_unusual",))
def test_insight_unusual():
    blob = _reach_insights_texts()
    name, needle = _INSIGHTS[4]
    if blob is None:
        record(name, False, "setup_failed: could not reach the Insights screen",
               depth=1, jump_kind="value", expect=needle)
        return
    ok = _norm(needle) in _norm(blob)
    record(name, ok,
           "" if ok else "behavior_wrong: Insights missing unusual-measurements card text",
           depth=1, jump_kind="value", expect=needle)


# ══════════════════════════════════════════════════════════════════════════════
# STATISTICS — exact Min/Max/Avg label+value STRINGS (depth 2, produced by saving)
# ══════════════════════════════════════════════════════════════════════════════

def _reach_statistics_with_weight(weight="80"):
    """create user + save weight, then reach Statistics. Returns joined text or
    None on setup failure."""
    ok_setup, _got = user_with_weight(weight)
    if not ok_setup:
        return None
    if not and_reach_drawer_dest("Statistics"):
        return None
    return all_text(ui())


@and_test(expects=("text_stats_weight_min",))
def test_stats_weight_min():
    blob = _reach_statistics_with_weight("80")
    if blob is None:
        record("text_stats_weight_min", False,
               "setup_failed: could not save weight 80 and reach Statistics",
               depth=2, jump_kind="value", expect="'Min: 80 kg'")
        return
    ok = _norm("Min: 80 kg") in _norm(blob)
    record("text_stats_weight_min", ok,
           "" if ok else "behavior_wrong: Statistics Weight card missing 'Min: 80 kg'",
           depth=2, jump_kind="value", expect="'Min: 80 kg'")


@and_test(expects=("text_stats_weight_max",))
def test_stats_weight_max():
    blob = _reach_statistics_with_weight("80")
    if blob is None:
        record("text_stats_weight_max", False,
               "setup_failed: could not save weight 80 and reach Statistics",
               depth=2, jump_kind="value", expect="'Max: 80 kg'")
        return
    ok = _norm("Max: 80 kg") in _norm(blob)
    record("text_stats_weight_max", ok,
           "" if ok else "behavior_wrong: Statistics Weight card missing 'Max: 80 kg'",
           depth=2, jump_kind="value", expect="'Max: 80 kg'")


@and_test(expects=("text_stats_weight_avg",))
def test_stats_weight_avg():
    blob = _reach_statistics_with_weight("80")
    if blob is None:
        record("text_stats_weight_avg", False,
               "setup_failed: could not save weight 80 and reach Statistics",
               depth=2, jump_kind="value", expect="'Avg: 80 kg'")
        return
    ok = _norm("Avg: 80 kg") in _norm(blob)
    record("text_stats_weight_avg", ok,
           "" if ok else "behavior_wrong: Statistics Weight card missing 'Avg: 80 kg'",
           depth=2, jump_kind="value", expect="'Avg: 80 kg'")


@and_test(expects=("text_stats_bmi_min",))
def test_stats_bmi_min():
    blob = _reach_statistics_with_weight("80")
    if blob is None:
        record("text_stats_bmi_min", False,
               "setup_failed: could not save weight 80 and reach Statistics",
               depth=2, jump_kind="value", expect="'Min: 24.7'")
        return
    ok = _norm("Min: 24.7") in _norm(blob)
    record("text_stats_bmi_min", ok,
           "" if ok else "behavior_wrong: Statistics BMI card missing 'Min: 24.7'",
           depth=2, jump_kind="value", expect="'Min: 24.7'")


@and_test(expects=("text_stats_bmr_min",))
def test_stats_bmr_min():
    blob = _reach_statistics_with_weight("80")
    if blob is None:
        record("text_stats_bmr_min", False,
               "setup_failed: could not save weight 80 and reach Statistics",
               depth=2, jump_kind="value", expect="'Min: 1840 kcal'")
        return
    ok = _norm("Min: 1840 kcal") in _norm(blob)
    record("text_stats_bmr_min", ok,
           "" if ok else "behavior_wrong: Statistics BMR card missing 'Min: 1840 kcal'",
           depth=2, jump_kind="value", expect="'Min: 1840 kcal'")


@and_test(expects=("text_stats_tdee_min",))
def test_stats_tdee_min():
    blob = _reach_statistics_with_weight("80")
    if blob is None:
        record("text_stats_tdee_min", False,
               "setup_failed: could not save weight 80 and reach Statistics",
               depth=2, jump_kind="value", expect="'Min: 2208 kcal'")
        return
    ok = _norm("Min: 2208 kcal") in _norm(blob)
    record("text_stats_tdee_min", ok,
           "" if ok else "behavior_wrong: Statistics TDEE card missing 'Min: 2208 kcal'",
           depth=2, jump_kind="value", expect="'Min: 2208 kcal'")


# ══════════════════════════════════════════════════════════════════════════════
# OVERVIEW MEASUREMENT-CARD value STRINGS (ABSENT before, PRESENT after — depth 1)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_card_weight_80kg",))
def test_card_weight_80kg():
    if not create_user():
        record("text_card_weight_80kg", False,
               "setup_failed: could not create the prerequisite user",
               depth=1, jump_kind="value", expect="card weight '80 kg' after save")
        return
    before = has_text(ui(), "80 kg")     # 'No Measurements Yet' surface -> absent
    got = add_weight_measurement("80")
    if got != "80":
        record("text_card_weight_80kg", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=1, jump_kind="value", expect="card weight '80 kg' after save")
        return
    after = has_text(ui(), "80 kg")
    ok = (not before) and after
    record("text_card_weight_80kg", ok,
           "" if ok else (f"behavior_wrong: card '80 kg' before={before} after={after} "
                          f"(expected absent then present)"),
           depth=1, jump_kind="value", expect="card weight '80 kg' after save")


@and_test(expects=("text_card_bmi_247",))
def test_card_bmi_247():
    if not create_user():
        record("text_card_bmi_247", False,
               "setup_failed: could not create the prerequisite user",
               depth=1, jump_kind="value", expect="card BMI '24.7' after save")
        return
    before = has_text(ui(), "24.7")
    got = add_weight_measurement("80")
    if got != "80":
        record("text_card_bmi_247", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=1, jump_kind="value", expect="card BMI '24.7' after save")
        return
    after = has_text(ui(), "24.7")
    ok = (not before) and after
    record("text_card_bmi_247", ok,
           "" if ok else (f"behavior_wrong: card '24.7' before={before} after={after} "
                          f"(expected absent then present)"),
           depth=1, jump_kind="value", expect="card BMI '24.7' after save")


# "Show more" expand affordance on the card — ABSENT before a measurement, PRESENT
# after. Matched over text+content-desc (it may render as a chevron content-desc).
@and_test(expects=("text_card_show_more",))
def test_card_show_more():
    if not create_user():
        record("text_card_show_more", False,
               "setup_failed: could not create the prerequisite user",
               depth=1, jump_kind="value", expect="card 'Show more' affordance after save")
        return
    before = has_text_desc(ui(), "Show more")
    got = add_weight_measurement("80")
    if got != "80":
        record("text_card_show_more", False,
               f"setup_failed: could not enter weight 80 (dialog held {got!r})",
               depth=1, jump_kind="value", expect="card 'Show more' affordance after save")
        return
    after = has_text_desc(ui(), "Show more")
    ok = (not before) and after
    record("text_card_show_more", ok,
           "" if ok else (f"behavior_wrong: 'Show more' before={before} after={after} "
                          f"(expected absent then present)"),
           depth=1, jump_kind="value", expect="card 'Show more' affordance after save")


# ══════════════════════════════════════════════════════════════════════════════
# OPAQUE TEXT CORES — canvas-baked axis text (the 3 _vlm; absent from view tree)
# ══════════════════════════════════════════════════════════════════════════════

# 14) Overview chart: the "6 Aug" date label baked onto the plot canvas. The card
#     & titles are rule-asserted above; this asks ONLY about the canvas text, which
#     no dump exposes.
@and_test(expects=("text_overview_chart_date_axis_vlm",))
def test_overview_chart_date_axis_vlm():
    ok_setup, _got = user_with_weight("80")
    if not ok_setup:
        record("text_overview_chart_date_axis_vlm", False,
               "setup_failed: could not save a measurement to render the Overview chart",
               depth=1, jump_kind="value", tag="content")
        return
    vlm_assert("text_overview_chart_date_axis",
               "In the upper chart/graph region of this screen (above the "
               "measurement card), is a date label that includes the abbreviated "
               "month 'Aug' printed along the horizontal axis?",
               RESULTS_DIR, depth=1, jump_kind="value", tag="content")


# 15) Charts screen TOP chart: horizontal date axis with 'Aug' day labels
#     (e.g. '2 Aug' ... '6 Aug'). Canvas text.
@and_test(expects=("text_charts_top_date_axis_vlm",))
def test_charts_top_date_axis_vlm():
    ok_setup, _got = user_with_weight("80")
    if not ok_setup:
        record("text_charts_top_date_axis_vlm", False,
               "setup_failed: could not save a measurement before opening Charts",
               depth=1, jump_kind="value", tag="content")
        return
    if not and_reach_drawer_dest("Charts"):
        record("text_charts_top_date_axis_vlm", False,
               "setup_failed: could not reach the Charts screen",
               depth=1, jump_kind="value", tag="content")
        return
    vlm_assert("text_charts_top_date_axis",
               "In the TOP chart of this Charts screen, are date labels containing "
               "the abbreviated month 'Aug' (for example '6 Aug') printed along the "
               "horizontal axis at the bottom of that chart?",
               RESULTS_DIR, depth=1, jump_kind="value", tag="content")


# 16) Charts screen LOWER chart: the '80' weight y-axis label (right side).
#     Canvas text.
@and_test(expects=("text_charts_weight_axis_80_vlm",))
def test_charts_weight_axis_80_vlm():
    ok_setup, _got = user_with_weight("80")
    if not ok_setup:
        record("text_charts_weight_axis_80_vlm", False,
               "setup_failed: could not save a measurement before opening Charts",
               depth=1, jump_kind="value", tag="content")
        return
    if not and_reach_drawer_dest("Charts"):
        record("text_charts_weight_axis_80_vlm", False,
               "setup_failed: could not reach the Charts screen",
               depth=1, jump_kind="value", tag="content")
        return
    vlm_assert("text_charts_weight_axis_80",
               "In the LOWER line chart on this Charts screen, is the number '80' "
               "printed as a value label on the vertical (y) axis at the side of "
               "the chart?",
               RESULTS_DIR, depth=1, jump_kind="value", tag="content")


TESTS = [
    # empty states
    test_empty_no_user_active,
    test_empty_no_measurements_yet,
    # top-bar titles
    test_title_overview,
    test_title_charts,
    test_title_table,
    test_title_statistics,
    test_title_insights,
    test_title_settings,
    # settings sub-screen titles
    test_settings_general_title,
    test_settings_chart_title,
    test_settings_measurement_types_title,
    test_settings_about_title,
    # insights (5 exact strings)
    test_insight_analysis,
    test_insight_body_composition,
    test_insight_weekly_habits,
    test_insight_year_in_review,
    test_insight_unusual,
    # statistics min/max/avg strings
    test_stats_weight_min,
    test_stats_weight_max,
    test_stats_weight_avg,
    test_stats_bmi_min,
    test_stats_bmr_min,
    test_stats_tdee_min,
    # overview card value strings
    test_card_weight_80kg,
    test_card_bmi_247,
    test_card_show_more,
    # opaque canvas axis text (VLM)
    test_overview_chart_date_axis_vlm,
    test_charts_top_date_axis_vlm,
    test_charts_weight_axis_80_vlm,
]

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