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

This app has NO list-of-records CRUD. Its persisted "data" is:
  * the per-table HIGH SCORE list + LAST SCORE (created by playing then ending a game),
  * the selected TABLE (initialLevel), and
  * the LINE WIDTH preference value.
So this lane exercises MULTI-STEP SEQUENCES, MULTI-RECORD INTEGRITY of the high-score
list, and DATA PERSISTENCE ACROSS PROCESS DEATH. Gameplay content (score number, ball,
field layout) is canvas-rendered and never reaches the view tree, so those consequences
are VLM-observed; every menu/dialog/panel consequence is rule-observed from the tree.

Package under test is argv[1]; never a literal here.
"""
import os
import re
import sys
import time

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

# ── Regexes for canvas-formatted scores read out of the tree TextViews ──────────
NUM_RE = re.compile(r"[0-9][0-9,]*")        # any comma/digit run, e.g. "4,800"
PURE_NUM_RE = re.compile(r"^[0-9][0-9,]*$")  # a bare score row (not "Last Score: n")


# ══════════════════════════════════════════════════════════════════════════════
# Shared helpers. The and_enter_*/and_play_* names are what BACK a declared depth.
# ══════════════════════════════════════════════════════════════════════════════

def _field_taps(n_rounds=5):
    """Launch the ball and pump the flippers by tapping the canvas playfield.

    The field has NO tree nodes, so we tap positions derived from the real screen
    size (never a pixel literal): a launch point in the upper-mid field, then the
    two lower corners where the flippers live. Any field tap launches the ball and
    activates bumpers, so this reliably drives the score above zero.
    """
    s = get_screen_info()
    w, h = s["width"], s["height"]
    launch = (int(w * 0.50), int(h * 0.30))
    flip_l = (int(w * 0.20), int(h * 0.88))
    flip_r = (int(w * 0.80), int(h * 0.88))
    for _ in range(n_rounds):
        tap(*launch); time.sleep(0.3)
        tap(*flip_l); time.sleep(0.2)
        tap(*flip_r); time.sleep(0.3)


def and_play_and_end_game(unlimited=False):
    """Start a game from a fresh menu, generate score, then End Game.

    Crosses into gameplay (surface +1) and back to the menu. Returns the menu
    nodes after End Game, or None if any step could not be driven. When
    `unlimited` is set, the Unlimited Balls toggle is checked first — such games
    are excluded from high scores by the app.
    """
    restart_app()
    if not wait_for_foreground(10):
        return None
    n = ui()
    if unlimited:
        ub = node_by_id(n, "unlimitedBallsToggle")
        if ub is None or ub.get("checked") == "true" or not tap_node(ub):
            return None
        n = ui()
    sg = node_by_id(n, "startGameButton")
    if sg is None or not tap_node(sg):
        return None
    and_enter("gameplay")          # surface: menu -> gameplay
    time.sleep(2)
    _field_taps()
    time.sleep(2)
    n = ui()
    pi = node_by_id(n, "pauseIcon")
    if pi is None or not tap_node(pi):
        return None
    time.sleep(1.2)
    n = ui()
    eg = node_by_id(n, "endGameButton")
    if eg is None or not tap_node(eg):
        return None
    time.sleep(1.5)
    return ui()


def and_reach_high_scores():
    """From the main menu, open the High Scores panel (panel swap, surface +1).

    Proves the jump via node_key strings: the highScorePanel appears and the
    START GAME button (whose node_key is text-based, "Button|START GAME")
    vanishes. Returns the high-score panel nodes, or None on failure.
    """
    n = ui()
    hs = node_by_id(n, "highScoreButton")
    if hs is None:
        return None
    if not and_reach_surface(hs, target="highScorePanel", source="START GAME"):
        return None
    return ui()


def and_enter_preferences():
    """Tap PREFERENCES -> the preferences activity (surface +1). Returns nodes."""
    n = ui()
    pb = node_by_id(n, "preferencesButton")
    if pb is None or not tap_node(pb):
        return None
    and_enter("preferences")
    time.sleep(1.2)
    return ui()


def and_enter_line_width_dialog():
    """From the preferences list, open the Line width EditText dialog (surface +1).

    Returns the sole EditText node, or None. Assumes and_enter_preferences() was
    already called.
    """
    lw = scroll_into_view("Line width")
    if lw is None or not tap_node(lw):
        return None
    and_enter("line_width_dialog")
    time.sleep(1.0)
    ets = find_by_class(ui(), "EditText")
    return ets[0] if ets else None


def _set_line_width(value):
    """In an open Line width dialog, clear the field, type `value`, tap OK.

    Clears via end-of-field + backspaces (the field may hold a prior value), then
    routes the digits through the kit's focus-verified typing. Returns True iff OK
    was tapped.
    """
    ets = find_by_class(ui(), "EditText")
    if not ets:
        return False
    et = ets[0]
    if not tap_node(et):
        return False
    time.sleep(0.4)
    press_key(123)                     # MOVE_END
    for _ in range(6):
        press_key(67)                  # DEL (backspace)
    time.sleep(0.3)
    if not type_text(et, value):
        return False
    n = ui()
    ok = find_node(n, text="OK") or node_by_id(n, "button1")
    return bool(ok and tap_node(ok))


def _numeric_rows(nodes):
    """Bare numeric score rows in the high-score list (excludes 'Last Score:')."""
    return [x.get("text", "") for x in nodes
            if PURE_NUM_RE.match(x.get("text", "").strip())]


def _last_score_row(nodes):
    for x in nodes:
        t = x.get("text", "")
        if t.startswith("Last Score"):
            return t
    return ""


def _start_game_to_field():
    """Start a game and settle on the gameplay canvas. Returns gameplay nodes or
    None. Crosses one surface (menu -> gameplay)."""
    restart_app()
    if not wait_for_foreground(10):
        return None
    n = ui()
    sg = node_by_id(n, "startGameButton")
    if sg is None or not tap_node(sg):
        return None
    and_enter("gameplay")
    time.sleep(2)
    return ui()


# ══════════════════════════════════════════════════════════════════════════════
# 1. HIGH-SCORE CREATION  (flagship data-creation, 3+ steps, before->after flip)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_highscore_created",))
def test_highscore_created_by_playing():
    clear_data()
    # Prove the negative half first: a virgin table has no scores.
    restart_app()
    if not wait_for_foreground(10):
        record("interaction_highscore_created", False,
               "setup_failed: app did not reach foreground",
               depth=2, jump_kind="transition", expect="numeric high-score row appears")
        return
    n0 = and_reach_high_scores()
    absent_before = bool(n0) and node_by_id(n0, "noHighScoresTextView") is not None
    # Play a real game and end it.
    if and_play_and_end_game() is None:
        record("interaction_highscore_created", False,
               "setup_failed: could not play a game through to End Game",
               depth=2, jump_kind="transition", expect="numeric high-score row appears")
        return
    n = and_reach_high_scores()
    if n is None:
        record("interaction_highscore_created", False,
               "feature_missing: no High Scores panel to open",
               depth=2, jump_kind="transition", expect="numeric high-score row appears")
        return
    no_scores_gone = node_by_id(n, "noHighScoresTextView") is None
    has_number = any(PURE_NUM_RE.match(x.get("text", "").strip()) for x in n)
    has_last = _last_score_row(n) != ""
    ok = absent_before and no_scores_gone and has_number and has_last
    record("interaction_highscore_created", ok,
           "" if ok else ("behavior_wrong: high score not created after a game "
                          f"(absent_before={absent_before} no_scores_gone={no_scores_gone} "
                          f"num={has_number} last={has_last})"),
           depth=2, jump_kind="transition",
           expect="noHighScores absent->gone + a numeric row + 'Last Score:' present")


# ══════════════════════════════════════════════════════════════════════════════
# 2. HIGH SCORE SURVIVES PROCESS DEATH  (sole-owner data-survival)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_highscore_persists_kill",))
def test_highscore_survives_process_death():
    clear_data()
    if and_play_and_end_game() is None:
        record("interaction_highscore_persists_kill", False,
               "setup_failed: could not play a game to seed a high score",
               depth=2, jump_kind="transition",
               expect="numeric high-score row still present after process kill")
        return
    # Confirm it landed, then KILL the process and relaunch.
    n = and_reach_high_scores()
    seeded = bool(n) and node_by_id(n, "noHighScoresTextView") is None \
        and any(PURE_NUM_RE.match(x.get("text", "").strip()) for x in n)
    force_stop_and_relaunch()
    if not wait_for_foreground(10):
        record("interaction_highscore_persists_kill", False,
               "setup_failed: app did not relaunch after force-stop",
               depth=2, jump_kind="transition",
               expect="numeric high-score row still present after process kill")
        return
    n = and_reach_high_scores()
    if n is None:
        record("interaction_highscore_persists_kill", False,
               "feature_missing: High Scores panel unreachable after relaunch",
               depth=2, jump_kind="transition",
               expect="numeric high-score row still present after process kill")
        return
    survived = node_by_id(n, "noHighScoresTextView") is None \
        and any(PURE_NUM_RE.match(x.get("text", "").strip()) for x in n) \
        and _last_score_row(n) != ""
    ok = seeded and survived
    record("interaction_highscore_persists_kill", ok,
           "" if ok else "behavior_wrong: high score did not survive process death",
           depth=2, jump_kind="transition",
           expect="numeric high-score row + 'Last Score:' after force-stop+relaunch")


# ══════════════════════════════════════════════════════════════════════════════
# 3. FRESH INSTALL SHOWS NO SCORES  (integrity baseline — the negative anchor)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_fresh_no_scores",))
def test_fresh_install_no_scores():
    clear_data()
    restart_app()
    if not wait_for_foreground(10):
        record("interaction_fresh_no_scores", False,
               "setup_failed: app did not reach foreground",
               depth=1, jump_kind="value", expect="'No scores for this table'")
        return
    n = and_reach_high_scores()
    if n is None:
        record("interaction_fresh_no_scores", False,
               "feature_missing: no High Scores panel",
               depth=1, jump_kind="value", expect="'No scores for this table'")
        return
    nohs = node_by_id(n, "noHighScoresTextView")
    no_numbers = not any(PURE_NUM_RE.match(x.get("text", "").strip()) for x in n)
    ok = nohs is not None and nohs.get("text") == "No scores for this table" and no_numbers
    record("interaction_fresh_no_scores", ok,
           "" if ok else "behavior_wrong: fresh table did not show the empty-scores message",
           depth=1, jump_kind="value", expect="'No scores for this table', no numeric rows")


# ══════════════════════════════════════════════════════════════════════════════
# 4. MULTI-RECORD INTEGRITY  (add several games, list keeps them, sorted desc)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_multi_record_highscores",
                   "interaction_multi_record_sorted_vlm"))
def test_multi_record_highscore_list():
    clear_data()
    played = 0
    for _ in range(3):
        if and_play_and_end_game() is not None:
            played += 1
        and_reset_depth()          # each game re-enters from a fresh menu
    if played < 2:
        record("interaction_multi_record_highscores", False,
               f"setup_failed: only {played}/3 games completed",
               depth=2, jump_kind="value", expect=">=2 numeric rows, non-increasing")
        record("interaction_multi_record_sorted_vlm", False,
               "setup_failed: not enough games to populate the list",
               depth=2, jump_kind="value", tag="content")
        return
    n = and_reach_high_scores()
    if n is None:
        record("interaction_multi_record_highscores", False,
               "feature_missing: High Scores panel unreachable",
               depth=2, jump_kind="value", expect=">=2 numeric rows, non-increasing")
        record("interaction_multi_record_sorted_vlm", False,
               "setup_failed: High Scores panel unreachable",
               depth=2, jump_kind="value", tag="content")
        return
    rows = _numeric_rows(n)
    vals = [int(r.replace(",", "")) for r in rows]
    # >=2 distinct entries survive, AND the list is sorted high-to-low (integrity:
    # a recreation that keeps only the latest row, or that fails to sort, breaks here).
    enough = len(rows) >= 2
    sorted_desc = vals == sorted(vals, reverse=True)
    ok = enough and sorted_desc
    record("interaction_multi_record_highscores", ok,
           "" if ok else (f"behavior_wrong: high-score list not multi-record/sorted "
                          f"(rows={rows})"),
           depth=2, jump_kind="value",
           expect=f">=2 numeric rows sorted descending (observed {rows})")
    # VLM: the panel visibly lists multiple score rows.
    vlm_assert("interaction_multi_record_sorted",
               "In the 'High scores' dialog, are at least two separate numeric score "
               "values listed (one per line), not just a single score?",
               depth=2, jump_kind="value", tag="content")


# ══════════════════════════════════════════════════════════════════════════════
# 5. LAST SCORE REFLECTS THE MOST-RECENT GAME  (data consequence, not the max)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_last_score_updates",))
def test_last_score_is_present_and_numeric():
    clear_data()
    if and_play_and_end_game() is None:
        record("interaction_last_score_updates", False,
               "setup_failed: could not complete a game",
               depth=2, jump_kind="value", expect="'Last Score: <number>' row")
        return
    n = and_reach_high_scores()
    if n is None:
        record("interaction_last_score_updates", False,
               "feature_missing: High Scores panel unreachable",
               depth=2, jump_kind="value", expect="'Last Score: <number>' row")
        return
    last = _last_score_row(n)
    ok = last.startswith("Last Score") and NUM_RE.search(last) is not None
    record("interaction_last_score_updates", ok,
           "" if ok else f"behavior_wrong: no numeric 'Last Score:' row (got {last!r})",
           depth=2, jump_kind="value",
           expect=f"'Last Score:' + a formatted number (observed {last!r})")


# ══════════════════════════════════════════════════════════════════════════════
# 6. UNLIMITED-BALLS GAME PRODUCES NO HIGH SCORE  (integrity rule consequence)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_unlimited_no_highscore",))
def test_unlimited_balls_excluded_from_highscores():
    clear_data()
    if and_play_and_end_game(unlimited=True) is None:
        record("interaction_unlimited_no_highscore", False,
               "setup_failed: could not play an Unlimited-Balls game to End Game",
               depth=2, jump_kind="value", expect="'No scores for this table' still shown")
        return
    n = and_reach_high_scores()
    if n is None:
        record("interaction_unlimited_no_highscore", False,
               "feature_missing: High Scores panel unreachable",
               depth=2, jump_kind="value", expect="'No scores for this table' still shown")
        return
    nohs = node_by_id(n, "noHighScoresTextView")
    no_numbers = not any(PURE_NUM_RE.match(x.get("text", "").strip()) for x in n)
    # The app excludes unlimited-balls games from high scores: the table stays empty.
    ok = nohs is not None and no_numbers
    record("interaction_unlimited_no_highscore", ok,
           "" if ok else ("behavior_wrong: an Unlimited-Balls game was wrongly recorded "
                          "as a high score"),
           depth=2, jump_kind="value",
           expect="noHighScoresTextView present + no numeric rows after unlimited game")


# ══════════════════════════════════════════════════════════════════════════════
# 7. LINE-WIDTH VALUE ROUND-TRIP WITHIN A SESSION  (data value survives a reopen)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_linewidth_roundtrip",))
def test_linewidth_value_roundtrip():
    clear_data()
    restart_app()
    if not wait_for_foreground(10):
        record("interaction_linewidth_roundtrip", False,
               "setup_failed: app did not reach foreground",
               depth=2, jump_kind="value", expect="Line width EditText shows '5' on reopen")
        return
    if and_enter_preferences() is None:
        record("interaction_linewidth_roundtrip", False,
               "setup_failed: Preferences unreachable",
               depth=2, jump_kind="value", expect="Line width EditText shows '5' on reopen")
        return
    if and_enter_line_width_dialog() is None:
        record("interaction_linewidth_roundtrip", False,
               "feature_missing: no Line width dialog",
               depth=2, jump_kind="value", expect="Line width EditText shows '5' on reopen")
        return
    if not _set_line_width("5"):
        record("interaction_linewidth_roundtrip", False,
               "setup_failed: could not enter a line width value",
               depth=2, jump_kind="value", expect="Line width EditText shows '5' on reopen")
        return
    time.sleep(0.8)
    # Reopen the dialog (still inside Preferences) and read the value back.
    et = and_enter_line_width_dialog()
    got = et.get("text") if et else None
    ok = got == "5"
    record("interaction_linewidth_roundtrip", ok,
           "" if ok else f"behavior_wrong: line width did not round-trip (got {got!r})",
           depth=2, jump_kind="value", expect="Line width EditText == '5' on reopen")


# ══════════════════════════════════════════════════════════════════════════════
# 8. LINE-WIDTH VALUE SURVIVES PROCESS DEATH  (data-survival, sole owner)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_linewidth_persists_kill",))
def test_linewidth_survives_process_death():
    clear_data()
    restart_app()
    if not wait_for_foreground(10):
        record("interaction_linewidth_persists_kill", False,
               "setup_failed: app did not reach foreground",
               depth=2, jump_kind="value", expect="Line width EditText shows '7' after kill")
        return
    if and_enter_preferences() is None or and_enter_line_width_dialog() is None:
        record("interaction_linewidth_persists_kill", False,
               "setup_failed: Line width dialog unreachable",
               depth=2, jump_kind="value", expect="Line width EditText shows '7' after kill")
        return
    if not _set_line_width("7"):
        record("interaction_linewidth_persists_kill", False,
               "setup_failed: could not enter a line width value",
               depth=2, jump_kind="value", expect="Line width EditText shows '7' after kill")
        return
    time.sleep(0.8)
    # Leave preferences, then KILL the process and relaunch.
    back(); time.sleep(1.0)
    force_stop_and_relaunch()
    if not wait_for_foreground(10):
        record("interaction_linewidth_persists_kill", False,
               "setup_failed: app did not relaunch after force-stop",
               depth=2, jump_kind="value", expect="Line width EditText shows '7' after kill")
        return
    and_reset_depth()
    if and_enter_preferences() is None:
        record("interaction_linewidth_persists_kill", False,
               "setup_failed: Preferences unreachable after relaunch",
               depth=2, jump_kind="value", expect="Line width EditText shows '7' after kill")
        return
    et = and_enter_line_width_dialog()
    got = et.get("text") if et else None
    ok = got == "7"
    record("interaction_linewidth_persists_kill", ok,
           "" if ok else f"behavior_wrong: line width did not survive process death (got {got!r})",
           depth=2, jump_kind="value", expect="Line width EditText == '7' after force-stop+relaunch")


# ══════════════════════════════════════════════════════════════════════════════
# 9. TABLE SELECTION SURVIVES PROCESS DEATH  (data-survival; canvas -> VLM + tree)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_table_persists_menu",
                   "interaction_table2_persists_kill_vlm"))
def test_table_selection_survives_kill():
    clear_data()
    restart_app()
    if not wait_for_foreground(10):
        record("interaction_table_persists_menu", False,
               "setup_failed: app did not reach foreground",
               depth=0, jump_kind="transition", expect="menu present after kill")
        record("interaction_table2_persists_kill_vlm", False,
               "setup_failed: app did not reach foreground",
               depth=0, jump_kind="transition", tag="color")
        return
    n = ui()
    nxt = node_by_id(n, "nextTableButton")
    if nxt is None or not tap_node(nxt):
        record("interaction_table_persists_menu", False,
               "feature_missing: no next-table control",
               depth=0, jump_kind="transition", expect="menu present after kill")
        record("interaction_table2_persists_kill_vlm", False,
               "feature_missing: no next-table control",
               depth=0, jump_kind="transition", tag="color")
        return
    time.sleep(0.8)
    # KILL and relaunch — the selected table must be restored.
    force_stop_and_relaunch()
    ok_menu = wait_for_foreground(10)
    n = ui()
    ok_menu = ok_menu and node_by_id(n, "buttonPanel") is not None \
        and node_by_id(n, "startGameButton") is not None
    record("interaction_table_persists_menu", ok_menu,
           "" if ok_menu else "behavior_wrong: main menu not restored after process kill",
           depth=0, jump_kind="transition", expect="buttonPanel + startGameButton after relaunch")
    # VLM: the restored field is table 2 (yellow bumpers + a blue/red bumper cluster),
    # NOT the sparse table-1 layout (cyan/red rollovers down the left edge, white circle top-left).
    vlm_assert("interaction_table2_persists_kill",
               "Behind the menu panel, does the pinball field show a cluster of blue "
               "circular bumpers with one red bumper among them near the upper area "
               "(table 2 layout), rather than a mostly-empty field with small circles "
               "along the left edge?",
               depth=0, jump_kind="transition", tag="color")


# ══════════════════════════════════════════════════════════════════════════════
# 10. SWITCH TABLES THEN BACK TO TABLE 1  (multi-step, returns to original layout)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_table_cycle_back_vlm",))
def test_table_cycle_back_to_one():
    clear_data()
    restart_app()
    if not wait_for_foreground(10):
        record("interaction_table_cycle_back_vlm", False,
               "setup_failed: app did not reach foreground",
               depth=0, jump_kind="transition", tag="color")
        return
    n = ui()
    nxt = node_by_id(n, "nextTableButton")
    prv = node_by_id(n, "previousTableButton")
    if nxt is None or prv is None:
        record("interaction_table_cycle_back_vlm", False,
               "feature_missing: table cycle controls absent",
               depth=0, jump_kind="transition", tag="color")
        return
    # Forward twice, then back twice -> should land on table 1 again.
    for _ in range(2):
        tap_node(nxt); time.sleep(0.6)
        n = ui(); nxt = node_by_id(n, "nextTableButton")
    for _ in range(2):
        n = ui(); prv = node_by_id(n, "previousTableButton")
        tap_node(prv); time.sleep(0.6)
    vlm_assert("interaction_table_cycle_back",
               "Behind the menu panel, is the pinball field the mostly-empty table-1 "
               "layout with small cyan and red circular rollovers along the left edge "
               "and a white circle near the top-left, rather than a field full of large "
               "blue bumpers?",
               depth=0, jump_kind="transition", tag="color")


# ══════════════════════════════════════════════════════════════════════════════
# 11. START GAME USES THE SELECTED TABLE  (multi-step sequence: switch -> play)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_selected_table_in_play",
                   "interaction_selected_table_in_play_vlm"))
def test_selected_table_used_in_game():
    clear_data()
    restart_app()
    if not wait_for_foreground(10):
        record("interaction_selected_table_in_play", False,
               "setup_failed: app did not reach foreground",
               depth=1, jump_kind="transition", expect="pauseIcon present in gameplay")
        record("interaction_selected_table_in_play_vlm", False,
               "setup_failed: app did not reach foreground",
               depth=1, jump_kind="transition", tag="color")
        return
    n = ui()
    nxt = node_by_id(n, "nextTableButton")
    if nxt is None or not tap_node(nxt):        # switch to table 2
        record("interaction_selected_table_in_play", False,
               "feature_missing: no next-table control",
               depth=1, jump_kind="transition", expect="pauseIcon present in gameplay")
        record("interaction_selected_table_in_play_vlm", False,
               "feature_missing: no next-table control",
               depth=1, jump_kind="transition", tag="color")
        return
    time.sleep(0.8)
    n = ui()
    sg = node_by_id(n, "startGameButton")
    entered = bool(sg) and tap_node(sg)
    if entered:
        and_enter("gameplay")
        time.sleep(2)
    n = ui()
    # Tree consequence: gameplay state entered (pauseIcon appears, buttonPanel gone).
    ok = entered and node_by_id(n, "pauseIcon") is not None \
        and node_by_id(n, "buttonPanel") is None
    record("interaction_selected_table_in_play", ok,
           "" if ok else "behavior_wrong: Start Game did not enter gameplay after switching table",
           depth=1, jump_kind="transition", expect="pauseIcon present + buttonPanel gone")
    # VLM: the in-play field is the table-2 layout we selected.
    vlm_assert("interaction_selected_table_in_play",
               "This pinball game screen shows a field with a cluster of large blue "
               "bumpers and one red bumper in the upper half (table 2). Is that blue "
               "bumper cluster present?",
               depth=1, jump_kind="transition", tag="color")


# ══════════════════════════════════════════════════════════════════════════════
# 12. PLAYING THE BALL RAISES THE SCORE ABOVE ZERO  (input->consequence, canvas)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_score_zero_then_nonzero_vlm",))
def test_play_makes_score_nonzero():
    n = _start_game_to_field()
    if n is None:
        record("interaction_score_zero_then_nonzero_vlm", False,
               "setup_failed: could not enter gameplay",
               depth=1, jump_kind="value", tag="content")
        return
    # Generate score by tapping the canvas playfield, then ask the VLM.
    _field_taps(6)
    time.sleep(1)
    vlm_assert("interaction_score_zero_then_nonzero",
               "Is the score number shown at the very top-centre of this pinball screen "
               "greater than zero (i.e. NOT '0')?",
               depth=1, jump_kind="value", tag="content")


# ══════════════════════════════════════════════════════════════════════════════
# 13. BALL IS LAUNCHED ONTO THE FIELD AFTER A TAP  (input->consequence, canvas)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_ball_launched_vlm",))
def test_ball_launched_onto_field():
    n = _start_game_to_field()
    if n is None:
        record("interaction_ball_launched_vlm", False,
               "setup_failed: could not enter gameplay",
               depth=1, jump_kind="transition", tag="shape")
        return
    s = get_screen_info()
    tap(int(s["width"] * 0.50), int(s["height"] * 0.30))   # launch the ball
    time.sleep(0.6)
    vlm_assert("interaction_ball_launched",
               "On this pinball playfield, is there a small solid bright circular ball "
               "somewhere inside the table outline (the ball is in play), distinct from "
               "the ring-shaped rollover targets?",
               depth=1, jump_kind="transition", tag="shape")


# ══════════════════════════════════════════════════════════════════════════════
# 14. SEQUENCE: PLAY -> END -> PLAY AGAIN  (two games in a row, list has >=1 row)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_two_games_sequence",))
def test_play_end_play_sequence():
    clear_data()
    first = and_play_and_end_game()
    and_reset_depth()
    if first is None:
        record("interaction_two_games_sequence", False,
               "setup_failed: first game could not be completed",
               depth=2, jump_kind="transition", expect=">=1 numeric row after 2nd game")
        return
    # First game must return us to a fresh menu (startGameButton back).
    back_to_menu = node_by_id(first, "startGameButton") is not None
    second = and_play_and_end_game()
    and_reset_depth()
    if second is None:
        record("interaction_two_games_sequence", False,
               "behavior_wrong: second game could not be started/ended",
               depth=2, jump_kind="transition", expect=">=1 numeric row after 2nd game")
        return
    n = and_reach_high_scores()
    has_rows = bool(n) and len(_numeric_rows(n)) >= 1
    ok = back_to_menu and has_rows
    record("interaction_two_games_sequence", ok,
           "" if ok else "behavior_wrong: play->end->play sequence did not populate high scores",
           depth=2, jump_kind="transition",
           expect="fresh menu between games + >=1 numeric high-score row after 2nd game")


# ══════════════════════════════════════════════════════════════════════════════
# 15. PAUSE VIA PAUSE-ICON  (multi-step state consequence, depth 2)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_pause_via_icon",))
def test_pause_via_icon():
    n = _start_game_to_field()
    if n is None:
        record("interaction_pause_via_icon", False,
               "setup_failed: could not enter gameplay",
               depth=2, jump_kind="transition", expect="resumeGameButton appears")
        return
    pi = node_by_id(n, "pauseIcon")
    if pi is None or not tap_node(pi):
        record("interaction_pause_via_icon", False,
               "feature_missing: no pause control in gameplay",
               depth=2, jump_kind="transition", expect="resumeGameButton appears")
        return
    and_enter("paused_menu")
    time.sleep(1.2)
    n = ui()
    ok = node_by_id(n, "resumeGameButton") is not None \
        and node_by_id(n, "pauseIcon") is None
    record("interaction_pause_via_icon", ok,
           "" if ok else "behavior_wrong: pauseIcon tap did not open the paused menu",
           depth=2, jump_kind="transition", expect="resumeGameButton present + pauseIcon gone")


# ══════════════════════════════════════════════════════════════════════════════
# 16. PAUSE VIA SCORE-AREA TAP  (alternate trigger, same consequence, depth 2)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_pause_via_scoreview",))
def test_pause_via_scoreview():
    n = _start_game_to_field()
    if n is None:
        record("interaction_pause_via_scoreview", False,
               "setup_failed: could not enter gameplay",
               depth=2, jump_kind="transition", expect="resumeGameButton appears")
        return
    sv = node_by_id(n, "scoreView")
    if sv is None or not tap_node(sv):
        record("interaction_pause_via_scoreview", False,
               "feature_missing: no scoreView to tap",
               depth=2, jump_kind="transition", expect="resumeGameButton appears")
        return
    and_enter("paused_menu")
    time.sleep(1.2)
    n = ui()
    ok = node_by_id(n, "resumeGameButton") is not None
    record("interaction_pause_via_scoreview", ok,
           "" if ok else "behavior_wrong: score-area tap did not pause the game",
           depth=2, jump_kind="transition", expect="resumeGameButton present after scoreView tap")


# ══════════════════════════════════════════════════════════════════════════════
# 17. RESUME RETURNS TO GAMEPLAY  (multi-step: play -> pause -> resume)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_resume_returns_gameplay",))
def test_resume_returns_to_gameplay():
    n = _start_game_to_field()
    if n is None:
        record("interaction_resume_returns_gameplay", False,
               "setup_failed: could not enter gameplay",
               depth=2, jump_kind="transition", expect="pauseIcon back after resume")
        return
    pi = node_by_id(n, "pauseIcon")
    if pi is None or not tap_node(pi):
        record("interaction_resume_returns_gameplay", False,
               "feature_missing: no pause control",
               depth=2, jump_kind="transition", expect="pauseIcon back after resume")
        return
    and_enter("paused_menu")
    time.sleep(1.2)
    n = ui()
    rg = node_by_id(n, "resumeGameButton")
    if rg is None or not tap_node(rg):
        record("interaction_resume_returns_gameplay", False,
               "behavior_wrong: paused menu had no RESUME control",
               depth=2, jump_kind="transition", expect="pauseIcon back after resume")
        return
    time.sleep(1.2)
    n = ui()
    ok = node_by_id(n, "pauseIcon") is not None \
        and node_by_id(n, "buttonPanel") is None
    record("interaction_resume_returns_gameplay", ok,
           "" if ok else "behavior_wrong: RESUME did not return to gameplay",
           depth=2, jump_kind="transition", expect="pauseIcon present + buttonPanel gone after RESUME")


# ══════════════════════════════════════════════════════════════════════════════
# 18. END-GAME FROM PAUSED RETURNS TO FRESH MENU  (data-neutral state transition)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_endgame_returns_menu",))
def test_endgame_returns_to_fresh_menu():
    n = _start_game_to_field()
    if n is None:
        record("interaction_endgame_returns_menu", False,
               "setup_failed: could not enter gameplay",
               depth=2, jump_kind="transition", expect="fresh menu (START GAME + Select Table) back")
        return
    pi = node_by_id(n, "pauseIcon")
    if pi is None or not tap_node(pi):
        record("interaction_endgame_returns_menu", False,
               "feature_missing: no pause control",
               depth=2, jump_kind="transition", expect="fresh menu (START GAME + Select Table) back")
        return
    and_enter("paused_menu")
    time.sleep(1.2)
    n = ui()
    eg = node_by_id(n, "endGameButton")
    if eg is None or not tap_node(eg):
        record("interaction_endgame_returns_menu", False,
               "behavior_wrong: paused menu had no END GAME control",
               depth=2, jump_kind="transition", expect="fresh menu (START GAME + Select Table) back")
        return
    time.sleep(1.5)
    n = ui()
    # Fresh menu: startGameButton + selectTableRow return; resume/end are gone.
    ok = node_by_id(n, "startGameButton") is not None \
        and node_by_id(n, "selectTableRow") is not None \
        and node_by_id(n, "resumeGameButton") is None
    record("interaction_endgame_returns_menu", ok,
           "" if ok else "behavior_wrong: End Game did not return to the fresh main menu",
           depth=2, jump_kind="transition",
           expect="startGameButton + selectTableRow present, resumeGameButton gone")


# ══════════════════════════════════════════════════════════════════════════════
# 19. BACK DURING GAME PAUSES (does not exit)  (custom-back consequence, depth 1)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_back_pauses_game",))
def test_back_during_game_pauses():
    n = _start_game_to_field()
    if n is None:
        record("interaction_back_pauses_game", False,
               "setup_failed: could not enter gameplay",
               depth=1, jump_kind="transition", expect="resumeGameButton appears, app still foreground")
        return
    press_key("KEYCODE_BACK")
    time.sleep(1.2)
    n = ui()
    ok = node_by_id(n, "resumeGameButton") is not None and is_app_foreground()
    record("interaction_back_pauses_game", ok,
           "" if ok else "behavior_wrong: BACK during game did not pause (or exited the app)",
           depth=1, jump_kind="transition", expect="resumeGameButton present + app foreground")



# ══════════════════════════════════════════════════════════════════════════════
# 20. START-GAME ENTERS GAMEPLAY  (core state flip; tree consequence + VLM)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_start_enters_gameplay",
                   "interaction_start_score_zero_vlm"))
def test_start_game_enters_gameplay():
    restart_app()
    if not wait_for_foreground(10):
        record("interaction_start_enters_gameplay", False,
               "setup_failed: app did not reach foreground",
               depth=1, jump_kind="transition", expect="pauseIcon present, buttonPanel gone")
        record("interaction_start_score_zero_vlm", False,
               "setup_failed: app did not reach foreground",
               depth=1, jump_kind="transition", tag="position")
        return
    n = ui()
    before = and_showing(n)
    sg = node_by_id(n, "startGameButton")
    entered = bool(sg) and tap_node(sg)
    if entered:
        and_enter("gameplay")
        time.sleep(2)
    after = and_showing()
    n = ui()
    # State flip: buttonPanel disappears, pauseIcon appears (a real surface jump).
    ok = entered and node_by_id(n, "pauseIcon") is not None \
        and node_by_id(n, "buttonPanel") is None \
        and and_reach(before, after, target="pauseIcon", source="START GAME")
    record("interaction_start_enters_gameplay", ok,
           "" if ok else "behavior_wrong: Start Game did not enter the gameplay state",
           depth=1, jump_kind="transition",
           expect="pauseIcon appeared + startGameButton/buttonPanel gone")
    # VLM (fine, position): a fresh game shows the score '0' at the top-centre.
    vlm_assert("interaction_start_score_zero",
               "At the very top-centre of this pinball screen (in the status bar strip), "
               "is a single digit '0' displayed as the current score?",
               depth=1, jump_kind="transition", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# 21. HIGH-SCORE BANNER RENDERS ON THE HIGH-SCORES PANEL  (canvas data readback)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_highscore_banner_vlm",))
def test_highscore_banner_rendered():
    clear_data()
    if and_play_and_end_game() is None:
        record("interaction_highscore_banner_vlm", False,
               "setup_failed: could not complete a game to produce a high score",
               depth=1, jump_kind="value", tag="color")
        return
    # Open the High Scores panel — its top status strip renders "High Score: <n>"
    # in yellow (canvas text, not in the tree).
    if and_reach_high_scores() is None:
        record("interaction_highscore_banner_vlm", False,
               "feature_missing: High Scores panel unreachable",
               depth=1, jump_kind="value", tag="color")
        return
    vlm_assert("interaction_highscore_banner",
               "In the thin status strip across the very top of the screen (above the "
               "'High scores' dialog), is there yellow-coloured text reading "
               "'High Score:' followed by a number?",
               depth=1, jump_kind="value", tag="color")


# ══════════════════════════════════════════════════════════════════════════════
# Suite registry — order groups the slow play/persistence tests together.
# ══════════════════════════════════════════════════════════════════════════════
TESTS = [
    test_fresh_install_no_scores,
    test_highscore_created_by_playing,
    test_highscore_survives_process_death,
    test_multi_record_highscore_list,
    test_last_score_is_present_and_numeric,
    test_unlimited_balls_excluded_from_highscores,
    test_linewidth_value_roundtrip,
    test_linewidth_survives_process_death,
    test_table_selection_survives_kill,
    test_table_cycle_back_to_one,
    test_selected_table_used_in_game,
    test_play_makes_score_nonzero,
    test_ball_launched_onto_field,
    test_play_end_play_sequence,
    test_pause_via_icon,
    test_pause_via_scoreview,
    test_resume_returns_to_gameplay,
    test_endgame_returns_to_fresh_menu,
    test_back_during_game_pauses,
    test_start_game_enters_gameplay,
    test_highscore_banner_rendered,
]


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