File size: 33,528 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
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
#!/usr/bin/env python3
"""NAVIGATION module — FastTimes (intermittent-fasting tracker).

Owns surface REACHABILITY and back-stack integrity ONLY. Every jump is proven with
and_reach(before, after, target, source): the TARGET surface's discriminating
element APPEARED *and* the SOURCE surface's element DISAPPEARED — a flat dump read
of an always-present element can never fake a reach. This lane is the sole owner of
jump_kind="reach" and of the deep (depth>=2/>=3) chains; the other lanes stay
shallow so real navigation depth is measured here.

Nav graph (verified live on the original):
  main = draggable two-pane Dashboard <-> History (swipe OR "Go to History"; BACK
         or the Back arrow returns to Dashboard — History is NOT a nav route).
  Dashboard -> Settings (gear), Manage Profiles (link), Statistics ("Go to
              Statistics"). Settings -> Theme & Accent Color (Custom swatch).
  History -> Daily Details (tap a day with a fast) -> Edit Fast dialog.
  History -> History Info sheet ("i"). Active fast -> phase-detail sheet (chip).
  Statistics -> History (top-right History icon).

Compose renders as android.view.View / TextView with NO resource-ids, so every
trigger and every discriminating key is a visible text or content-desc.

VLM budget for this lane = 6 (transition end-states / toolbar affordances that are
visual): the Statistics chart, the History month grid, the Theme&Accent swatch
grid, the History-Info bottom sheet, the Daily-Details bottom sheet, and the
Edit-Fast centered dialog card. Every other reach/back-stack case is pure rule.

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

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


# ── 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():
    """The first-run "Notification Preferences" rationale can appear on the first
    goal tap after clear_data(). Dismiss it (choice is irrelevant to navigation)."""
    nodes = ui()
    if not find_node(nodes, text="Notification Preferences"):
        return False
    for label in ("No Notifications", "Cancel", "Skip", "Enable Notifications"):
        n = find_node(nodes, text=label)
        if n:
            tap_node(n)
            settle("tap")
            return True
    return False


def _on_dashboard(nodes=None):
    nodes = ui() if nodes is None else nodes
    return find_node(nodes, text="Set your goal") is not None


def start_test_timer_active():
    """From a CLEAN dashboard, tap the Test Timer goal cell -> ACTIVE-FAST card.
    Handles the optional first-run notification rationale. Returns True on success."""
    dash = ui()
    cell = find_node(dash, text="Test Timer")
    if not cell:
        return False
    tap_node(cell)
    settle("tap")
    _dismiss_notif_rationale()
    after = ui()
    if find_node(after, content_desc="End Fast"):
        return True
    # 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")
        _dismiss_notif_rationale()
    return find_node(ui(), content_desc="End Fast") is not None


def wait_goal_reached(timeout_polls=16):
    """Poll until the Test Timer flips to 'Goal Reached!' (~11 s). Bounded so a
    slow emulator never hangs the suite; returns whether it flipped."""
    for _ in range(timeout_polls):
        if find_node(ui(), text="Goal Reached!"):
            return True
        settle("tap")
    return False


def save_test_timer_fast():
    """Complete + SAVE one Test Timer fast from a clean dashboard, landing back on
    the Dashboard with the fast persisted (so day 5 in History has a record).
    Returns True on success."""
    if not start_test_timer_active():
        return False
    wait_goal_reached()                      # a completed fast earns the Goal-Met dot
    ef = find_node(ui(), content_desc="End Fast")
    if not ef:
        return False
    tap_node(ef)
    settle("tap")
    save = find_node(ui(), text="Save")      # "Fast Complete!" summary modal
    if not save:
        return False
    tap_node(save)
    settle("tap")
    return _on_dashboard()


def open_history_via_link():
    """Dashboard -> History pane through the 'Go to History' arrow. Returns True
    when the calendar month header is showing."""
    n = find_node(ui(), content_desc="Go to History")
    if not n:
        return False
    tap_node(n)
    settle("tap")
    return find_node(ui(), text="August 2026") is not None


def open_daily_details_day5():
    """From the History pane, tap the day-5 cell (which holds the saved fast) and
    open its Daily Details bottom sheet. Returns True when the sheet is showing."""
    nodes = ui()
    day = find_node(nodes, text="5")
    marker = find_node(nodes, content_desc="Goal Met")
    # Prefer a point spanning the day number and its Goal-Met dot so the tap lands
    # on the day cell regardless of which sub-node is the click target.
    if day and marker and "_center" in day and "_center" in marker:
        x = (day["_center"][0] + marker["_center"][0]) // 2
        y = (day["_center"][1] + marker["_center"][1]) // 2
        tap(x, y)
    elif marker:
        tap_node(marker)
    elif day:
        tap_node(day)
    else:
        return False
    return any("details for" in k.lower() for k in and_showing())


def _color_scheme_row_y():
    """Vertical centre of the horizontally-scrollable Color Scheme swatch row.
    That row is the short scrollable=true node (the tall one is the page's outer
    vertical ScrollView), so pick the scrollable node with the smallest height."""
    rows = [n for n in find_nodes(ui(), scrollable=True) if "_bounds" in n]
    short = None
    for n in rows:
        h = n["_bounds"][3] - n["_bounds"][1]
        if h < 400 and (short is None
                        or h < (short["_bounds"][3] - short["_bounds"][1])):
            short = n
    if short:
        return (short["_bounds"][1] + short["_bounds"][3]) // 2
    return None


# ── Named depth helpers (the and_enter_*/and_reach_* NAME is what the depth audit
# looks for; each body is a real, proven jump). ────────────────────────────────
def and_reach_by(trigger_text="", trigger_desc="", target="", source=""):
    """Locate a labelled trigger on the CURRENT surface, then PROVE the jump:
    `target` appeared and `source` vanished. Counts one surface (jump_kind='reach')."""
    nodes = ui()
    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_reach_settings():
    return and_reach_by(trigger_desc="Settings", target="Appearance",
                        source="Set your goal")


def and_reach_statistics():
    return and_reach_by(trigger_desc="Go to Statistics", target="Trends",
                        source="Set your goal")


def and_reach_profiles():
    return and_reach_by(trigger_text="Manage Profiles", target="Other Profiles",
                        source="Set your goal")


def and_reach_accent_color():
    """Settings -> Theme & Accent Color. The 'Custom' swatch sits at the far right
    of the horizontally-scrollable Color Scheme row, so scroll that row left first,
    then tap the swatch CIRCLE (which is the clickable element sitting just ABOVE
    the 'Custom' label — the label TextView itself is not the click target)."""
    s = get_screen_info()
    y = _color_scheme_row_y()
    if y is None:
        row = find_node(ui(), text="Color Scheme")
        y = (row["_bounds"][3] + 90) if (row and "_bounds" in row) \
            else int(s["height"] * 0.40)
    for _ in range(5):
        if find_node(ui(), text="Custom"):
            break
        swipe(int(s["width"] * 0.9), y, int(s["width"] * 0.11), y, ms=400)
    custom = find_node(ui(), text="Custom")
    if not custom or "_bounds" not in custom:
        return False
    cx = custom["_center"][0]
    cy = custom["_bounds"][1] - 90            # the swatch circle above the label
    before = and_showing()
    tap(cx, cy)
    after = and_showing()
    ok = and_reach(before, after, "Accent Color", "Color Scheme")
    if ok:
        and_enter("Theme & Accent Color")
    return ok


def and_reach_history_info():
    return and_reach_by(trigger_desc="History Info", target="Understanding History",
                        source="August 2026")


def and_reach_phase_sheet():
    return and_reach_by(trigger_text="Post-Absorptive State", target="Timing",
                        source="Current Fast")


def and_reach_daily_details():
    """History pane -> Daily Details sheet for day 5. Proven via and_showing delta
    (the sheet title appears, the month header vanishes). Counts one surface."""
    before = and_showing()
    if not open_daily_details_day5():
        return False
    after = and_showing()
    ok = and_reach(before, after, "Details for", "August 2026")
    if ok:
        and_enter("Daily Details")
    return ok


def and_reach_edit_fast():
    """Daily Details sheet -> Edit Fast dialog (pencil). Counts one surface."""
    n = find_node(ui(), content_desc="Edit Fast")
    if not n:
        return False
    return and_reach_surface(n, "Start Time", "Details for")


# ═══════════════════════════════════════════════════════════════════════════════
# (1) TOP-LEVEL REACH — one per route (depth=1, jump_kind="reach")
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_reach_settings",))
def test_reach_settings():
    open_main_clear()
    ok = _on_dashboard() and and_reach_settings()
    record("navigation_reach_settings", bool(ok),
           "" if ok else "feature_missing: Settings not reached from the Dashboard "
                         "gear (Appearance did not appear / Set-your-goal did not "
                         "disappear)",
           depth=1, jump_kind="reach",
           expect="Settings 'Appearance' appeared; Dashboard 'Set your goal' left")


@and_test(expects=("navigation_reach_profiles",))
def test_reach_profiles():
    open_main_clear()
    ok = _on_dashboard() and and_reach_profiles()
    record("navigation_reach_profiles", bool(ok),
           "" if ok else "feature_missing: Manage Profiles not reached from the "
                         "Dashboard link ('Other Profiles' did not appear / "
                         "'Set your goal' did not disappear)",
           depth=1, jump_kind="reach",
           expect="Manage Profiles 'Other Profiles' appeared; 'Set your goal' left")


@and_test(expects=("navigation_reach_statistics", "navigation_reach_statistics_vlm"))
def test_reach_statistics():
    open_main_clear()
    ok = _on_dashboard() and and_reach_statistics()
    record("navigation_reach_statistics", bool(ok),
           "" if ok else "feature_missing: Statistics ('Performance') not reached "
                         "from 'Go to Statistics' ('Trends' did not appear / "
                         "'Set your goal' did not disappear)",
           depth=1, jump_kind="reach",
           expect="Statistics 'Trends' appeared; Dashboard 'Set your goal' left")
    # VLM END-STATE: the statistics screen renders a bar chart over a day-letter axis.
    vlm_assert("navigation_reach_statistics",
               "Is there a horizontal row of bar-chart segments drawn above a row of "
               "single-letter day-of-week axis labels (like T F S S M T W)? "
               "Answer YES or NO.",
               RESULTS_DIR, tag="shape", depth=1, jump_kind="reach")


@and_test(expects=("navigation_reach_history", "navigation_reach_history_vlm"))
def test_reach_history():
    open_main_clear()
    n = find_node(ui(), content_desc="Go to History")
    ok = bool(n) and and_reach_surface(n, "August 2026", "Set your goal")
    record("navigation_reach_history", bool(ok),
           "" if ok else "feature_missing: History pane not reached from 'Go to "
                         "History' ('August 2026' did not appear / 'Set your goal' "
                         "did not disappear)",
           depth=1, jump_kind="reach",
           expect="History 'August 2026' appeared; Dashboard 'Set your goal' left")
    # VLM END-STATE: the History pane presents a month calendar grid.
    vlm_assert("navigation_reach_history",
               "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="reach")


@and_test(expects=("navigation_reach_history_swipe",))
def test_reach_history_swipe():
    open_main_clear()
    reached = False
    s = get_screen_info()
    # main is a draggable two-pane: a slow right->left horizontal drag flips
    # Dashboard -> History. Retry at a couple of y-bands (the goal grid intercepts
    # some rows). Each attempt is a proven reach via and_showing before/after.
    for yf in (0.30, 0.45, 0.60):
        if not _on_dashboard():
            open_main()
        before = and_showing()
        y = int(s["height"] * yf)
        swipe(int(s["width"] * 0.92), y, int(s["width"] * 0.08), y, ms=600)
        after = and_showing()
        if and_reach(before, after, "August 2026", "Set your goal"):
            reached = True
            and_enter("History (drag)")
            break
    record("navigation_reach_history_swipe", bool(reached),
           "" if reached else "feature_missing: dragging the two-pane did not flip "
                              "Dashboard -> History ('August 2026' never appeared)",
           depth=1, jump_kind="reach",
           expect="Horizontal drag: History 'August 2026' appeared; 'Set your "
                  "goal' left")


# ═══════════════════════════════════════════════════════════════════════════════
# (2) BACK-STACK INTEGRITY — reach then BACK restores the exact source (reach)
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_back_settings",))
def test_back_settings():
    open_main_clear()
    deep = and_reach_settings()
    before = and_showing()                 # Settings surface
    and_back()                             # pop one surface
    after = and_showing()
    restored = and_reach(before, after, target="Set your goal", source="Appearance")
    ok = deep and restored
    record("navigation_back_settings", bool(ok),
           "" if ok else ("setup_failed: Settings not reached" if not deep
                          else "behavior_wrong: BACK from Settings did not restore "
                               "the Dashboard ('Set your goal')"),
           depth=1, jump_kind="reach",
           expect="After BACK: 'Set your goal' restored; Settings 'Appearance' gone")


@and_test(expects=("navigation_back_profiles",))
def test_back_profiles():
    open_main_clear()
    deep = and_reach_profiles()
    before = and_showing()
    and_back()
    after = and_showing()
    restored = and_reach(before, after, target="Set your goal", source="Other Profiles")
    ok = deep and restored
    record("navigation_back_profiles", bool(ok),
           "" if ok else ("setup_failed: Manage Profiles not reached" if not deep
                          else "behavior_wrong: BACK from Manage Profiles did not "
                               "restore the Dashboard"),
           depth=1, jump_kind="reach",
           expect="After BACK: 'Set your goal' restored; 'Other Profiles' gone")


@and_test(expects=("navigation_back_statistics",))
def test_back_statistics():
    open_main_clear()
    deep = and_reach_statistics()
    before = and_showing()
    and_back()
    after = and_showing()
    restored = and_reach(before, after, target="Set your goal", source="Trends")
    ok = deep and restored
    record("navigation_back_statistics", bool(ok),
           "" if ok else ("setup_failed: Statistics not reached" if not deep
                          else "behavior_wrong: BACK from Statistics did not restore "
                               "the Dashboard"),
           depth=1, jump_kind="reach",
           expect="After BACK: 'Set your goal' restored; Statistics 'Trends' gone")


@and_test(expects=("navigation_back_history",))
def test_back_history():
    open_main_clear()
    n = find_node(ui(), content_desc="Go to History")
    deep = bool(n) and and_reach_surface(n, "August 2026", "Set your goal")
    before = and_showing()                 # History pane
    and_back()                             # History uses a BackHandler -> Dashboard
    after = and_showing()
    restored = and_reach(before, after, target="Set your goal", source="August 2026")
    ok = deep and restored
    record("navigation_back_history", bool(ok),
           "" if ok else ("setup_failed: History pane not reached" if not deep
                          else "behavior_wrong: BACK from History did not return to "
                               "the Dashboard ('Set your goal')"),
           depth=1, jump_kind="reach",
           expect="After BACK: Dashboard 'Set your goal' restored; History "
                  "'August 2026' gone")


@and_test(expects=("navigation_history_back_arrow",))
def test_history_back_arrow():
    open_main_clear()
    n = find_node(ui(), content_desc="Go to History")
    deep = bool(n) and and_reach_surface(n, "August 2026", "Set your goal")
    # The History pane shows a top-left Back arrow (desc="Back"); tapping it returns
    # to the Dashboard. Prove the reverse reach on that arrow specifically.
    arrow = find_node(ui(), content_desc="Back")
    reached_home = bool(arrow) and and_reach_surface(arrow, "Set your goal",
                                                     "August 2026")
    if reached_home:
        and_back()  # keep the depth counter honest (this pop matches the arrow)
    ok = deep and reached_home
    record("navigation_history_back_arrow", bool(ok),
           "" if ok else ("setup_failed: History pane not reached" if not deep
                          else "behavior_wrong: the History Back arrow did not return "
                               "to the Dashboard"),
           depth=1, jump_kind="reach",
           expect="Back-arrow tap: Dashboard 'Set your goal' restored; 'August "
                  "2026' gone")


# ═══════════════════════════════════════════════════════════════════════════════
# (3) DEPTH-2 CHAIN — Dashboard -> Settings -> Theme & Accent Color
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_reach_accent_color", "navigation_reach_accent_color_vlm"))
def test_reach_accent_color():
    open_main_clear()
    hop1 = and_reach_settings()                 # depth 1
    hop2 = hop1 and and_reach_accent_color()    # depth 2
    ok = hop1 and hop2
    record("navigation_reach_accent_color", bool(ok),
           "" if ok else ("setup_failed: Settings not reached" if not hop1
                          else "feature_missing: Theme & Accent Color not reached "
                               "from the Color Scheme 'Custom' swatch ('Accent "
                               "Color' did not appear)"),
           depth=2, jump_kind="reach",
           expect="Dashboard->Settings->Theme&Accent: 'Accent Color' appeared; "
                  "Settings 'Color Scheme' left")
    # VLM END-STATE: the Theme & Accent screen shows a grid of round color swatches.
    vlm_assert("navigation_reach_accent_color",
               "Under an 'Accent Color' heading, is there a grid of multiple small "
               "circular color swatches? Answer YES or NO.",
               RESULTS_DIR, tag="shape", depth=2, jump_kind="reach")


@and_test(expects=("navigation_backstack_accent",))
def test_backstack_accent():
    open_main_clear()
    hop1 = and_reach_settings()
    hop2 = hop1 and and_reach_accent_color()    # now 2 deep: Dashboard/Settings/Accent
    # Unwind hop by hop: BACK -> Settings, BACK -> Dashboard, asserting each pop.
    before_a = and_showing()                    # Theme & Accent
    and_back()
    after_a = and_showing()
    to_settings = and_reach(before_a, after_a, target="Color Scheme",
                            source="Accent Color")
    before_s = and_showing()                    # Settings
    and_back()
    after_s = and_showing()
    to_dash = and_reach(before_s, after_s, target="Set your goal", source="Appearance")
    ok = hop1 and hop2 and to_settings and to_dash
    record("navigation_backstack_accent", bool(ok),
           "" if ok else ("setup_failed: accent-color chain not built"
                          if not (hop1 and hop2)
                          else "behavior_wrong: BACK did not unwind Theme&Accent -> "
                               "Settings -> Dashboard hop by hop"),
           depth=2, jump_kind="reach",
           expect="1st BACK -> Settings 'Color Scheme'; 2nd BACK -> Dashboard "
                  "'Set your goal'")


# ═══════════════════════════════════════════════════════════════════════════════
# (4) SHEET / OVERLAY REACH
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_reach_history_info", "navigation_reach_history_info_vlm"))
def test_reach_history_info():
    open_main_clear()
    on_hist = open_history_via_link()            # depth 1 (not asserted as reach here)
    reached = on_hist and and_reach_history_info()
    ok = on_hist and reached
    record("navigation_reach_history_info", bool(ok),
           "" if ok else ("setup_failed: History pane not reached" if not on_hist
                          else "feature_missing: 'History Info' did not open the "
                               "'Understanding History' sheet"),
           depth=2, jump_kind="reach",
           expect="History 'Understanding History' sheet appeared; 'August 2026' left")
    # VLM END-STATE: an info sheet is presented from the bottom over the calendar.
    vlm_assert("navigation_reach_history_info",
               "Is a titled information panel presented over the lower portion of the "
               "screen as a bottom sheet (a rounded panel rising from the bottom edge "
               "with a small drag handle at its top)? Answer YES or NO.",
               RESULTS_DIR, tag="position", depth=2, jump_kind="reach")


@and_test(expects=("navigation_reach_phase_sheet",))
def test_reach_phase_sheet():
    open_main_clear()
    active = start_test_timer_active()           # active-fast card shows the phase chip
    reached = active and and_reach_phase_sheet()
    ok = active and reached
    record("navigation_reach_phase_sheet", bool(ok),
           "" if ok else ("setup_failed: could not start a Test Timer fast"
                          if not active
                          else "feature_missing: tapping the 'Post-Absorptive State' "
                               "chip did not open the phase-detail sheet ('Timing' "
                               "did not appear)"),
           depth=1, jump_kind="reach",
           expect="Phase sheet 'Timing' appeared; active-fast 'Current Fast' left")


# ═══════════════════════════════════════════════════════════════════════════════
# (5) STATISTICS -> HISTORY cross-navigation
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_stats_to_history",))
def test_stats_to_history():
    open_main_clear()
    on_stats = and_reach_statistics()            # depth 1
    # Statistics has a top-right History icon (desc="History") that jumps to the
    # History pane. Prove it: 'August 2026' appears, Statistics 'Trends' leaves.
    reached = on_stats and and_reach_by(trigger_desc="History", target="August 2026",
                                        source="Trends")
    ok = on_stats and reached
    record("navigation_stats_to_history", bool(ok),
           "" if ok else ("setup_failed: Statistics not reached" if not on_stats
                          else "feature_missing: the Statistics History icon did not "
                               "jump to the History pane"),
           depth=2, jump_kind="reach",
           expect="Statistics History icon -> 'August 2026' appeared; 'Trends' left")


# ═══════════════════════════════════════════════════════════════════════════════
# (6) DATA-DEPENDENT DEEP CHAIN — History -> Daily Details -> Edit Fast + unwind
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("navigation_reach_daily_details", "navigation_reach_daily_details_vlm"))
def test_reach_daily_details():
    open_main_clear()
    made = save_test_timer_fast()                # create the record we navigate to
    on_hist = made and open_history_via_link()   # depth 1
    reached = on_hist and and_reach_daily_details()  # depth 2 (Daily Details sheet)
    ok = made and on_hist and reached
    record("navigation_reach_daily_details", bool(ok),
           "" if ok else ("setup_failed: could not save a Test Timer fast" if not made
                          else "setup_failed: History pane not reached" if not on_hist
                          else "feature_missing: tapping day 5 did not open its "
                               "Daily Details sheet ('Details for ...' did not appear)"),
           depth=2, jump_kind="reach",
           expect="Day-5 tap -> 'Details for August 5' sheet appeared; 'August "
                  "2026' left")
    # VLM END-STATE: the daily details are a bottom sheet overlay.
    vlm_assert("navigation_reach_daily_details",
               "Is a titled details panel presented over the lower portion of the "
               "screen as a bottom sheet (a rounded panel rising from the bottom "
               "edge), with the dimmed calendar visible above it? Answer YES or NO.",
               RESULTS_DIR, tag="position", depth=2, jump_kind="reach")


@and_test(expects=("navigation_reach_edit_fast", "navigation_reach_edit_fast_vlm"))
def test_reach_edit_fast():
    open_main_clear()
    made = save_test_timer_fast()
    on_hist = made and open_history_via_link()       # depth 1
    on_sheet = on_hist and and_reach_daily_details()  # depth 2
    reached = on_sheet and and_reach_edit_fast()      # depth 3 (Edit Fast dialog)
    ok = made and on_hist and on_sheet and reached
    record("navigation_reach_edit_fast", bool(ok),
           "" if ok else ("setup_failed: could not build History->Daily-Details"
                          if not on_sheet
                          else "feature_missing: the Daily Details 'Edit Fast' pencil "
                               "did not open the Edit Fast dialog ('Start Time' did "
                               "not appear)"),
           depth=3, jump_kind="reach",
           expect="Edit-Fast pencil -> dialog 'Start Time' appeared; sheet 'Details "
                  "for' left")
    # VLM END-STATE: Edit Fast is a centered dialog card (not a bottom sheet).
    vlm_assert("navigation_reach_edit_fast",
               "Is there an 'Edit Fast' dialog shown as a rounded rectangular card "
               "floating in the center of the screen (with 'Cancel' and 'Save' "
               "buttons), rather than attached to the bottom edge? Answer YES or NO.",
               RESULTS_DIR, tag="position", depth=3, jump_kind="reach")


@and_test(expects=("navigation_backstack_deep",))
def test_backstack_deep():
    open_main_clear()
    made = save_test_timer_fast()
    on_hist = made and open_history_via_link()
    on_sheet = on_hist and and_reach_daily_details()   # depth 2
    on_dialog = on_sheet and and_reach_edit_fast()     # depth 3
    built = made and on_hist and on_sheet and on_dialog
    # Unwind the deepest chain hop by hop.
    # hop 3->2: Cancel the Edit Fast dialog (safe; never touch 'Delete Fast').
    cancel = find_node(ui(), text="Cancel")
    if cancel:
        tap_node(cancel)
    else:
        and_back()
    settle("tap")
    back_on_sheet = any("details for" in k.lower() for k in and_showing())
    # hop 2->1: BACK closes the Daily Details sheet -> History pane.
    before_s = and_showing()
    and_back()
    after_s = and_showing()
    to_history = and_reach(before_s, after_s, target="August 2026", source="Details for")
    # hop 1->0: BACK closes the History pane -> Dashboard.
    before_h = and_showing()
    and_back()
    after_h = and_showing()
    to_dash = and_reach(before_h, after_h, target="Set your goal", source="August 2026")
    ok = built and back_on_sheet and to_history and to_dash
    record("navigation_backstack_deep", bool(ok),
           "" if ok else ("setup_failed: could not build the "
                          "Dashboard->History->Details->Edit chain" if not built
                          else "behavior_wrong: BACK did not unwind Edit -> Details "
                               "-> History -> Dashboard hop by hop"),
           depth=3, jump_kind="reach",
           expect="Cancel->Details sheet; BACK->History 'August 2026'; BACK->"
                  "Dashboard 'Set your goal'")


# ═══════════════════════════════════════════════════════════════════════════════
TESTS = [
    test_reach_settings,
    test_reach_profiles,
    test_reach_statistics,
    test_reach_history,
    test_reach_history_swipe,
    test_back_settings,
    test_back_profiles,
    test_back_statistics,
    test_back_history,
    test_history_back_arrow,
    test_reach_accent_color,
    test_backstack_accent,
    test_reach_history_info,
    test_reach_phase_sheet,
    test_stats_to_history,
    test_reach_daily_details,
    test_reach_edit_fast,
    test_backstack_deep,
]

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