File size: 29,084 Bytes
41dfd8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""STRUCTURE module — FastTimes (intermittent-fasting tracker).

Owns two things only:
  (1) the GATE: the app launches into its Dashboard with the top-level surfaces
      present (title, "Set your goal" card, the 2-col goal grid, the green FAB).
  (2) tree-SHAPE deltas: an interaction changes the view tree's SHAPE — a class of
      widget appears/vanishes, a dialog adds a window layer, a list populates. Each
      delta is recorded as a before->after and then REVERSED to assert it restores.

Content strings -> text lane; checked/selected -> states; reachability -> nav;
values -> computation. Here we assert SHAPE and existence of surfaces, plus spatial
layout via the VLM (the circular ring, the calendar grid, the expressive stat-card
shapes — none of which reach the view tree).

Run:  python3 test_android_structure.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

require_kit(1)


# ── Portable launcher (LeakCanary registers a 2nd LAUNCHER activity; monkey opens
# it ~half the time). Resolve THIS package's real MainActivity at runtime. ──────
def _main_component():
    out = adb_shell("cmd", "package", "query-activities", "--brief",
                    "-a", "android.intent.action.MAIN",
                    "-c", "android.intent.category.LAUNCHER")
    cands = [l.strip() for l in out.splitlines() if (PACKAGE + "/") in l]
    good = [c for c in cands if "leakcanary" not in c.lower()]
    return (good or cands or [""])[0]


def open_main():
    """Force-stop then launch the REAL MainActivity (never LeakCanary)."""
    force_stop()
    comp = _main_component()
    if comp:
        adb_shell("am", "start", "-n", comp)
    else:
        launch_app()
    settle("launch")
    wait_for_foreground()
    if "leakcanary" in get_current_activity().lower() and comp:
        adb_shell("am", "start", "-n", comp)
        settle("launch")


def open_main_clear():
    """Virgin state: wipe data (no active fast, empty history), then open Main."""
    clear_data()
    open_main()


# ── Domain helpers ───────────────────────────────────────────────────────────
def _dismiss_notif_rationale(nodes):
    """The first-run "Notification Preferences" rationale can appear on the first
    goal tap after clear_data(). Dismiss it (choice is irrelevant to structure)."""
    if not find_node(nodes, text="Notification Preferences"):
        return False
    for label in ("No Notifications", "Enable Notifications", "Cancel", "Skip"):
        n = find_node(nodes, text=label)
        if n:
            tap_node(n)
            settle("tap")
            return True
    return False


def start_test_timer():
    """From a clean dashboard, tap the "Test Timer" goal cell and end up on the
    ACTIVE-FAST card. Handles the optional first-run notification rationale.
    Returns the post-start node tree, or None if the cell was missing."""
    dash = ui()
    cell = find_node(dash, text="Test Timer")
    if not cell:
        return None
    tap_node(cell)
    settle("tap")
    after = ui()
    if _dismiss_notif_rationale(after):
        after = ui()
    if not find_node(after, content_desc="End Fast"):
        # dialog path may have consumed the tap; retry the cell once
        cell = find_node(after, text="Test Timer")
        if cell:
            tap_node(cell)
            settle("tap")
            after = ui()
    return after


def end_active_fast_no_save(nodes):
    """Tap End Fast, then BACK out of the "Fast Complete!" summary WITHOUT saving,
    returning to a clean dashboard. Keeps history empty (no CRUD side effect)."""
    ef = find_node(nodes, content_desc="End Fast")
    if not ef:
        return ui()
    tap_node(ef)
    settle("tap")
    back()                     # dismiss the summary modal without saving
    settle("tap")
    return ui()


# ── Named navigation helpers (back a depth>=1 claim honestly) ──────────────────
def and_reach_screen(nodes, trigger_text="", trigger_desc="", target="", source=""):
    """Tap a labelled trigger on `nodes`, then PROVE the surface jump: `target`
    appeared and `source` vanished. Counts one surface (jump_kind='reach')."""
    n = None
    if trigger_text:
        n = find_node(nodes, text=trigger_text) or find_node_ci(nodes, trigger_text)
    if n is None and trigger_desc:
        n = find_node(nodes, content_desc=trigger_desc)
    if n is None:
        return False
    return and_reach_surface(n, target, source or None)


def and_enter_dialog(nodes, trigger_desc="", trigger_text=""):
    """Open an in-place dialog/overlay (a new window layer over the same screen),
    confirming the surface changed. Counts one surface (depth+1)."""
    ok, _note = and_enter_surface(nodes, target_text=trigger_text,
                                  content_desc=trigger_desc)
    return ok


RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR  # noqa: F405


# ═══════════════════════════════════════════════════════════════════════════════
# (1) GATE — top-level Dashboard surfaces present (jump_kind="none", depth=0)
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_gate_launch",))
def test_gate_launch():
    open_main_clear()
    nodes = ui()
    fg = wait_for_foreground()
    # main container: single-Activity Compose renders a ComposeView host inside a
    # top-level layout container. Assert BOTH a layout host and a Compose host.
    container = find_by_class(nodes, "ComposeView") and find_by_class(nodes, "FrameLayout")
    ok = bool(fg and container)
    record("structure_gate_launch", ok,
           "" if ok else "setup_failed: app did not reach the foreground with a "
                          "Compose container",
           depth=0, jump_kind="none")


@and_test(expects=("structure_gate_dashboard_surfaces", "structure_dashboard_fab_vlm"))
def test_gate_dashboard_surfaces():
    open_main_clear()
    nodes = ui()
    # top-level Dashboard surfaces, by visible text + content-desc (no ids):
    title = find_node_ci(nodes, "Fast Times")            # toolbar title
    goal_card = find_node_ci(nodes, "Set your goal")     # goal card header
    perf = find_node_ci(nodes, "Performance")            # performance section
    hist = find_node_ci(nodes, "History")                # history section
    fab = find_node(nodes, content_desc="Add Fast")      # green add FAB
    settings = find_node(nodes, content_desc="Settings")  # toolbar gear
    ok = all([title, goal_card, perf, hist, fab, settings])
    record("structure_gate_dashboard_surfaces", bool(ok),
           "" if ok else "feature_missing: a top-level Dashboard surface is absent "
                          "(title/Set your goal/Performance/History/FAB/Settings)",
           depth=0, jump_kind="none")
    # VLM: the FAB is a green button in the bottom-right corner (a rounded square
    # with a dark icon). Assert the exact rendered COLOR + POSITION.
    vlm_assert("structure_dashboard_fab",
               "Is there a green colored button in the bottom-right corner of the "
               "screen containing a small dark icon? Answer YES or NO.",
               RESULTS_DIR, tag="color", depth=0, jump_kind="none")


@and_test(expects=("structure_gate_goal_grid", "structure_goal_grid_layout_vlm"))
def test_gate_goal_grid():
    open_main_clear()
    nodes = ui()
    # The 8-cell goal grid: assert the SHAPE (all 8 named cells exist). This is
    # existence of a structural grid, not any single string's content.
    cells = ["12h", "14h", "16h", "18h", "24h", "∞", "1h", "0h"]
    present = [c for c in cells if find_node(nodes, text=c)]
    ok = len(present) == 8
    record("structure_gate_goal_grid", ok,
           "" if ok else f"feature_missing: goal grid incomplete, only "
                         f"{len(present)}/8 cells present ({present})",
           depth=0, jump_kind="none")
    # VLM: the eight cells are laid out as a 2-column grid.
    vlm_assert("structure_goal_grid_layout",
               "Under the 'Set your goal' heading, are the goal cells arranged in a "
               "grid with exactly two columns per row? Answer YES or NO.",
               RESULTS_DIR, tag="position", depth=0, jump_kind="none")


# ═══════════════════════════════════════════════════════════════════════════════
# (2) SHAPE DELTAS — in-place (depth=0) transitions with a reverse
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_fab_speeddial_expand", "structure_fab_speeddial_vlm"))
def test_fab_speeddial_expand():
    open_main_clear()
    dash = ui()
    fab = find_node(dash, content_desc="Add Fast")
    if not fab:
        record("structure_fab_speeddial_expand", False,
               "feature_missing: Add Fast FAB not present on Dashboard",
               depth=0, jump_kind="transition",
               expect="FAB expand adds 'Start Open Fast'+'View History' children")
    else:
        before = and_showing(dash)
        n_clk_before = len(find_nodes(dash, clickable=True))
        tap_node(fab)
        exp_nodes = ui()
        after = and_showing(exp_nodes)
        n_clk_after = len(find_nodes(exp_nodes, clickable=True))
        # speed-dial GROWS the tree: 2 new labelled actions + 2 more clickables.
        added = after - before
        grew = (any("Start Open Fast" in k for k in added)
                and any("View History" in k for k in added)
                and n_clk_after >= n_clk_before + 2)
        # reverse: tapping the FAB again collapses it back to the original shape.
        fab2 = find_node(exp_nodes, content_desc="Add Fast")
        if fab2:
            tap_node(fab2)
        coll = ui()
        restored = (not find_node(coll, text="Start Open Fast")
                    and len(find_nodes(coll, clickable=True)) == n_clk_before)
        ok = grew and restored
        record("structure_fab_speeddial_expand", ok,
               "" if ok else ("behavior_wrong: speed-dial did not add the two "
                              "action buttons" if not grew
                              else "behavior_wrong: speed-dial did not collapse back"),
               depth=0, jump_kind="transition",
               expect="clickables +2 with 'Start Open Fast'+'View History' on expand,"
                      " restored on collapse")
        # re-expand so the VLM screenshot shows the speed-dial open
        fab3 = find_node(coll, content_desc="Add Fast")
        if fab3:
            tap_node(fab3)
    vlm_assert("structure_fab_speeddial",
               "Are there two green pill-shaped action buttons stacked vertically "
               "directly above the round green button in the bottom-right corner? "
               "Answer YES or NO.",
               RESULTS_DIR, tag="position", depth=0, jump_kind="transition")


@and_test(expects=("structure_active_fast_shape", "structure_active_fast_ring_vlm"))
def test_active_fast_shape():
    open_main_clear()
    dash = ui()
    before = and_showing(dash)
    fab_before = bool(find_node(dash, content_desc="Add Fast"))
    active = start_test_timer()
    if active is None:
        record("structure_active_fast_shape", False,
               "setup_failed: 'Test Timer' goal cell not found on Dashboard",
               depth=0, jump_kind="transition",
               expect="active-fast card adds ProgressBar+End Fast, FAB disappears")
    else:
        # SHAPE delta: a circular ProgressBar (the ring) + an "End Fast" control
        # appear, and the "Add Fast" FAB disappears while a fast is active.
        ring = find_by_class(active, "ProgressBar")
        end_fast = find_node(active, content_desc="End Fast")
        fab_after = bool(find_node(active, content_desc="Add Fast"))
        after = and_showing(active)
        changed = surface_changed(before, after)
        grew = bool(ring) and bool(end_fast) and fab_before and (not fab_after)
        # VLM while the ring is on screen (before we tear the fast down)
        vlm_assert("structure_active_fast_ring",
                   "Is there a circular ring or arc drawn around the countdown "
                   "timer numbers near the top-center of the screen? "
                   "Answer YES or NO.",
                   RESULTS_DIR, tag="shape", depth=0, jump_kind="transition")
        # reverse: end the fast (no save) -> the goal grid shape returns, ring gone.
        restored_nodes = end_active_fast_no_save(active)
        restored = (bool(find_node(restored_nodes, text="Set your goal"))
                    and not find_node(restored_nodes, content_desc="End Fast")
                    and bool(find_node(restored_nodes, content_desc="Add Fast")))
        ok = changed and grew and restored
        record("structure_active_fast_shape", ok,
               "" if ok else ("behavior_wrong: starting a fast did not swap the goal "
                              "card for the active-fast ring/End-Fast shape"
                              if not grew
                              else "behavior_wrong: ending the fast did not restore "
                                   "the Dashboard goal shape"),
               depth=0, jump_kind="transition",
               expect="goal card -> ProgressBar ring + End Fast + FAB gone; "
                      "restored to goal grid on End Fast")
        return
    # active is None path: still spend the declared VLM record (screenshot dashboard)
    vlm_assert("structure_active_fast_ring",
               "Is there a circular ring or arc drawn around the countdown "
               "timer numbers near the top-center of the screen? Answer YES or NO.",
               RESULTS_DIR, tag="shape", depth=0, jump_kind="transition")


# ═══════════════════════════════════════════════════════════════════════════════
# (3) SHAPE DELTAS — navigation-backed (depth>=1), each proven by and_reach_*
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_dashboard_to_profiles", "structure_profiles_grid_vlm"))
def test_dashboard_to_profiles_shape():
    open_main_clear()
    dash = ui()
    before = and_showing(dash)
    # Navigate to Manage Profiles (proves reach: 'Other Profiles' appears, the
    # 'Set your goal' goal card vanishes). Backs depth=1.
    reached = and_reach_screen(dash, trigger_text="Manage Profiles",
                               target="Other Profiles", source="Set your goal")
    prof = ui()
    after = and_showing(prof)
    # SHAPE: the profiles screen adds a grid of profile cards (many named cards) and
    # an "Add Profile" FAB — a materially different tree from the Dashboard.
    cards = [t for t in ("12 Hours", "14 Hours", "16 Hours", "18 Hours", "24 Hours")
             if find_node(prof, text=t)]
    add_fab = bool(find_node(prof, content_desc="Add Profile"))
    ok = reached and surface_changed(before, after) and len(cards) >= 4 and add_fab
    record("structure_dashboard_to_profiles", bool(ok),
           "" if ok else ("feature_missing: Manage Profiles screen not reached / no "
                          "profile-card grid + Add Profile FAB"),
           depth=1, jump_kind="transition",
           expect="Dashboard goal card -> Manage Profiles grid (>=4 duration cards) "
                  "+ Add Profile FAB")
    # VLM: the profiles are rendered as a grid of cards.
    vlm_assert("structure_profiles_grid",
               "Under the 'Other Profiles' heading, are multiple fasting-profile "
               "cards arranged in a two-column grid? Answer YES or NO.",
               RESULTS_DIR, tag="position", depth=1, jump_kind="transition")


@and_test(expects=("structure_add_profile_dialog", "structure_add_profile_dialog_vlm"))
def test_add_profile_dialog_shape():
    open_main_clear()
    dash = ui()
    reached = and_reach_screen(dash, trigger_text="Manage Profiles",
                               target="Other Profiles", source="Set your goal")
    prof = ui()
    n_edit_before = len(find_by_class(prof, "EditText"))
    # Open the Add Profile dialog (a new window layer over Manage Profiles). depth=2.
    opened = and_enter_dialog(prof, trigger_desc="Add Profile")
    dlg = ui()
    # SHAPE delta of the dialog layer: 3 EditText fields + 1 CheckBox appear.
    n_edit = len(find_by_class(dlg, "EditText"))
    n_check = len(find_by_class(dlg, "CheckBox"))
    has_labels = all(find_node(dlg, text=t) for t in ("Add Profile", "Cancel", "Save"))
    grew = (n_edit_before == 0 and n_edit == 3 and n_check == 1 and has_labels)
    # VLM WHILE THE DIALOG IS OPEN (must precede the Cancel that reverses it).
    vlm_assert("structure_add_profile_dialog",
               "Is there a rounded rectangular dialog card overlaid on the screen "
               "that contains three empty text input boxes stacked vertically with a "
               "'Cancel' and 'Save' button below them? Answer YES or NO.",
               RESULTS_DIR, tag="shape", depth=2, jump_kind="transition")
    # reverse: Cancel dismisses the dialog -> EditTexts gone, grid back.
    cancel = find_node(dlg, text="Cancel")
    if cancel:
        tap_node(cancel)
    back_nodes = ui()
    restored = (len(find_by_class(back_nodes, "EditText")) == 0
                and bool(find_node(back_nodes, content_desc="Add Profile")))
    ok = reached and opened and grew and restored
    record("structure_add_profile_dialog", bool(ok),
           "" if ok else ("behavior_wrong: Add Profile dialog did not add 3 "
                          "EditText fields + a checkbox" if not grew
                          else "behavior_wrong: Cancel did not dismiss the dialog"),
           depth=2, jump_kind="transition",
           expect="EditText 0->3 + 1 CheckBox on dialog open, restored on Cancel")


@and_test(expects=("structure_settings_rows", "structure_settings_toggles_vlm"))
def test_settings_row_shape():
    open_main_clear()
    dash = ui()
    before = and_showing(dash)
    reached = and_reach_screen(dash, trigger_desc="Settings",
                               target="Appearance", source="Set your goal")
    st = ui()
    after = and_showing(st)
    # SHAPE: a real Settings column has MANY distinct section/row labels; a stub
    # would not. Require at least 6 of the known section/row labels to be present.
    labels = ["Appearance", "Color Scheme", "First Day of Week",
              "Show Floating Action Button", "Use Expressive Progress Indicator",
              "Show Fasting Phases", "Notifications",
              "Show live progress notification", "Goal reached notification"]
    found = [x for x in labels if find_node_ci(st, x)]
    ok = reached and surface_changed(before, after) and len(found) >= 6
    record("structure_settings_rows", bool(ok),
           "" if ok else (f"feature_missing: Settings has only {len(found)} of the "
                          f"expected section/row labels ({found})"),
           depth=1, jump_kind="transition",
           expect="Settings column shows >=6 distinct section/row labels")
    # VLM: the toggle rows render as pill switches on the right of their labels.
    vlm_assert("structure_settings_toggles",
               "Does the Settings screen show setting rows with pill-shaped toggle "
               "switches aligned to the right side of the rows? Answer YES or NO.",
               RESULTS_DIR, tag="shape", depth=1, jump_kind="transition")


@and_test(expects=("structure_settings_scroll_reveal",))
def test_settings_scroll_reveal():
    open_main_clear()
    dash = ui()
    reached = and_reach_screen(dash, trigger_desc="Settings",
                               target="Appearance", source="Set your goal")
    top = ui()
    # A real Settings screen is a scrollable column: the "Export Data" / "Import
    # Data" Data-Management buttons sit BELOW the fold, so they are absent from the
    # first dump and a scroll REVEALS them (a scroll-driven shape change of what is
    # on screen). Also assert the column is wrapped in a ScrollView (a stub with a
    # fixed Column would not scroll). scroll_into_view re-dumps between swipes.
    scrollable = bool(find_by_class(top, "ScrollView"))
    export_top = find_node_ci(top, "Export Data")
    revealed = scroll_into_view("Export Data", max_swipes=6)
    import_after = find_node_ci(ui(), "Import Data")
    ok = (reached and scrollable and (export_top is None)
          and bool(revealed) and bool(import_after))
    record("structure_settings_scroll_reveal", bool(ok),
           "" if ok else ("behavior_wrong: 'Export Data'/'Import Data' not revealed "
                          "by scrolling the Settings column"
                          if export_top is None
                          else "behavior_wrong: 'Export Data' was already visible at "
                               "the top (no scroll delta)"),
           depth=1, jump_kind="transition",
           expect="ScrollView column; 'Export Data' hidden at top, revealed on scroll")


@and_test(expects=("structure_statistics_containers", "structure_stats_cards_vlm",
                   "structure_stats_chart_vlm"))
def test_statistics_containers_shape():
    open_main_clear()
    dash = ui()
    before = and_showing(dash)
    reached = and_reach_screen(dash, trigger_desc="Go to Statistics",
                               target="Trends", source="Set your goal")
    st = ui()
    after = and_showing(st)
    # SHAPE: the expected SET of statistics containers exists — the three stat cards,
    # the "Trends" block, and the segmented toggles (RadioButton group, >=3 options).
    stat_cards = [t for t in ("Total Fasts", "Average Fast", "Consistency")
                  if find_node(st, text=t)]
    trends = bool(find_node(st, text="Trends"))
    radios = find_by_class(st, "RadioButton")
    ok = (reached and surface_changed(before, after)
          and len(stat_cards) == 3 and trends and len(radios) >= 3)
    record("structure_statistics_containers", bool(ok),
           "" if ok else ("feature_missing: Statistics screen missing expected "
                          f"containers (cards={stat_cards}, trends={trends}, "
                          f"radios={len(radios)})"),
           depth=1, jump_kind="transition",
           expect="3 stat cards + 'Trends' + a >=3-option segmented toggle present")
    # VLM: the three Material-3-Expressive stat cards have distinctive non-rectangular
    # shapes (pentagon / blob / scalloped).
    vlm_assert("structure_stats_cards",
               "Are the three statistics cards ('Total Fasts', 'Average Fast', "
               "'Consistency') drawn as non-rectangular blob/pentagon/scalloped "
               "shapes rather than plain rectangles? Answer YES or NO.",
               RESULTS_DIR, tag="shape", depth=1, jump_kind="transition")
    # VLM: a horizontal bar chart is rendered above the day/date axis.
    vlm_assert("structure_stats_chart",
               "Is there a horizontal row of bar-chart segments drawn above a row of "
               "single-letter day-of-week axis labels? Answer YES or NO.",
               RESULTS_DIR, tag="shape", depth=1, jump_kind="transition")


@and_test(expects=("structure_statistics_expand",))
def test_statistics_expand_shape():
    open_main_clear()
    dash = ui()
    reached = and_reach_screen(dash, trigger_desc="Go to Statistics",
                               target="Trends", source="Set your goal")
    st = ui()
    before = and_showing(st)
    n_before = len(st)
    # The "All-time statistics" Expand chevron GROWS the tree (adds a Total Duration
    # row + a Collapse control). Locate the expand affordance and toggle it.
    exp = find_node(st, content_desc="Expand")
    if exp is None:
        # fall back to the row label if the chevron desc differs
        exp = find_node(st, text="All-time statistics")
    grew = restored = False
    if exp is not None:
        tap_node(exp)
        st2 = ui()
        after = and_showing(st2)
        added = after - before
        grew = (len(st2) > n_before
                and (any("Collapse" in k for k in added)
                     or any("Total Duration" in k for k in added)))
        # reverse: collapse it back
        coll = (find_node(st2, content_desc="Collapse")
                or find_node(st2, content_desc="Expand"))
        if coll:
            tap_node(coll)
        st3 = ui()
        restored = (not find_node(st3, content_desc="Collapse"))
    ok = reached and grew and restored
    record("structure_statistics_expand", bool(ok),
           "" if ok else ("behavior_wrong: 'All-time statistics' expand did not grow "
                          "the tree" if not grew
                          else "behavior_wrong: expanded section did not collapse back"),
           depth=1, jump_kind="transition",
           expect="All-time statistics expand adds Total Duration/Collapse, "
                  "restored on collapse")


@and_test(expects=("structure_history_calendar", "structure_history_grid_vlm",
                   "structure_history_summary_vlm"))
def test_history_calendar_shape():
    open_main_clear()
    dash = ui()
    before = and_showing(dash)
    reached = and_reach_screen(dash, trigger_desc="Go to History",
                               target="August 2026", source="Set your goal")
    hist = ui()
    after = and_showing(hist)
    # SHAPE: a real month calendar has a large number of numeric day cells. Count
    # distinct day numbers 1..31; a stub would not render a full grid.
    days = set()
    for n in hist:
        t = n.get("text", "").strip()
        if t.isdigit() and 1 <= int(t) <= 31:
            days.add(int(t))
    month_hdr = bool(find_node(hist, text="August 2026"))
    nav = (bool(find_node(hist, content_desc="Previous Month"))
           and bool(find_node(hist, content_desc="Next Month")))
    ok = (reached and surface_changed(before, after)
          and len(days) >= 28 and month_hdr and nav)
    record("structure_history_calendar", bool(ok),
           "" if ok else (f"feature_missing: History calendar incomplete "
                          f"(distinct day cells={len(days)}, header={month_hdr}, "
                          f"month-nav={nav})"),
           depth=1, jump_kind="transition",
           expect=">=28 distinct day cells + month header + prev/next month nav")
    # VLM: the days form a month grid with a weekday header row.
    vlm_assert("structure_history_grid",
               "Is there a monthly calendar laid out as a grid of numbered day cells "
               "in seven columns, with a row of weekday letters above it? "
               "Answer YES or NO.",
               RESULTS_DIR, tag="position", depth=1, jump_kind="transition")
    # VLM: the 'August Summary' shows three distinctly-shaped stat cards.
    vlm_assert("structure_history_summary",
               "Below the calendar, does the 'August Summary' section show three "
               "non-rectangular stat cards positioned side by side in one row? "
               "Answer YES or NO.",
               RESULTS_DIR, tag="shape", depth=1, jump_kind="transition")


# ═══════════════════════════════════════════════════════════════════════════════
TESTS = [
    test_gate_launch,
    test_gate_dashboard_surfaces,
    test_gate_goal_grid,
    test_fab_speeddial_expand,
    test_active_fast_shape,
    test_dashboard_to_profiles_shape,
    test_add_profile_dialog_shape,
    test_settings_row_shape,
    test_settings_scroll_reveal,
    test_statistics_containers_shape,
    test_statistics_expand_shape,
    test_history_calendar_shape,
]

if __name__ == "__main__":
    if not device_online():
        print("setup_failed: device offline / adb tunnel down — aborting")
        sys.exit(2)
    run_suite(TESTS, "structure")