File size: 26,821 Bytes
51eaa60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
"""
verifier_helpers.py — High-level AX testing patterns for macOS app verification.

v6 core library. Encodes all robust testing patterns as reusable functions
so verifier agents call high-level APIs instead of building from scratch.

Depends on: ax_helpers.py (AXHelper class)
"""

import datetime
import os
import re
import signal
import subprocess
import time
from collections import Counter

# ---------------------------------------------------------------------------
# Key codes (macOS virtual key codes)
# ---------------------------------------------------------------------------
KC_LEFT_ARROW = 123
KC_RIGHT_ARROW = 124
KC_UP_ARROW = 126
KC_DOWN_ARROW = 125
KC_SPACE = 49
KC_RETURN = 36
KC_TAB = 48
KC_ESCAPE = 53
KC_Q = 12
KC_W = 13

# ---------------------------------------------------------------------------
# Bilingual keyword constants
# ---------------------------------------------------------------------------

QUIT_KEYWORDS = [
    "quit", "exit", "close app", "terminate",
    "退出", "关闭", "结束",
]
UPDATE_KEYWORDS = [
    "update", "updates", "check for update", "check for updates",
    "check update", "software update",
    "更新", "检查更新", "软件更新",
]
CALENDAR_KEYWORDS = [
    "calendar", "calendars", "event", "events",
    "show calendar", "hide calendar", "toggle calendar",
    "日历", "事件", "日程",
]
HOLIDAY_KEYWORDS = [
    "holiday", "holidays", "public holiday", "festival",
    "假日", "节假日", "节日", "假期", "公共假日",
]
APPEARANCE_KEYWORDS = [
    "appearance", "theme", "dark", "light", "system",
    "dark mode", "light mode",
    "外观", "主题", "深色", "浅色", "暗色", "亮色",
]
LOGIN_KEYWORDS = [
    "login", "launch at login", "start at login", "open at login",
    "launch at startup", "start at startup", "auto start", "autostart",
    "登录时启动", "开机启动", "自动启动", "启动时打开",
]
ABOUT_KEYWORDS = [
    "about", "info", "information", "version",
    "关于", "版本", "信息",
]
TODAY_KEYWORDS = [
    "today", "go to today", "return to today",
    "current", "now",
    "今天", "今日", "当前",
]

NAV_PREV_KEYWORDS = [
    "prev", "previous", "back", "left", "earlier",
    "上一", "前一", "上个", "前",
    "◀", "←", "❮", "◁", "⬅",
]
NAV_NEXT_KEYWORDS = [
    "next", "forward", "right", "later",
    "下一", "后一", "下个", "后",
    "▶", "→", "❯", "▷", "➡",
]

WEEKDAY_SYMBOLS = {
    "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
    "SU", "MO", "TU", "WE", "TH", "FR", "SA",
    "Su", "Mo", "Tu", "We", "Th", "Fr",
    "S", "M", "T", "W", "F",
    "日", "一", "二", "三", "四", "五", "六",
}

MONTH_YEAR_PATTERN = re.compile(
    r"("
    r"[A-Z][a-z]{2,8}\s+\d{4}"
    r"|\d{4}\s*[年/\-\.]\s*\d{1,2}\s*[月]?"
    r"|\d{1,2}\s*[月]\s*\d{4}"
    r"|\d{4}\s*[年]"
    r"|[A-Z][a-z]{2,8}\s*\d{4}"
    r")",
    re.UNICODE,
)

LUNAR_KEYWORDS = [
    "初", "十", "廿", "卅",
    "正月", "二月", "三月", "四月", "五月", "六月",
    "七月", "八月", "九月", "十月", "冬月", "腊月",
]

SOLAR_TERM_KEYWORDS = [
    "立春", "雨水", "惊蛰", "春分", "清明", "谷雨",
    "立夏", "小满", "芒种", "夏至", "小暑", "大暑",
    "立秋", "处暑", "白露", "秋分", "寒露", "霜降",
    "立冬", "小雪", "大雪", "冬至", "小寒", "大寒",
]


# ---------------------------------------------------------------------------
# Low-level: Key sending via CGEvent
# ---------------------------------------------------------------------------

def send_key(keycode, modifiers=None):
    """Send a keyboard event via CGEvent API.
    modifiers: list of "cmd", "shift", "alt", "ctrl"."""
    import Quartz
    src = Quartz.CGEventSourceCreate(Quartz.kCGEventSourceStateHIDSystemState)
    down = Quartz.CGEventCreateKeyboardEvent(src, keycode, True)
    up = Quartz.CGEventCreateKeyboardEvent(src, keycode, False)
    flags = 0
    if modifiers:
        flag_map = {
            "cmd": Quartz.kCGEventFlagMaskCommand,
            "shift": Quartz.kCGEventFlagMaskShift,
            "alt": Quartz.kCGEventFlagMaskAlternate,
            "ctrl": Quartz.kCGEventFlagMaskControl,
        }
        for mod in modifiers:
            flags |= flag_map.get(mod, 0)
        Quartz.CGEventSetFlags(down, flags)
        Quartz.CGEventSetFlags(up, flags)
    Quartz.CGEventPost(Quartz.kCGHIDEventTap, down)
    Quartz.CGEventPost(Quartz.kCGHIDEventTap, up)
    time.sleep(0.3)


def click_at(x, y):
    """Click at absolute screen coordinates via CGEvent."""
    import Quartz
    point = Quartz.CGPointMake(x, y)
    down = Quartz.CGEventCreateMouseEvent(
        None, Quartz.kCGEventLeftMouseDown, point, Quartz.kCGMouseButtonLeft)
    up = Quartz.CGEventCreateMouseEvent(
        None, Quartz.kCGEventLeftMouseUp, point, Quartz.kCGMouseButtonLeft)
    Quartz.CGEventPost(Quartz.kCGHIDEventTap, down)
    time.sleep(0.05)
    Quartz.CGEventPost(Quartz.kCGHIDEventTap, up)
    time.sleep(0.3)


# ---------------------------------------------------------------------------
# Panel detection: find and manage UI panels/windows
# ---------------------------------------------------------------------------

def find_panel_container(ax, min_texts=3, max_depth=12):
    """Find the app's main panel container.

    A popover/sheet is accepted by ROLE alone: a menu-bar / status-item app's
    freshly-opened popover is often sparse (an empty clipboard list, an empty
    note, a search field) so requiring >= min_texts wrongly REJECTS it. The
    generic container roles (window/group/web_area/scroll_area) still require
    >= min_texts text children to avoid matching window chrome.

    Searches to max_depth=12 (was 3). Status-item popovers sit ~7-8 levels deep
    in the AX tree, so the old depth-3 search SILENTLY MISSED them ->
    ensure_panel_open()/ensure_ui_visible() returned None -> every reveal-
    dependent test hit `None.id` -> 0% baseline -> the whole menu-bar app was
    pruned to 0 and the job failed. (Verified on a live VM: depth-3 missed the
    popover 3/3 fresh launches; depth-12 + role-accept found it 3/3.)
    Returns the AXElement or None."""
    for role in ("popover", "sheet"):
        containers = ax.find(role=role, max_results=10, max_depth=max_depth)
        if containers:
            return containers[0]
    for role in ("window", "group", "web_area", "scroll_area"):
        containers = ax.find(role=role, max_results=10, max_depth=max_depth)
        for c in containers:
            texts = ax.find_text_elements(root_id=c.id, max_results=min_texts + 1)
            if len(texts) >= min_texts:
                return c
    return None


def is_panel_visible(ax, min_texts=2):
    """Check if any panel-like container with content is visible."""
    return find_panel_container(ax, min_texts=min_texts) is not None


def ensure_panel_open(ax):
    """Ensure the app's panel is open. Tries clicking each menu_bar_item.
    Returns the panel container element, or None if all attempts fail."""
    panel = find_panel_container(ax)
    if panel:
        return panel

    # max_depth=6 (was 3): the status-item / menu-bar-extra item that actually
    # reveals a status app's popover sits ~depth 4 — DEEPER than the app's own
    # menu-bar items (Apple/File/Edit at depth 2-3). A depth-3 search returned
    # only the app menus (whose AXPress opens dropdowns, NOT the popover), so the
    # status item was never pressed and the popover never opened -> None ->
    # 0% baseline for every menu-bar app. Widen the net so the status item is
    # found and pressed. (Verified on a live VM: depth-3 never opened the popover;
    # depth>=4 did.)
    mbis = ax.find(role="menu_bar_item", max_results=12, max_depth=6)
    # Two passes. The old code interleaved a CG click per item: AXPress, and if
    # that didn't reveal, click_element_cg the SAME item immediately. But a CG
    # click on an app menu (Apple/File/Edit) opens a blocking dropdown that
    # POISONS the next press, so the status popover a later AXPress would have
    # opened was never seen -> None -> 0% baseline for menu-bar apps.
    # Pass 1: AXPress every item, dismissing any dropdown a miss leaves open.
    # (Verified on a live VM: AXPress-only opened + detected the popover 3/3;
    # the interleaved CG click made it fail 3/3.)
    for mbi in mbis:
        ax.action(mbi.id, "AXPress")
        time.sleep(1.0)
        panel = find_panel_container(ax)
        if panel:
            return panel
        dismiss_menus(ax)
    # Pass 2: CG-click fallback only if AXPress revealed nothing anywhere.
    for mbi in mbis:
        ax.click_element_cg(mbi.id)
        time.sleep(1.0)
        panel = find_panel_container(ax)
        if panel:
            return panel
        dismiss_menus(ax)

    return None


def dismiss_panel(ax):
    """Dismiss the panel. Multi-strategy: Escape -> click outside.
    Returns True if panel was dismissed (or was already closed)."""
    if not is_panel_visible(ax):
        return True

    send_key(KC_ESCAPE)
    time.sleep(0.8)
    if not is_panel_visible(ax):
        return True

    click_at(10, 10)
    time.sleep(0.8)
    return not is_panel_visible(ax)


def dismiss_menus(ax):
    """Dismiss any open menus by pressing Escape twice."""
    send_key(KC_ESCAPE)
    time.sleep(0.3)
    send_key(KC_ESCAPE)
    time.sleep(0.3)


# ---------------------------------------------------------------------------
# Text extraction: robust methods for getting text from panels
# ---------------------------------------------------------------------------

def get_panel_texts(ax, panel=None):
    """Get all text strings from the panel. Scoped to the target app only.
    Returns list[str]."""
    if panel is None:
        panel = find_panel_container(ax)
    if panel is None:
        return []
    text_els = ax.find_text_elements(root_id=panel.id, max_results=300)
    return [el.text for el in text_els if el.text]


def snapshot_panel_text(ax, panel=None):
    """Counter-based snapshot of panel text, for detecting changes."""
    return Counter(get_panel_texts(ax, panel))


def extract_date_numbers(texts):
    """Extract day-of-month numbers (1-31) from a list of text strings.
    Handles standalone "7", mixed "7 廿一", "15 初一", etc."""
    found = set()
    for t in texts:
        s = str(t).strip()
        if s.isdigit():
            n = int(s)
            if 1 <= n <= 31:
                found.add(n)
            continue
        for m in re.finditer(r'\b(\d{1,2})\b', s):
            n = int(m.group(1))
            if 1 <= n <= 31:
                found.add(n)
        m = re.match(r'^(\d{1,2})', s)
        if m:
            n = int(m.group(1))
            if 1 <= n <= 31:
                found.add(n)
    return found


def count_weekday_symbols(texts):
    """Count how many texts match known weekday symbols."""
    return sum(1 for t in texts if str(t).strip() in WEEKDAY_SYMBOLS)


def has_month_year(texts):
    """Check if any text contains a month/year pattern."""
    all_text = " ".join(str(t) for t in texts)
    return MONTH_YEAR_PATTERN.search(all_text) is not None


# ---------------------------------------------------------------------------
# Menu item search: keyword-based with fallback
# ---------------------------------------------------------------------------

def find_by_keywords(items, keywords):
    """Find first item matching any keyword (case-insensitive, partial match)."""
    for item in items:
        name_lower = (item.name or "").lower()
        for kw in keywords:
            if kw.lower() in name_lower:
                return item
    return None


def find_menu_item(ax, keywords):
    """Search for a menu item by keyword list.
    First searches role=menu_item, then falls back to all clickable elements."""
    items = ax.find(role="menu_item", max_results=100)
    result = find_by_keywords(items, keywords)
    if result:
        return result

    clickable = ax.find_clickable(max_results=200)
    return find_by_keywords(clickable, keywords)


def open_actions_menu(ax):
    """Open the actions/settings menu and return its menu items.
    Tries buttons, pop-up buttons, menu buttons, then all clickable elements."""
    panel = ensure_panel_open(ax)
    if panel is None:
        return []

    existing = ax.find(role="menu_item", max_results=5)
    if len(existing) >= 3:
        return existing

    skip_keywords = ["quit", "close", "exit", "delete", "remove"]

    def _try_press(el):
        ax.action(el.id, "AXPress")
        time.sleep(0.6)
        menu_items = ax.find(role="menu_item", max_results=50)
        if len(menu_items) >= 3:
            return menu_items
        ax.click_element_cg(el.id)
        time.sleep(0.6)
        menu_items = ax.find(role="menu_item", max_results=50)
        if len(menu_items) >= 3:
            return menu_items
        send_key(KC_ESCAPE)
        time.sleep(0.3)
        return None

    for role in ("button", "pop_up_button", "menu_button"):
        elements = ax.find(role=role, root_id=panel.id, max_results=20)
        for el in elements:
            name = (el.name or "").lower()
            if any(kw in name for kw in skip_keywords):
                continue
            result = _try_press(el)
            if result:
                return result

    clickable = ax.find_clickable(root_id=panel.id, max_results=50)
    for el in clickable:
        name = (el.name or "").lower()
        if any(kw in name for kw in skip_keywords):
            continue
        if el.role in ("button", "pop_up_button", "menu_button"):
            continue
        result = _try_press(el)
        if result:
            return result

    return ax.find(role="menu_item", max_results=50)


# ---------------------------------------------------------------------------
# Month navigation: multi-strategy with fallback
# ---------------------------------------------------------------------------

def navigate_month(ax, direction="forward"):
    """Navigate to the next/previous month. Multi-strategy fallback:
    1. Named button (prev/next/arrow keywords)
    2. Keyboard arrow key
    3. Brute force — try all clickable elements
    Returns True if panel text changed."""
    panel = ensure_panel_open(ax)
    if panel is None:
        return False
    text_before = snapshot_panel_text(ax, panel)

    # Strategy 1: named button
    keywords = NAV_NEXT_KEYWORDS if direction == "forward" else NAV_PREV_KEYWORDS
    clickable = ax.find_clickable(root_id=panel.id, max_results=50)
    for el in clickable:
        name_lower = (el.name or "").lower()
        if any(kw.lower() in name_lower for kw in keywords):
            ax.action(el.id, "AXPress")
            time.sleep(0.6)
            panel2 = find_panel_container(ax)
            if panel2:
                text_after = snapshot_panel_text(ax, panel2)
                if text_after != text_before:
                    return True
            ax.click_element_cg(el.id)
            time.sleep(0.6)
            panel2 = find_panel_container(ax)
            if panel2:
                text_after = snapshot_panel_text(ax, panel2)
                if text_after != text_before:
                    return True

    # Strategy 2: keyboard
    key_code = KC_RIGHT_ARROW if direction == "forward" else KC_LEFT_ARROW
    send_key(key_code)
    time.sleep(0.5)
    panel2 = find_panel_container(ax)
    if panel2:
        text_after = snapshot_panel_text(ax, panel2)
        if text_after != text_before:
            return True

    # Strategy 3: brute force — try all clickable in panel
    panel = ensure_panel_open(ax)
    if panel is None:
        return False
    text_before = snapshot_panel_text(ax, panel)
    buttons = ax.find(role="button", root_id=panel.id, max_results=20)
    for btn in buttons:
        name = (btn.name or "").lower()
        if any(kw in name for kw in ["quit", "close", "exit", "setting", "about"]):
            continue
        ax.action(btn.id, "AXPress")
        time.sleep(0.6)
        panel2 = find_panel_container(ax)
        if panel2:
            text_after = snapshot_panel_text(ax, panel2)
            if text_after != text_before:
                return True
        ax.click_element_cg(btn.id)
        time.sleep(0.6)
        panel2 = find_panel_container(ax)
        if panel2:
            text_after = snapshot_panel_text(ax, panel2)
            if text_after != text_before:
                return True

    return False


# ---------------------------------------------------------------------------
# Today detection: multi-strategy
# ---------------------------------------------------------------------------

def check_today_in_panel(ax, panel=None):
    """Check if today's date is present in the panel. Multi-strategy:
    1. Extract date numbers and check for today
    2. Search for "today" keywords in text
    3. Check AXSelected/AXDescription attributes"""
    today = datetime.date.today().day

    if panel is None:
        panel = ensure_panel_open(ax)
    texts = get_panel_texts(ax, panel)

    # Strategy 1: date number extraction
    numbers = extract_date_numbers(texts)
    if today in numbers:
        return True

    # Strategy 2: "today" keyword search
    for t in texts:
        for kw in TODAY_KEYWORDS:
            if kw.lower() in str(t).lower():
                return True

    # Strategy 3: AX attributes
    if panel:
        elements = ax.find(root_id=panel.id, max_results=200)
        for el in elements:
            attrs = ax.get(el.id, ["AXSelected", "AXDescription"])
            if attrs.get("AXSelected"):
                return True
            desc = str(attrs.get("AXDescription", ""))
            if re.search(r"\btoday\b|今天|今日", desc, re.IGNORECASE):
                return True
            if str(today) in desc:
                return True

    return False


# ---------------------------------------------------------------------------
# Application lifecycle
# ---------------------------------------------------------------------------

def quit_app_via_menu(ax):
    """Try to quit the app via menu item. Returns True if quit item found and clicked."""
    items = open_actions_menu(ax)
    quit_item = find_by_keywords(items, QUIT_KEYWORDS)
    if quit_item:
        ax.action(quit_item.id, "AXPress")
        time.sleep(1.0)
        return True
    return False


def quit_app_via_shortcut(pid):
    """Quit app via Cmd+Q. Returns True if process terminated."""
    send_key(KC_Q, modifiers=["cmd"])
    time.sleep(1.5)
    try:
        os.kill(pid, 0)
        return False
    except ProcessLookupError:
        return True


def is_process_running(pid):
    """Check if a process is still running."""
    try:
        os.kill(pid, 0)
        return True
    except ProcessLookupError:
        return False


# ---------------------------------------------------------------------------
# Screenshot capture
# ---------------------------------------------------------------------------

def take_screenshot(save_path, region=None):
    """Take a screenshot and save to save_path.
    region: optional (x, y, w, h) tuple for partial capture.
    Returns the save_path on success, None on failure."""
    os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
    cmd = ["screencapture", "-x"]
    if region:
        x, y, w, h = region
        cmd.extend(["-R", f"{x},{y},{w},{h}"])
    cmd.append(save_path)
    try:
        subprocess.run(cmd, timeout=10, check=True,
                       capture_output=True, text=True)
        if os.path.exists(save_path) and os.path.getsize(save_path) > 0:
            return save_path
    except (subprocess.SubprocessError, OSError):
        pass
    return None


def take_screenshot_of_panel(ax, save_path):
    """Take a fullscreen screenshot. Uses fullscreen to stay consistent with
    official screenshots captured by the App Explorer (CU-based)."""
    return take_screenshot(save_path)


# ---------------------------------------------------------------------------
# VLM screenshot comparison (Claude Vision API)
# ---------------------------------------------------------------------------

def _load_image_base64(path):
    """Load image file as base64 string."""
    import base64
    with open(path, "rb") as f:
        return base64.b64encode(f.read()).decode("utf-8")


def _get_media_type(path):
    """Infer media type from file extension."""
    ext = os.path.splitext(path)[1].lower()
    return {"png": "image/png", "jpg": "image/jpeg",
            "jpeg": "image/jpeg", "gif": "image/gif",
            "webp": "image/webp"}.get(ext.lstrip("."), "image/png")


def compare_screenshots_vlm(official_path, recreated_path, aspect,
                             model=None, api_key=None, base_url=None):
    """Compare two screenshots using VLM via OpenAI-compatible API.

    Args:
        official_path: path to the official app screenshot (ground truth)
        recreated_path: path to the recreated app screenshot
        aspect: what visual aspect to compare
        model: VLM model name (default: env VLM_MODEL)
        api_key: API key (default: env VLM_API_KEY)
        base_url: API base URL (default: env VLM_BASE_URL)

    Returns:
        dict with keys: score (int 1-10), reason (str)
    """
    import json
    try:
        import urllib.request
        import urllib.error
    except ImportError:
        return {"score": 1, "reason": "urllib not available"}

    if not os.path.exists(official_path):
        return {"score": 1, "reason": f"Official screenshot not found: {official_path}"}
    if not os.path.exists(recreated_path):
        return {"score": 1, "reason": f"Recreated screenshot not found: {recreated_path}"}

    model = model or os.environ.get("VLM_MODEL", "qwen-vl-max")
    api_key = api_key or os.environ.get("VLM_API_KEY") \
        or os.environ.get("OPENAI_API_KEY") \
        or os.environ.get("ANTHROPIC_API_KEY")
    base_url = base_url or os.environ.get("VLM_BASE_URL") \
        or os.environ.get("OPENAI_BASE_URL") \
        or "https://dashscope.aliyuncs.com/compatible-mode/v1"

    if not api_key:
        return {"score": 1, "reason": "No API key found (set VLM_API_KEY)"}

    base_url = base_url.rstrip("/")

    official_b64 = _load_image_base64(official_path)
    recreated_b64 = _load_image_base64(recreated_path)
    official_mime = _get_media_type(official_path)
    recreated_mime = _get_media_type(recreated_path)

    prompt = f"""You are a visual QA judge comparing two macOS app screenshots.

Image 1 (OFFICIAL): The reference/ground-truth screenshot of the original app.
Image 2 (RECREATED): A screenshot of a recreated version of the same app.

Visual aspect to evaluate: {aspect}

Compare the two screenshots and rate how faithfully the recreated app reproduces the visual aspect described above.

Focus on:
- Layout and positioning of UI elements
- Text content and formatting
- Colors, icons, and visual styling
- Overall visual similarity for the specified aspect

Rate on a scale of 1-10:
  1-2: Completely different, no resemblance
  3-4: Major differences, some elements recognizable
  5-6: Moderate similarity, layout roughly correct but notable differences
  7-8: Good reproduction, minor visual differences
  9-10: Near-perfect match, only trivial differences (antialiasing, font rendering)

Be lenient on minor pixel differences, font rendering, and antialiasing — focus on functional visual equivalence.

Respond in EXACTLY this JSON format (no other text):
{{"score": <integer 1-10>, "reason": "one sentence explanation"}}"""

    payload = {
        "model": model,
        "messages": [{
            "role": "user",
            "content": [
                {"type": "image_url", "image_url": {
                    "url": f"data:{official_mime};base64,{official_b64}"}},
                {"type": "image_url", "image_url": {
                    "url": f"data:{recreated_mime};base64,{recreated_b64}"}},
                {"type": "text", "text": prompt}
            ]
        }],
        "temperature": 0,
        "max_tokens": 256,
    }

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}",
    }

    import time as _time
    max_retries = 12
    last_err = None

    for attempt in range(max_retries):
        try:
            req = urllib.request.Request(
                f"{base_url}/chat/completions",
                data=json.dumps(payload).encode("utf-8"),
                headers=headers,
                method="POST")
            with urllib.request.urlopen(req, timeout=120) as resp:
                body = json.loads(resp.read().decode("utf-8"))

            text = body["choices"][0]["message"]["content"].strip()

            json_match = re.search(r'\{[^{}]*"score"[^{}]*\}', text)
            if json_match:
                result = json.loads(json_match.group())
                score = int(result.get("score", 1))
                score = max(1, min(10, score))
                result["score"] = score
                result.setdefault("reason", "")
                return result

            return {"score": 1, "reason": f"Could not parse VLM response: {text[:200]}"}

        except urllib.error.HTTPError as e:
            last_err = f"HTTP {e.code}: {e.read().decode('utf-8', errors='replace')[:200]}"
            if e.code == 429:
                delay = 3
            else:
                delay = 10
            if attempt < max_retries - 1:
                _time.sleep(delay)
                continue
        except (urllib.error.URLError, json.JSONDecodeError, OSError) as e:
            last_err = str(e)
            if attempt < max_retries - 1:
                _time.sleep(10)
                continue

    return {"score": 1, "reason": f"VLM API error after {max_retries} attempts: {last_err}"}


def assert_screenshot_match(ax, official_screenshot_path, aspect,
                             save_dir="/tmp/verifier_screenshots"):
    """High-level helper: take screenshot of current app panel, compare with official.
    Raises AssertionError if VLM judges the screenshots don't match."""
    import time as _time
    _time.sleep(1.0)
    os.makedirs(save_dir, exist_ok=True)
    basename = os.path.basename(official_screenshot_path)
    recreated_path = os.path.join(save_dir, f"recreated_{basename}")

    result = take_screenshot_of_panel(ax, recreated_path)
    assert result is not None, "Failed to take screenshot of recreated app"

    comparison = compare_screenshots_vlm(official_screenshot_path, recreated_path, aspect)
    score = comparison.get("score", 1)
    assert score >= 7, (
        f"Screenshot mismatch for '{aspect}': {comparison.get('reason', '')} "
        f"(score={score}/10)"
    )