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
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
"""Recreation-Bench Windows pytest conftest — per-test app lifecycle + auto result collection.

Provides fixtures: app (per-test: launch → yield → kill), rb (per-test depth tracker),
results_dir, frame.

Each test's outcome is written into ``<module>_results.json`` incrementally (crash-safe).

Design notes:
- The ``app`` fixture launches a FRESH app instance for each test and kills it after.
- Cold mode (RB_APP_BINARY or RB_LAUNCH_SCRIPT set): per-test launch/kill with retries,
  PID-based window matching, image-name fallback kill.
- Warm mode (neither set): attach to already-running app, no kill on teardown.
- Results are flushed to disk after EVERY test (crash-safe).
"""
from __future__ import annotations

import json
import os
import shutil
import subprocess
import time

import pytest

try:
    import rb_testgen_kit as kit

    _tier_of = kit.tier_of
except Exception:
    def _tier_of(jk):
        return {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}.get(jk, 2)


# ── Results accumulator (flushed after every test for crash safety) ───────────
_results: list[dict] = []


def pytest_configure(config):
    config.addinivalue_line(
        "markers",
        "rb(jump_kind, expect, depth): declare behavioral metadata for scoring",
    )


def pytest_sessionstart(session):
    _results.clear()


def _extract_rb_marker(item):
    """(jump_kind, expect, declared_depth) from the @pytest.mark.rb(...) marker."""
    m = item.get_closest_marker("rb")
    if m is None:
        return "none", "", None
    jk = m.kwargs.get("jump_kind", m.args[0] if m.args else "none")
    expect = m.kwargs.get("expect", m.args[1] if len(m.args) > 1 else "")
    depth = m.kwargs.get("depth", None)
    return jk, expect, depth


# ── Depth tracker fixture ────────────────────────────────────────────────────
class _RBDepth:
    __slots__ = ("depth", "reached")

    def __init__(self):
        self.depth = 0
        self.reached = 0

    def enter(self, _surface: str = "") -> int:
        self.depth += 1
        self.reached = max(self.reached, self.depth)
        return self.depth

    def back(self) -> int:
        self.depth = max(0, self.depth - 1)
        return self.depth


@pytest.fixture
def rb(request):
    """Depth tracker: ``def test_x(app, rb): rb.enter("prefs")``. Fresh per test;
    pytest_runtest_makereport reads its ``reached`` into the record's ``depth``."""
    tracker = _RBDepth()
    request.node._rb = tracker
    return tracker


# ── App lifecycle helpers ────────────────────────────────────────────────────
def _results_dir() -> str:
    return os.environ.get("RB_RESULTS_DIR") or os.environ.get("RESULTS_DIR", ".")


_APP_STARTUP_WAIT = 3
_LAUNCH_RETRIES = 3


def _launch_app() -> int | None:
    """Launch the app with retries. Handles single-instance apps where the initial
    PID dies and the real process runs under a different PID (found by exe name).

    Returns PID or None.
    """
    launch_script = os.environ.get("RB_LAUNCH_SCRIPT", "")
    binary = os.environ.get("RB_APP_BINARY", "")
    exe_name = os.path.basename(binary) if binary else ""

    for attempt in range(_LAUNCH_RETRIES):
        pid = None

        if launch_script and os.path.exists(launch_script):
            try:
                ps_exe = shutil.which("pwsh") or "powershell"
                result = subprocess.run(
                    [ps_exe, "-ExecutionPolicy", "Bypass", "-File", launch_script],
                    capture_output=True, text=True, timeout=30,
                    encoding="utf-8", errors="replace",
                )
                for line in result.stdout.strip().splitlines():
                    line = line.strip()
                    if line.isdigit():
                        pid = int(line)
                        break
            except Exception:
                pass
        elif binary and os.path.exists(binary):
            try:
                proc = subprocess.Popen(
                    [binary], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                )
                pid = proc.pid
            except Exception:
                pass

        if pid is None:
            if attempt < _LAUNCH_RETRIES - 1:
                time.sleep(3)
            continue

        # Wait for process to settle
        time.sleep(_APP_STARTUP_WAIT)

        # Verify the PID is still alive
        if _is_pid_alive(pid):
            return pid

        # Single-instance app: PID died, find real process by exe name
        if exe_name:
            real_pid = _find_pid_by_name(exe_name)
            if real_pid:
                return real_pid

        if attempt < _LAUNCH_RETRIES - 1:
            time.sleep(3)

    return None


def _is_pid_alive(pid: int) -> bool:
    """Check if a PID is still running."""
    try:
        result = subprocess.run(
            ["tasklist", "/FI", f"PID eq {pid}", "/NH", "/FO", "CSV"],
            capture_output=True, text=True, timeout=5,
        )
        return str(pid) in result.stdout
    except Exception:
        return False


def _find_pid_by_name(exe_name: str) -> int | None:
    """Find a running process by image name. Returns PID or None."""
    try:
        result = subprocess.run(
            ["tasklist", "/FI", f"IMAGENAME eq {exe_name}", "/NH", "/FO", "CSV"],
            capture_output=True, text=True, timeout=5,
        )
        for line in result.stdout.strip().splitlines():
            if exe_name.lower() in line.lower():
                parts = line.strip('"').split('","')
                if len(parts) >= 2 and parts[1].strip('"').isdigit():
                    return int(parts[1].strip('"'))
    except Exception:
        pass
    return None


def _kill_app(pid: int) -> None:
    """Graceful close first (prevents 'restore session?' on next launch),
    then force kill as fallback, then verify by image name."""
    binary = os.environ.get("RB_APP_BINARY", "")
    exe_name = os.path.basename(binary) if binary else ""

    # Step 1: Graceful close (WM_CLOSE) — gives app a chance to save state cleanly
    try:
        subprocess.run(
            ["taskkill", "/PID", str(pid)],
            capture_output=True, timeout=5,
        )
    except Exception:
        pass

    # Wait up to 3s for graceful exit
    for _ in range(6):
        if not _is_pid_alive(pid):
            break
        time.sleep(0.5)

    # Step 2: Force kill if still alive
    if _is_pid_alive(pid):
        try:
            subprocess.run(
                ["taskkill", "/F", "/T", "/PID", str(pid)],
                capture_output=True, timeout=10,
            )
        except Exception:
            pass
        time.sleep(1)

    # Step 3: Fallback kill by image name (catches single-instance app re-PID)
    if exe_name and _find_pid_by_name(exe_name):
        try:
            subprocess.run(
                ["taskkill", "/F", "/IM", exe_name],
                capture_output=True, timeout=10,
            )
        except Exception:
            pass
        time.sleep(1)


def _wait_for_window_by_pid(pid: int, timeout: float = 30.0):
    """Wait for a window belonging to the given PID (or its children) to appear."""
    try:
        from pywinauto import Desktop
        import psutil
    except ImportError:
        return None

    deadline = time.time() + timeout
    while time.time() < deadline:
        try:
            # Build PID tree (app may spawn child processes that own the window)
            pids = {pid}
            try:
                parent = psutil.Process(pid)
                for child in parent.children(recursive=True):
                    pids.add(child.pid)
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                pass

            for w in Desktop(backend="uia").windows():
                try:
                    if w.process_id() in pids:
                        title = w.window_text() or ""
                        # Skip empty/system windows
                        if title and title not in ("", "Program Manager",
                                                   "Microsoft Text Input Application"):
                            return w
                except Exception:
                    continue
        except Exception:
            pass
        time.sleep(0.5)
    return None


# ── Stray system dialog dismissal (per-test, M5 fix) ────────────────────────
_STRAY_DIALOG_TITLES = {
    "Shutdown Event Tracker", "Windows Error Reporting",
    "Microsoft Visual C++ Runtime Library", "Windows Update",
    ".NET Framework", "Application Error", "Windows Security",
}


def _dismiss_stray_system_dialogs() -> None:
    """Close system-level dialogs that can steal focus or block interaction."""
    try:
        from pywinauto import Desktop
        from pywinauto.keyboard import send_keys
        for w in Desktop(backend="uia").windows():
            try:
                title = w.window_text() or ""
                if any(s in title for s in _STRAY_DIALOG_TITLES):
                    try:
                        w.close()
                    except Exception:
                        try:
                            w.set_focus()
                            send_keys("{ESC}")
                        except Exception:
                            pass
            except Exception:
                continue
    except Exception:
        pass


_post_launch_captured = False


def _get_module_from_argv() -> str:
    """Extract module name from sys.argv (pytest is invoked with the test file path)."""
    for arg in sys.argv:
        base = os.path.basename(arg)
        if base.startswith("test_uia_") and base.endswith(".py"):
            return base[len("test_uia_"):-len(".py")]
    return "unknown"


def _capture_post_launch(window) -> None:
    """Capture a desktop screenshot after the first successful app launch per module."""
    global _post_launch_captured
    if _post_launch_captured:
        return
    _post_launch_captured = True
    try:
        from PIL import ImageGrab
        rd = _results_dir()
        ss_dir = os.path.join(rd, "screenshots")
        os.makedirs(ss_dir, exist_ok=True)
        module = _get_module_from_argv()
        img = ImageGrab.grab()
        img.save(os.path.join(ss_dir, f"post_launch_{module}.png"))
    except Exception:
        pass


# ── App fixtures ─────────────────────────────────────────────────────────────
@pytest.fixture(scope="session")
def results_dir() -> str:
    return _results_dir()


@pytest.fixture
def app():
    """Per-test app lifecycle: launch fresh → yield window → kill.

    Cold mode: PID-based window matching (precise, no false positives).
    Warm mode: title-based matching (attaches to already-running app).
    """
    import rb_uia

    app_name = os.environ.get("RB_APP_NAME", "")
    binary = os.environ.get("RB_APP_BINARY", "")
    launch_script = os.environ.get("RB_LAUNCH_SCRIPT", "")

    # Dismiss system-level stray windows before each test (M5 fix)
    _dismiss_stray_system_dialogs()

    if binary or launch_script:
        # Cold mode: launch fresh app for this test
        pid = _launch_app()
        if pid is None:
            pytest.fail("app failed to launch (all retries exhausted)", pytrace=False)

        # Wait for window by PID (precise matching, no title ambiguity)
        w = _wait_for_window_by_pid(pid, timeout=30.0)
        if w is None:
            _kill_app(pid)
            pytest.fail(
                f"app launched (PID={pid}) but no window found within 30s",
                pytrace=False,
            )
        rb_uia.focus_app_window(w)
        # Capture post-launch screenshot (once per module for debugging)
        _capture_post_launch(w)
        yield w
        _kill_app(pid)
    else:
        # Warm mode: attach to already-running app (for run_live.ps1)
        w = rb_uia.get_app(app_name)
        if w is None:
            pytest.fail(
                f"app not found via UIA (RB_APP_NAME={app_name!r})",
                pytrace=False,
            )
        rb_uia.focus_app_window(w)
        yield w


@pytest.fixture
def frame(app):
    """Alias for the app's top-level window."""
    return app


# ── Hook: collect results per test + flush immediately (C3 fix) ──────────────
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    if call.when != "call" and not (call.when == "setup" and report.failed):
        return
    jk, expect, declared_depth = _extract_rb_marker(item)
    tracker = getattr(item, "_rb", None)
    measured = tracker.reached if tracker else 0
    depth = declared_depth if declared_depth is not None else measured

    passed = report.passed if call.when == "call" else False
    msg = ""
    if report.failed and report.longrepr:
        msg = str(report.longrepr)[-500:]

    rec = {
        "name": item.name,
        "passed": passed,
        "message": msg,
        "depth": depth,
        "jump_kind": jk,
        "tier": _tier_of(jk),
        "expect": expect,
    }
    _results.append(rec)
    # Flush immediately after each test (crash-safe: partial results survive)
    _flush_results(item)


def _flush_results(item=None):
    """Write current results to disk (incremental, crash-safe)."""
    rd = _results_dir()
    module = "unknown"
    if item:
        fspath = str(item.fspath.basename if hasattr(item.fspath, "basename")
                     else os.path.basename(str(item.fspath)))
        if fspath.startswith("test_uia_") and fspath.endswith(".py"):
            module = fspath[len("test_uia_"):-len(".py")]
    elif _results:
        module = _module_from_results()

    payload = {"module": module, "tests": list(_results)}
    try:
        os.makedirs(rd, exist_ok=True)
        with open(os.path.join(rd, f"{module}_results.json"), "w") as f:
            json.dump(payload, f, indent=2)
    except Exception:
        pass


def _module_from_results() -> str:
    return "unknown"


# ── Session finish: final write ──────────────────────────────────────────────
def pytest_sessionfinish(session, exitstatus):
    """Final write of results (covers the case where last test didn't trigger flush)."""
    rd = _results_dir()
    module = _module_from_session(session)
    payload = {"module": module, "tests": list(_results)}
    try:
        os.makedirs(rd, exist_ok=True)
        with open(os.path.join(rd, f"{module}_results.json"), "w") as f:
            json.dump(payload, f, indent=2)
    except Exception:
        pass


def _module_from_session(session) -> str:
    """Extract module name from the test file being run."""
    items = session.items
    if items:
        fspath = str(items[0].fspath.basename if hasattr(items[0].fspath, "basename")
                     else os.path.basename(str(items[0].fspath)))
        if fspath.startswith("test_uia_") and fspath.endswith(".py"):
            return fspath[len("test_uia_"):-len(".py")]
    return "unknown"


# ── Terminal summary: run self-audit ─────────────────────────────────────────
def pytest_terminal_summary(terminalreporter, exitstatus, config):
    rd = _results_dir()
    if not os.path.isdir(rd):
        return
    try:
        import rb_testgen_kit as k
        terminalreporter.write_sep("=", "RB Self-Audit")
        k.rb_audit(rd)
        k.rb_lint(rd)
        testgen_dir = os.path.dirname(rd) if os.path.basename(rd) == "baseline_results" else rd
        if os.path.isdir(testgen_dir):
            k.rb_lint_sources(testgen_dir)
            k.rb_audit_depth(testgen_dir, rd)
            k.rb_audit_tier(testgen_dir, rd)
    except Exception as e:
        terminalreporter.write_line(f"[rb_audit] skipped: {e}")