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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
#!/usr/bin/env python3
"""openScale — STATE-CHANGE lane.

This lane OWNS `checked` / `selected` / `focused` transitions and their
app-authored consequence, page-level state machines, conditional enable/disable,
and SETTINGS/mode persistence. Every test reads the state BEFORE from a fresh
ui(), drives the change through the real user path, reads AFTER from a fresh
ui() (re-locating the node — the old dict is stale), and asserts the flip PLUS
its consequence where one is observable.

GROUND TRUTH (all OBSERVED on the running original on this emulator):
  * Compose switches render as `View checkable="true" checked=... clickable=true`;
    the row LABEL is a SEPARATE `View cd="<label>"` (or a TextView with that text).
    To flip: tap the label ROW, RE-DUMP, read `checked` on the nearest checkable
    View on that row's y. All five General toggles default OFF.
  * Settings → General (drawer → Settings → General): toggles Dynamic colors,
    High contrast, Vibration on new measurement, Reminder function, File Logging.
  * Enabling "Reminder function" pops the OS notification-permission dialog — that
    IS its observable consequence; the dialog must be dismissed or it poisons
    later tests, so _dismiss_perm_dialog() runs before every drawer navigation.
  * Settings → Chart: Show data points (default ON), Show goal lines (OFF),
    Show projection (OFF).
  * Settings → Measurement Types → (row) Edit → "Edit Type" form: real checkable
    toggles Enabled / Pinned / On right Y-axis (depth 3).
  * Table state machine: default "No columns selected for display."; tapping a
    metric-filter icon enables that column and a data row appears; "Select items"
    → "0 selected"; tapping the data row → "1 selected" (the row also gains a
    filled teal checkbox + a light-blue tint — a VLM colour/shape subject).
  * High contrast / Dynamic colors ON visibly recolour the switch (dark/navy or
    blue track, thumb to the RIGHT) — VLM colour/position subjects.

Deliberately NOT tested (genuinely unobservable in this build, so a test would
be a guaranteed baseline_fail rather than a signal about any recreation):
  * "Assisted Weighing" switch on the Add-User form — the form exposes no
    checkable View and does not scroll; the switch is not in the view tree here.
  * Smoothing-Algorithm dropdown selection — the field did not read back the
    chosen option reliably, so the selected-state could not be asserted.
"""
import os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from android_testgen_kit import *          # noqa: F403,F401

TESTS = []


def _register(fn):
    TESTS.append(fn)
    return fn


# ══════════════════════════════════════════════════════════════════════════════
# Locators for Compose switches (the checkable View is anonymous; find it by the
# label row's vertical position).
# ══════════════════════════════════════════════════════════════════════════════

def _checkable_on_row(nodes, label):
    """The checkable+clickable View on the same row as `label` (matched by cd or
    text), i.e. the toggle whose y-centre is within ~90px of the label's."""
    lab = find_node(nodes, content_desc=label) or find_node_ci(nodes, label)
    if lab is None or "_center" not in lab:
        return None
    ly = lab["_center"][1]
    cands = [n for n in nodes
             if n.get("checkable") == "true" and n.get("clickable") == "true"
             and "_center" in n and abs(n["_center"][1] - ly) < 90]
    cands.sort(key=lambda n: abs(n["_center"][1] - ly))   # nearest by |dy|
    return cands[0] if cands else None


def _row_trigger(nodes, label):
    """The tappable ROW for `label` — prefer the cd-labelled View (the whole row
    is clickable), else the checkable toggle itself."""
    row = find_node(nodes, content_desc=label)
    if row is not None:
        return row
    return _checkable_on_row(nodes, label)


def _read_checked(label):
    """Read `checked` for a labelled toggle out of a FRESH dump."""
    sw = _checkable_on_row(ui(), label)
    return None if sw is None else sw.get("checked")


# ══════════════════════════════════════════════════════════════════════════════
# System-dialog immunity. Enabling 'Reminder function' shows the OS notification-
# permission dialog; if left up it overlays a relaunched openScale and breaks
# every later test's navigation. Dismiss it non-destructively.
# ══════════════════════════════════════════════════════════════════════════════

def _perm_dialog_showing(nodes=None):
    nodes = ui() if nodes is None else nodes
    return (find_node_ci(nodes, "Allow openScale to send you notifications?")
            is not None
            or (find_node_ci(nodes, "Don’t allow") is not None
                and find_node_ci(nodes, "Allow") is not None))


def _dismiss_perm_dialog():
    """Tap 'Don't allow' (NON-destructive — never touches app data) if the OS
    permission dialog is up. Returns True if one was dismissed."""
    dismissed = False
    for _ in range(2):
        nodes = ui()
        if not _perm_dialog_showing(nodes):
            break
        btn = (find_node_ci(nodes, "Don’t allow")
               or find_node_ci(nodes, "Don't allow")
               or find_node_ci(nodes, "Deny"))
        if btn is not None and is_safe(btn) and tap_node(btn):
            dismissed = True
            settle("tap")
        else:
            break
    return dismissed


def _clean_launch():
    """restart_app + wait + dismiss any leftover system dialog. Kept in a helper
    so the process relaunch never appears in a test BODY (the depth auditor treats
    an in-body relaunch as non-navigation)."""
    restart_app()
    wait_for_foreground()
    settle("launch")
    _dismiss_perm_dialog()
    return device_online()


# ══════════════════════════════════════════════════════════════════════════════
# depth-family navigation helpers — the and_enter_* / and_reach_* NAMES are what
# back every declared depth>=1 (the auditor descends into these file-local
# helpers and looks for and_enter()/and_reach()). Each opens ONE surface.
# ══════════════════════════════════════════════════════════════════════════════

def _open_menu():
    _dismiss_perm_dialog()
    m = find_node(ui(), content_desc="Open menu")
    if m is None or not tap_node(m):
        return False
    settle("launch")
    return True


def and_reach_settings():
    """drawer → Settings, PROVING the jump (the Settings menu's 'Data Management'
    row appears and the drawer's 'Close navigation menu' handle leaves)."""
    if not _open_menu():
        return False
    node = find_node(ui(), content_desc="Settings")
    if node is None:
        return False
    return and_reach_surface(node, "Data Management", "Close navigation menu")


def and_enter_settings_sub(sub_cd, title):
    """From the Settings menu, tap a sub-row and confirm its screen (its TopBar
    title) is showing. Counts one surface."""
    node = find_node(ui(), content_desc=sub_cd) or find_node_ci(ui(), sub_cd)
    if node is None or not tap_node(node):
        return False
    settle("launch")
    ok = find_node_ci(ui(), title) is not None
    if ok:
        and_enter(sub_cd)
    return ok


def and_reach_general():
    """drawer → Settings → General (depth 2). True once the General screen is up
    (Dynamic-colors row present)."""
    if not and_reach_settings():
        return False
    if not and_enter_settings_sub("General", "General"):
        return False
    return find_node(ui(), content_desc="Dynamic colors") is not None


def and_reach_chart_settings():
    """drawer → Settings → Chart (depth 2). True once the Chart screen is up
    (Show-data-points row present)."""
    if not and_reach_settings():
        return False
    if not and_enter_settings_sub("Chart", "Chart"):
        return False
    return find_node_ci(ui(), "Show data points") is not None


def and_reach_measurement_types():
    """drawer → Settings → Measurement Types (depth 2). True once the list is up."""
    if not and_reach_settings():
        return False
    return and_enter_settings_sub("Measurement Types", "Measurement Types")


def and_enter_edit_type():
    """From the Measurement Types list, open the first row's Edit form
    ('Edit Type' title). Counts one surface (→ depth 3 in the pinned test)."""
    edit = find_node(ui(), content_desc="Edit")
    if edit is None or not tap_node(edit):
        return False
    settle("launch")
    ok = find_node_ci(ui(), "Edit Type") is not None
    if ok:
        and_enter("edit_type")
    return ok


def and_reach_table():
    """drawer → Table, PROVING the jump (the 'Select items' action appears and the
    drawer handle leaves)."""
    if not _open_menu():
        return False
    node = find_node(ui(), content_desc="Table")
    if node is None:
        return False
    return and_reach_surface(node, "Select items", "Close navigation menu")


def and_reach_overview():
    """drawer → Overview, PROVING the jump (the 'Add new measurement' toolbar
    action appears and the drawer handle leaves). Used to LEAVE a settings
    sub-screen for the persistence probes."""
    if not _open_menu():
        return False
    node = find_node(ui(), content_desc="Overview")
    if node is None:
        return False
    return and_reach_surface(node, "Add new measurement", "Close navigation menu")


def and_reach_charts():
    """drawer → Charts, PROVING the jump. `before` is snapshotted on the SOURCE
    screen BEFORE the drawer opens (so the drawer's own 'Charts' menu item is not
    already in `before` and the Charts TITLE genuinely APPEARS). The Charts and
    Overview toolbars share the Bluetooth action, so no source key is asserted."""
    before = and_showing()                 # source screen, no 'Charts' title
    if not _open_menu():
        return False
    node = find_node(ui(), content_desc="Charts")
    if node is None or not tap_node(node):
        return False
    settle("launch")
    after = and_showing()
    ok = and_reach(before, after, "Charts")
    if ok:
        and_enter("charts")
    return ok


def _leave_general_to_overview():
    """Leave the General SUB-screen (which has a Back arrow, NOT a hamburger) for
    the Overview: Back → Settings menu → Back → Overview. Uses and_back() so the
    depth counter pops the two surfaces it crossed. True on the Overview."""
    if find_node(ui(), content_desc="Data Management") is None:
        and_back()                          # General -> Settings menu
        settle("launch")
    if find_node(ui(), content_desc="Add new measurement") is None:
        and_back()                          # Settings menu -> Overview
        settle("launch")
    return find_node(ui(), content_desc="Add new measurement") is not None


# ══════════════════════════════════════════════════════════════════════════════
# Data fixture: a clean user + one 80 kg measurement, left on the Overview. The
# Table state-machine and chart tests need a real data row; a test that needs
# data MUST create it itself (recon §First-run). clear_data() also clears any
# granted/denied permission and dismisses a stray dialog.
# ══════════════════════════════════════════════════════════════════════════════

def _set_dialog_value(val):
    """PROVEN recipe: a NumberInputDialog must be open. Clear → tap → type ONE
    char at a time (type_text drops the 2nd digit here). Returns the field text."""
    c = find_node_ci(ui(), "Clear")
    if c:
        tap_node(c)
        settle("keyboard")
    ets = find_by_class(ui(), "EditText")
    if not ets:
        return ""
    tap_node(ets[0])
    settle("keyboard")
    settle("keyboard")
    for ch in str(val):
        adb_shell("input", "text", ch)   # kit injects the serial
        settle("text")
    settle("text")
    ets = find_by_class(ui(), "EditText")
    return ets[0].get("text", "") if ets else ""


def _create_user_with_weight(weight="80", height="180", name="StateUser"):
    """clear_data → user (Name+Height, top-right Save) → New Measurement → Weight
    → OK → Save measurement. Returns True once the Overview shows '<weight> kg'."""
    clear_data()
    launch_app()
    wait_for_foreground()
    settle("launch")
    _dismiss_perm_dialog()
    add = find_node_ci(ui(), "Add User")
    if add is None or not tap_node(add):
        return False
    settle("launch")
    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")
    # top-right Save Button (disk icon, no cd) — x>800, y<280
    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
            and n.get("_bounds", (0, 0, 0, 0))[1] < 280]
    if not btns or not tap_node(btns[0]):
        return False
    settle("launch")
    trig = (find_node_ci(ui(), "Add Measurement")
            or find_node(ui(), content_desc="Add new measurement"))
    if trig is None or not tap_node(trig):
        return False
    settle("launch")
    ew = find_node(ui(), content_desc="Edit Weight")
    if ew is None or not tap_node(ew):
        return False
    settle("tap")
    got = _set_dialog_value(weight)
    if got != str(weight):
        return False
    ok = find_node_ci(ui(), "OK")
    if ok:
        tap_node(ok)
        settle("tap")
    sm = find_node(ui(), content_desc="Save measurement")
    if sm:
        tap_node(sm)
        settle("launch")
    return find_node_ci(ui(), f"{weight} kg") is not None


def _enable_first_table_column(nodes):
    """On the Table, tap the first metric-filter icon (Weight) so a data column —
    and therefore a data row — appears. No-op if columns already on."""
    if find_node_ci(nodes, "No columns selected for display.") is None:
        return True
    icons = [n for n in nodes
             if n.get("content-desc", "").isdigit()
             and n.get("_bounds", (0, 0, 0, 0))[1] < 500]
    if not icons or not tap_node(icons[0]):
        return False
    settle("launch")
    return find_node_ci(ui(), "No columns selected for display.") is None


def _first_data_row(nodes):
    """The single measurement row in the Table (its text starts with the month)."""
    for n in nodes:
        if n.get("text", "").strip().startswith("Aug") \
                and n.get("_bounds", (0, 0, 0, 0))[1] > 550:
            return n
    return None


# ── shared setup that leaves the app ON the target settings screen ─────────────

def _fresh_general():
    """clean launch → drawer → Settings → General. True on the General screen."""
    if not _clean_launch():
        return False
    return and_reach_general()


def _fresh_chart_settings():
    if not _clean_launch():
        return False
    return and_reach_chart_settings()


def _ensure_off(label):
    """Make `label` start from checked=false (flip it off if it is on), so a
    subsequent flip is a deterministic false→true. Assumes the toggle is on
    screen. Returns the (now-off) state string."""
    sw = _checkable_on_row(ui(), label)
    if sw is not None and sw.get("checked") == "true":
        tap_node(_row_trigger(ui(), label))
        settle("tap")
        _dismiss_perm_dialog()
    return _read_checked(label)


# ══════════════════════════════════════════════════════════════════════════════
# 1–4. Settings → General toggles that flip cleanly (depth 2). Each is a real
#      checked false→true transition; the discriminating assertion is the
#      before→after `checked` change on the app's own checkable View, and that we
#      stayed on General. (Reminder is handled specially below — it pops a
#      permission dialog.)
# ══════════════════════════════════════════════════════════════════════════════

def _general_toggle_case(name, label, expect_after="checked=true"):
    if not _fresh_general():
        record(name, False,
               "setup_failed: could not reach Settings -> General",
               depth=2, jump_kind="transition", expect=expect_after)
        return
    _ensure_off(label)                       # deterministic start = OFF
    sw = _checkable_on_row(ui(), label)
    if sw is None:
        record(name, False,
               f"feature_missing: no '{label}' toggle on General",
               depth=2, jump_kind="transition", expect=expect_after)
        return
    before = sw.get("checked")
    tap_node(_row_trigger(ui(), label))
    settle("tap")
    after = _read_checked(label)
    still_general = find_node(ui(), content_desc="Dynamic colors") is not None
    good = (before == "false" and after == "true" and still_general)
    record(name, good,
           "" if good else
           (f"behavior_wrong: '{label}' checked {before}->{after} "
            f"(expected false->true, staying on General)"),
           depth=2, jump_kind="transition", expect=expect_after)
    # restore OFF so persisted theme/settings never bleed into a later test
    _ensure_off(label)


@_register
@and_test(expects=("states_general_dynamic_colors",))
def test_general_dynamic_colors():
    _general_toggle_case("states_general_dynamic_colors", "Dynamic colors")


@_register
@and_test(expects=("states_general_high_contrast",))
def test_general_high_contrast():
    _general_toggle_case("states_general_high_contrast", "High contrast")


@_register
@and_test(expects=("states_general_vibration",))
def test_general_vibration():
    _general_toggle_case("states_general_vibration",
                         "Vibration on new measurement")


@_register
@and_test(expects=("states_general_file_logging",))
def test_general_file_logging():
    """Enabling File Logging is CONDITIONAL: openScale gates it behind an in-app
    'Enable File Logging?' confirmation dialog (a real app-authored gate a bare
    framework Switch would not have). Assert OFF -> confirmation dialog appears
    -> tap 'Enable' -> checked becomes true."""
    name = "states_general_file_logging"
    if not _fresh_general():
        record(name, False,
               "setup_failed: could not reach Settings -> General",
               depth=2, jump_kind="transition",
               expect="file-logging flip -> confirm dialog -> checked=true")
        return
    _ensure_off("File Logging")
    sw = _checkable_on_row(ui(), "File Logging")
    if sw is None:
        record(name, False,
               "feature_missing: no 'File Logging' toggle on General",
               depth=2, jump_kind="transition",
               expect="file-logging flip -> confirm dialog -> checked=true")
        return
    before = sw.get("checked")
    tap_node(_row_trigger(ui(), "File Logging"))
    settle("tap")
    dialog = find_node_ci(ui(), "Enable File Logging?") is not None
    after = None
    if dialog:
        en = find_node_ci(ui(), "Enable")
        if en is not None:
            tap_node(en)
            settle("tap")
            after = _read_checked("File Logging")
    good = (before == "false" and dialog and after == "true")
    record(name, good,
           "" if good else
           (f"behavior_wrong: File Logging from {before}: confirm dialog={dialog}, "
            f"checked after Enable={after} (expected dialog then checked=true)"),
           depth=2, jump_kind="transition",
           expect="file-logging flip -> confirm dialog -> checked=true")


# ══════════════════════════════════════════════════════════════════════════════
# 5. Reminder function: flipping it ON is CONDITIONAL — it requests the OS
#    notification permission. The app-authored CONSEQUENCE of enabling the
#    reminder is exactly that permission dialog appearing; assert the transition
#    (row tapped from OFF) PLUS the dialog, then dismiss it non-destructively.
# ══════════════════════════════════════════════════════════════════════════════

@_register
@and_test(expects=("states_general_reminder",))
def test_general_reminder():
    name = "states_general_reminder"
    if not _fresh_general():
        record(name, False,
               "setup_failed: could not reach Settings -> General",
               depth=2, jump_kind="transition",
               expect="reminder flip -> notification-permission dialog")
        return
    _ensure_off("Reminder function")
    sw = _checkable_on_row(ui(), "Reminder function")
    if sw is None:
        record(name, False,
               "feature_missing: no 'Reminder function' toggle on General",
               depth=2, jump_kind="transition",
               expect="reminder flip -> notification-permission dialog")
        return
    before = sw.get("checked")
    tap_node(_row_trigger(ui(), "Reminder function"))
    settle("tap")
    # Consequence: either the OS permission dialog appears, OR (if already
    # granted) the toggle simply becomes checked. Accept either as the ON effect.
    dialog = _perm_dialog_showing()
    after = None if dialog else _read_checked("Reminder function")
    good = (before == "false") and (dialog or after == "true")
    record(name, good,
           "" if good else
           (f"behavior_wrong: 'Reminder function' from {before} produced neither "
            f"the notification-permission dialog nor checked=true"),
           depth=2, jump_kind="transition",
           expect="reminder flip -> notification-permission dialog")
    _dismiss_perm_dialog()                    # never leave it up for the next test


# ══════════════════════════════════════════════════════════════════════════════
# 6–8. Settings → Chart toggles (depth 2). "Show data points" defaults ON, the
#      others OFF — assert each FLIPS from its observed default.
# ══════════════════════════════════════════════════════════════════════════════

def _chart_toggle_case(name, label):
    if not _fresh_chart_settings():
        record(name, False,
               "setup_failed: could not reach Settings -> Chart",
               depth=2, jump_kind="transition", expect="checked flips")
        return
    sw = _checkable_on_row(ui(), label)
    if sw is None:
        record(name, False,
               f"feature_missing: no '{label}' toggle on Chart settings",
               depth=2, jump_kind="transition", expect="checked flips")
        return
    before = sw.get("checked")
    tap_node(_row_trigger(ui(), label))
    settle("tap")
    after = _read_checked(label)
    still_chart = find_node_ci(ui(), "Show data points") is not None
    good = (after is not None and before is not None
            and after != before and still_chart)
    expected = f"checked={'false' if before == 'true' else 'true'}"
    record(name, good,
           "" if good else
           (f"behavior_wrong: '{label}' checked {before}->{after} "
            f"(expected a flip, staying on Chart)"),
           depth=2, jump_kind="transition", expect=expected)


@_register
@and_test(expects=("states_chart_show_data_points",))
def test_chart_show_data_points():
    _chart_toggle_case("states_chart_show_data_points", "Show data points")


@_register
@and_test(expects=("states_chart_show_goal_lines",))
def test_chart_show_goal_lines():
    _chart_toggle_case("states_chart_show_goal_lines", "Show goal lines")


@_register
@and_test(expects=("states_chart_show_projection",))
def test_chart_show_projection():
    _chart_toggle_case("states_chart_show_projection", "Show projection")


# ══════════════════════════════════════════════════════════════════════════════
# 9. Measurement Types → Edit Type → "Pinned" checkable flip (depth 3).
#    The list-level cd="Pinned" is only a STATUS icon; the real toggle lives in
#    the per-type Edit form. This is the deepest state change in the lane.
# ══════════════════════════════════════════════════════════════════════════════

@_register
@and_test(expects=("states_type_pinned_toggle", "states_type_pinned_toggle_vlm"))
def test_type_pinned_toggle():
    name = "states_type_pinned_toggle"
    q = ("Is there an on/off toggle switch (a rounded pill-shaped control with a "
         "circular thumb) on the same row as the label 'Pinned' on this form?")
    if not _clean_launch() or not and_reach_measurement_types() \
            or not and_enter_edit_type():
        record(name, False,
               "setup_failed: could not reach Measurement Types -> Edit Type",
               depth=3, jump_kind="transition", expect="Pinned checked flips")
        vlm_assert(name, q, RESULTS_DIR, depth=3, jump_kind="transition",
                   tag="shape")
        return
    sw = _checkable_on_row(ui(), "Pinned")
    if sw is None:
        record(name, False,
               "feature_missing: no 'Pinned' toggle on the Edit Type form",
               depth=3, jump_kind="transition", expect="Pinned checked flips")
        vlm_assert(name, q, RESULTS_DIR, depth=3, jump_kind="transition",
                   tag="shape")
        return
    before = sw.get("checked")
    tap_node(sw)
    settle("tap")
    after = _read_checked("Pinned")
    still_edit = find_node_ci(ui(), "Edit Type") is not None
    good = (after is not None and before is not None
            and after != before and still_edit)
    expected = f"checked={'false' if before == 'true' else 'true'}"
    record(name, good,
           "" if good else
           (f"behavior_wrong: 'Pinned' checked {before}->{after} "
            f"(expected a flip, staying on Edit Type)"),
           depth=3, jump_kind="transition", expect=expected)
    # VLM: the toggle is a rendered affordance the tree only exposes as a bool.
    vlm_assert(name, q, RESULTS_DIR, depth=3, jump_kind="transition", tag="shape")


# ══════════════════════════════════════════════════════════════════════════════
# 10. Table selection COUNT state machine: 0 selected -> 1 selected (depth 2).
#     The count text is the state; the row-highlight COLOUR is the VLM below.
# ══════════════════════════════════════════════════════════════════════════════

@_register
@and_test(expects=("states_table_selection_count",
                   "states_table_unselected_vlm",
                   "states_table_row_highlight_vlm",
                   "states_table_checkbox_checked_vlm"))
def test_table_selection_count():
    name = "states_table_selection_count"

    def _bail(msg):
        record(name, False, msg, depth=2, jump_kind="transition",
               expect="0 selected -> 1 selected")
        vlm_assert("states_table_unselected", msg, RESULTS_DIR, expect="SKIP",
                   depth=2, jump_kind="transition", tag="shape")
        vlm_assert("states_table_row_highlight", msg, RESULTS_DIR, expect="SKIP",
                   depth=2, jump_kind="transition", tag="color")
        vlm_assert("states_table_checkbox_checked", msg, RESULTS_DIR,
                   expect="SKIP", depth=2, jump_kind="transition", tag="shape")

    if not _create_user_with_weight("80"):
        _bail("setup_failed: could not create user + 80 kg measurement")
        return
    if not and_reach_table():
        _bail("setup_failed: could not reach Table")
        return
    if not _enable_first_table_column(ui()):
        _bail("setup_failed: could not enable a Table column (no data row)")
        return
    si = find_node(ui(), content_desc="Select items")
    if si is None or not tap_node(si):
        _bail("setup_failed: 'Select items' action not tappable")
        return
    settle("launch")
    before_showing = find_node_ci(ui(), "0 selected") is not None
    # VLM (unselected baseline): empty checkbox on the row.
    vlm_assert("states_table_unselected",
               "On this table in selection mode, is the checkbox on the data "
               "row an EMPTY (unchecked) square outline?",
               RESULTS_DIR, depth=2, jump_kind="transition", tag="shape")
    row = _first_data_row(ui())
    if row is None or not tap_node(row):
        record(name, False,
               "setup_failed: no data row to select in selection mode",
               depth=2, jump_kind="transition", expect="0 selected -> 1 selected")
        vlm_assert("states_table_row_highlight", "setup_failed: no data row",
                   RESULTS_DIR, expect="SKIP", depth=2, jump_kind="transition",
                   tag="color")
        vlm_assert("states_table_checkbox_checked", "setup_failed: no data row",
                   RESULTS_DIR, expect="SKIP", depth=2, jump_kind="transition",
                   tag="shape")
        return
    settle("tap")
    after_nodes = ui()
    after_showing = find_node_ci(after_nodes, "1 selected") is not None
    zero_gone = find_node_ci(after_nodes, "0 selected") is None
    good = before_showing and after_showing and zero_gone
    record(name, good,
           "" if good else
           (f"behavior_wrong: count did not advance 0->1 "
            f"(0 shown before={before_showing}, 1 shown after={after_showing})"),
           depth=2, jump_kind="transition", expect="1 selected")
    # VLM: the selected row's highlight tint + its filled checkmark checkbox.
    vlm_assert("states_table_row_highlight",
               "Is the selected data row (the one with a checked checkbox) shown "
               "with a light BLUE background tint, distinct from the plain white "
               "header area above it?",
               RESULTS_DIR, depth=2, jump_kind="transition", tag="color")
    vlm_assert("states_table_checkbox_checked",
               "Is the checkbox on the selected row a FILLED teal/blue square "
               "containing a white checkmark (not an empty outline)?",
               RESULTS_DIR, depth=2, jump_kind="transition", tag="shape")


# ══════════════════════════════════════════════════════════════════════════════
# 11–12. SETTINGS PERSISTENCE (this lane owns it): flip a toggle ON, LEAVE the
#        General screen (drawer → Overview), RETURN (drawer → Settings → General),
#        assert the checked value survived. depth>=2, reached via the depth family.
# ══════════════════════════════════════════════════════════════════════════════

def _persistence_case(name, label):
    if not _fresh_general():
        record(name, False,
               "setup_failed: could not reach Settings -> General",
               depth=2, jump_kind="transition", expect="checked=true persists")
        return
    _ensure_off(label)                       # start OFF
    sw = _checkable_on_row(ui(), label)
    if sw is None:
        record(name, False, f"feature_missing: no '{label}' toggle",
               depth=2, jump_kind="transition", expect="checked=true persists")
        return
    tap_node(_row_trigger(ui(), label))      # flip ON
    settle("tap")
    _dismiss_perm_dialog()
    if _read_checked(label) != "true":
        record(name, False,
               f"behavior_wrong: '{label}' did not turn on before the leave/return",
               depth=2, jump_kind="transition", expect="checked=true persists")
        _ensure_off(label)
        return
    # LEAVE General for the Overview (Back x2 — a sub-screen has a Back arrow,
    # not a hamburger), then RETURN to General.
    if not _leave_general_to_overview():
        record(name, False,
               "setup_failed: could not leave General to the Overview",
               depth=2, jump_kind="transition", expect="checked=true persists")
        return
    if not and_reach_general():
        record(name, False,
               "setup_failed: could not return to Settings -> General",
               depth=2, jump_kind="transition", expect="checked=true persists")
        return
    persisted = _read_checked(label)
    good = persisted == "true"
    record(name, good,
           "" if good else
           (f"behavior_wrong: '{label}' was {persisted} after leaving and "
            f"returning (expected it to persist as true)"),
           depth=2, jump_kind="transition", expect="checked=true persists")
    _ensure_off(label)                        # restore OFF


@_register
@and_test(expects=("states_high_contrast_persists",))
def test_high_contrast_persists():
    _persistence_case("states_high_contrast_persists", "High contrast")


@_register
@and_test(expects=("states_dynamic_colors_persists",))
def test_dynamic_colors_persists():
    _persistence_case("states_dynamic_colors_persists", "Dynamic colors")


# ══════════════════════════════════════════════════════════════════════════════
# VLM lane (budget = 11). Theme / highlight / switch colour + position are
# genuinely unreadable from the view tree. Each question is written from a
# screenshot actually captured on the original; ≥2/3 are fine-grained
# (color/shape/position/size).
#
# Emitted inside rule tests above (4 records):
#   states_type_pinned_toggle_vlm       (shape)
#   states_table_unselected_vlm         (shape)
#   states_table_row_highlight_vlm      (color)
#   states_table_checkbox_checked_vlm   (shape)
# The seven below bring the total to 11.
# ══════════════════════════════════════════════════════════════════════════════

@_register
@and_test(expects=("states_general_all_off_vlm",))
def test_general_all_off_vlm():
    """General with the appearance toggles OFF: thumbs LEFT, pale/gray tracks."""
    name = "states_general_all_off"
    if not _fresh_general():
        record(name + "_vlm", False, "setup_failed: could not reach General",
               depth=2, jump_kind="transition", expect="both toggles OFF-left",
               tag="position")
        return
    _ensure_off("Dynamic colors")
    _ensure_off("High contrast")
    vlm_assert(name,
               "On this settings screen, are the 'Dynamic colors' and 'High "
               "contrast' toggle switches BOTH in the OFF position, i.e. the "
               "round thumb sits on the LEFT side of a pale/gray track?",
               RESULTS_DIR, depth=2, jump_kind="transition", tag="position")


@_register
@and_test(expects=("states_high_contrast_on_pos_vlm",))
def test_high_contrast_on_pos_vlm():
    """High contrast ON: its thumb moves RIGHT; Dynamic colors above stays LEFT."""
    name = "states_high_contrast_on_pos"
    if not _fresh_general():
        record(name + "_vlm", False, "setup_failed: could not reach General",
               depth=2, jump_kind="transition", expect="HC thumb right",
               tag="position")
        return
    _ensure_off("Dynamic colors")
    _ensure_off("High contrast")
    tap_node(_row_trigger(ui(), "High contrast"))
    settle("tap")
    vlm_assert(name,
               "The 'High contrast' toggle is ON and 'Dynamic colors' is OFF. Is "
               "the 'High contrast' switch thumb on the RIGHT side of its track "
               "while the 'Dynamic colors' switch thumb (just above it) is on the "
               "LEFT?",
               RESULTS_DIR, depth=2, jump_kind="transition", tag="position")
    _ensure_off("High contrast")


@_register
@and_test(expects=("states_high_contrast_on_color_vlm",))
def test_high_contrast_on_color_vlm():
    """High contrast ON: the enabled switch track is a very dark near-black/navy."""
    name = "states_high_contrast_on_color"
    if not _fresh_general():
        record(name + "_vlm", False, "setup_failed: could not reach General",
               depth=2, jump_kind="transition", expect="HC track dark",
               tag="color")
        return
    _ensure_off("High contrast")
    tap_node(_row_trigger(ui(), "High contrast"))
    settle("tap")
    vlm_assert(name,
               "Look at the 'High contrast' toggle, now ON. Is its track a very "
               "DARK colour (near-black or dark navy) with a light/white thumb?",
               RESULTS_DIR, depth=2, jump_kind="transition", tag="color")
    _ensure_off("High contrast")


@_register
@and_test(expects=("states_dynamic_colors_on_pos_vlm",))
def test_dynamic_colors_on_pos_vlm():
    """Dynamic colors ON: its thumb moves RIGHT."""
    name = "states_dynamic_colors_on_pos"
    if not _fresh_general():
        record(name + "_vlm", False, "setup_failed: could not reach General",
               depth=2, jump_kind="transition", expect="Dyn thumb right",
               tag="position")
        return
    _ensure_off("Dynamic colors")
    tap_node(_row_trigger(ui(), "Dynamic colors"))
    settle("tap")
    vlm_assert(name,
               "The 'Dynamic colors' toggle is now ON. Is its round switch thumb "
               "on the RIGHT side of the track (the ON position)?",
               RESULTS_DIR, depth=2, jump_kind="transition", tag="position")
    _ensure_off("Dynamic colors")


@_register
@and_test(expects=("states_dynamic_colors_on_color_vlm",))
def test_dynamic_colors_on_color_vlm():
    """Dynamic colors ON: the enabled switch track is a saturated blue/navy."""
    name = "states_dynamic_colors_on_color"
    if not _fresh_general():
        record(name + "_vlm", False, "setup_failed: could not reach General",
               depth=2, jump_kind="transition", expect="Dyn track blue",
               tag="color")
        return
    _ensure_off("Dynamic colors")
    tap_node(_row_trigger(ui(), "Dynamic colors"))
    settle("tap")
    vlm_assert(name,
               "Look at the 'Dynamic colors' toggle, now ON. Is its track a "
               "solid BLUE / dark-blue colour (clearly not gray)?",
               RESULTS_DIR, depth=2, jump_kind="transition", tag="color")
    _ensure_off("Dynamic colors")


@_register
@and_test(expects=("states_vibration_on_pos_vlm",))
def test_vibration_on_pos_vlm():
    """Vibration ON: its thumb moves RIGHT (a rendered affordance for the bool)."""
    name = "states_vibration_on_pos"
    if not _fresh_general():
        record(name + "_vlm", False, "setup_failed: could not reach General",
               depth=2, jump_kind="transition", expect="Vib thumb right",
               tag="position")
        return
    _ensure_off("Vibration on new measurement")
    tap_node(_row_trigger(ui(), "Vibration on new measurement"))
    settle("tap")
    vlm_assert(name,
               "The 'Vibration on new measurement' toggle is now ON. Is its round "
               "switch thumb on the RIGHT side of the track?",
               RESULTS_DIR, depth=2, jump_kind="transition", tag="position")
    _ensure_off("Vibration on new measurement")


@_register
@and_test(expects=("states_chart_data_point_vlm",))
def test_chart_data_point_vlm():
    """With 'Show data points' ON (default) and one entry, the Charts line graph
    plots a single small circular point marker — a canvas-only rendered state."""
    name = "states_chart_data_point"
    if not _create_user_with_weight("80"):
        record(name + "_vlm", False,
               "setup_failed: could not create a measurement to chart",
               depth=2, jump_kind="transition", expect="a point marker on line",
               tag="shape")
        return
    if not and_reach_charts():
        record(name + "_vlm", False, "setup_failed: could not reach Charts",
               depth=2, jump_kind="transition", expect="a point marker on line",
               tag="shape")
        return
    vlm_assert(name,
               "On this line chart, is there at least one small filled CIRCULAR "
               "data-point marker plotted on the graph line?",
               RESULTS_DIR, depth=2, jump_kind="transition", tag="shape")


# ══════════════════════════════════════════════════════════════════════════════
if __name__ == "__main__":
    run_suite(TESTS, "states")