#!/usr/bin/env python3
"""
Regression & Acceptance Test Suite for Newbie Kit v18 (watcher v10.6.5 + prompt-runner v1.6.6-v10.6.5)
Covers Host Orders seq=61161, seq=61162, and A87 seq=61163:
  1) Symmetrical Startup Preflight Gate (xdotool executable + version check, ldd LD_LIBRARY_PATH check,
     X11 display socket, SOCKS5 \x05\x00 handshake probe on 11090/tunnels, seed profile readable without opening,
     ramdisk writable + space, Playwright/Chromium, records writable, PREFLIGHT_BLOCKED distinct from FAILED).
  2) prompt-runner Blocker ②: Input verification off-by-1 (actual=80464 / expected=80463 on PROMPT-A8.txt)
     caused by Chromium contenteditable trailing <br> newline, while preserving strict fail-closed check on real mutations.
  3) watcher Blocker ③: Post-send confirmation readback (_box_text & _read_body_text_robust) when composer
     re-mounts or toggles contenteditable="false" during streaming, plus UNCONFIRMED HOLD self-resolution.
"""

import importlib.util
import json
import os
import socket
import stat
import tempfile
import threading
from pathlib import Path

KIT_DIR = Path(__file__).resolve().parent
WATCHER_PATH = KIT_DIR / "scripts" / "watcher.py"
RUNNER_PATH = KIT_DIR / "scripts" / "prompt-runner.py"


def _load_mod(name, path):
    spec = importlib.util.spec_from_file_location(name, path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


w_mod = _load_mod("watcher_v10_6_5", WATCHER_PATH)
p_mod = _load_mod("prompt_runner_v1_6_6", RUNNER_PATH)


def test_01_xdotool_must_actually_execute_not_just_exist_and_ldd_check():
    """61162 Req 1, 2, 3: xdotool must be in PATH AND actually run 'xdotool version' (rc==0), and ldd must have 0 'not found'."""
    for label, mod in [("watcher", w_mod), ("prompt-runner", p_mod)]:
        with tempfile.TemporaryDirectory() as td:
            tdir = Path(td)
            fake_bin = tdir / "bin"
            fake_bin.mkdir()
            # Create an executable xdotool file that fails at runtime with missing libxdo.so.3 (simulating 61154/61162 morning incident)
            xdo_broken = fake_bin / "xdotool"
            xdo_broken.write_text(
                "#!/bin/sh\necho 'xdotool: error while loading shared libraries: libxdo.so.3: cannot open shared object file: No such file or directory' >&2\nexit 127\n",
                encoding="utf-8",
            )
            xdo_broken.chmod(0o755)

            old_path = os.environ.get("PATH", "")
            old_ensure = mod._ensure_runtime_tool_env
            try:
                os.environ["PATH"] = str(fake_bin)
                mod._ensure_runtime_tool_env = lambda: (os.environ["PATH"], os.environ.get("LD_LIBRARY_PATH", ""))
                ok, detail = mod._preflight_check_xdotool_executable("A8")
                assert ok is False, f"{label}: broken xdotool binary must NOT pass preflight!"
                assert "rc=127" in detail and "libxdo.so.3" in detail and str(xdo_broken) in detail, (
                    f"{label}: failure detail must include exact path, rc, and stderr, got: {detail}"
                )

                # Now make xdotool succeed with 'xdotool version 3.20211022.1'
                xdo_broken.write_text(
                    "#!/bin/sh\necho 'xdotool version 3.20211022.1'\nexit 0\n",
                    encoding="utf-8",
                )
                ok2, detail2 = mod._preflight_check_xdotool_executable("A8")
                assert ok2 is True, f"{label}: working xdotool must pass, got: {detail2}"
                assert "xdotool version 3.20211022.1" in detail2, detail2

                # Now simulate ldd reporting 'libxdo.so.3 => not found'
                fake_ldd = fake_bin / "ldd"
                fake_ldd.write_text(
                    "#!/bin/sh\necho '\tlibxdo.so.3 => not found'\necho '\tlibc.so.6 => /lib/x86_64-linux-gnu/libc.so.6'\nexit 0\n",
                    encoding="utf-8",
                )
                fake_ldd.chmod(0o755)
                ok_ldd, detail_ldd = mod._preflight_check_shared_libraries_ldd("A8")
                assert ok_ldd is False, f"{label}: missing shared lib in ldd must block!"
                assert "libxdo.so.3 => not found" in detail_ldd and "LD_LIBRARY_PATH=" in detail_ldd, detail_ldd

                # Now make ldd report all resolved
                fake_ldd.write_text(
                    "#!/bin/sh\necho '\tlibxdo.so.3 => /usr/lib/x86_64-linux-gnu/libxdo.so.3 (0x00007f)'\nexit 0\n",
                    encoding="utf-8",
                )
                ok_ldd2, detail_ldd2 = mod._preflight_check_shared_libraries_ldd("A8")
                assert ok_ldd2 is True, f"{label}: clean ldd must pass, got: {detail_ldd2}"
            finally:
                mod._ensure_runtime_tool_env = old_ensure
                os.environ["PATH"] = old_path
    print("PASS test_01_xdotool_must_actually_execute_not_just_exist_and_ldd_check")


def test_02_socks5_greeting_probe_catches_ssh_local_forward_impostor():
    """60564 + A87 61163 item ⑦: Port 11090 listening with SSH banner (ssh -L) must be rejected by _probe_socks5_greeting."""
    # 1. Start a fake ssh -L listener that sends SSH-2.0 banner
    srv_ssh = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    srv_ssh.bind(("127.0.0.1", 0))
    srv_ssh.listen(1)
    ssh_port = srv_ssh.getsockname()[1]

    def _ssh_worker():
        try:
            conn, _ = srv_ssh.accept()
            conn.recv(16)
            conn.sendall(b"SSH-2.0-OpenSSH_9.2p1 Debian-2\r\n")
            conn.close()
        except Exception:
            pass

    t1 = threading.Thread(target=_ssh_worker, daemon=True)
    t1.start()
    ok_ssh, dtl_ssh = w_mod._probe_socks5_greeting(ssh_port)
    srv_ssh.close()
    assert ok_ssh is False and "non-socks5-listener" in dtl_ssh and "SSH-2.0" in dtl_ssh, (ok_ssh, dtl_ssh)

    # 2. Start a real SOCKS5 greeting responder (\x05\x00)
    srv_s5 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    srv_s5.bind(("127.0.0.1", 0))
    srv_s5.listen(1)
    s5_port = srv_s5.getsockname()[1]

    def _s5_worker():
        try:
            conn, _ = srv_s5.accept()
            greeting = conn.recv(16)
            if greeting.startswith(b"\x05"):
                conn.sendall(b"\x05\x00")
            conn.close()
        except Exception:
            pass

    t2 = threading.Thread(target=_s5_worker, daemon=True)
    t2.start()
    ok_s5, dtl_s5 = w_mod._probe_socks5_greeting(s5_port)
    srv_s5.close()
    assert ok_s5 is True and "socks5-ok" in dtl_s5, (ok_s5, dtl_s5)
    print("PASS test_02_socks5_greeting_probe_catches_ssh_local_forward_impostor")


def test_03_preflight_blocked_record_distinct_from_failed_and_full_report():
    """61162 Req 2, 3, 4: When preflight blocks in prompt-runner, JSONL & summary record status='PREFLIGHT_BLOCKED'
    with missing item names and detailed cause (never bare 'preflight failed'), and round stops immediately with exit 2."""
    with tempfile.TemporaryDirectory() as td:
        tdir = Path(td)
        prof_root = tdir / "local-profiles"
        (prof_root / "ai-8" / "Default").mkdir(parents=True)
        (prof_root / "ai-8" / "Default" / "Cookies").write_bytes(b"SQLite format 3\x00cookie_data")
        (prof_root / "ai-9" / "Default").mkdir(parents=True)
        jsonl_file = tdir / "records.jsonl"
        pf_jsonl = tdir / "preflight_report.jsonl"
        summary_file = tdir / "summary.log"

        old_fetch = p_mod.fetch_prompt_for_number
        old_pf = p_mod.run_watcher_preflight
        old_pf_env = os.environ.get("PREFLIGHT_REPORT_JSONL")
        try:
            os.environ["PREFLIGHT_REPORT_JSONL"] = str(pf_jsonl)
            p_mod.fetch_prompt_for_number = lambda n, base_url=None, timeout=15.0: {
                "ok": True,
                "status": 200,
                "url": f"http://149.118.48.126:8080/PROMPT-A{n}.txt",
                "text": "<entry_pass>test</entry_pass>\n",
                "bytes": 30,
                "sha256": "a" * 64,
                "reason": "OK",
            }
            # Force xdotool_executable and shared_libraries_ldd to fail while calling real run_watcher_preflight
            old_xdo = p_mod._preflight_check_xdotool_executable
            old_ldd = p_mod._preflight_check_shared_libraries_ldd
            old_tun = p_mod._preflight_check_server_tunnel_forwards
            old_dir = p_mod._preflight_check_server_direct_carrier
            old_dsp = p_mod._preflight_check_display
            old_pw = p_mod._preflight_check_playwright_chromium
            old_rot = p_mod._preflight_check_server_rotation_json
            old_dsk = p_mod._preflight_check_disk_space
            try:
                p_mod._preflight_check_xdotool_executable = lambda sid: (
                    False,
                    "xdotool-exec-failed(path=/usr/bin/xdotool, rc=127, stderr='libxdo.so.3: cannot open shared object file')",
                )
                p_mod._preflight_check_shared_libraries_ldd = lambda sid: (
                    False,
                    "shared-lib-not-found(xdotool: libxdo.so.3 => not found | LD_LIBRARY_PATH='')",
                )
                p_mod._preflight_check_server_tunnel_forwards = lambda sid: (True, "ready=(11080,)")
                p_mod._preflight_check_server_direct_carrier = lambda sid: (True, "port=11090 exit_ip=149.118.48.126")
                p_mod._preflight_check_display = lambda sid: (True, "DISPLAY=:98")
                p_mod._preflight_check_playwright_chromium = lambda sid: (True, "playwright=1.64.0 chromium_rev=1248")
                p_mod._preflight_check_server_rotation_json = lambda sid: (True, "non-rotation-seat")
                p_mod._preflight_check_disk_space = lambda sid, *a, **kw: (True, "ramdisk_free=1000000000")

                rc, rows, _ = p_mod.run_prompt_runner(
                    profiles_root=prof_root,
                    only_numbers=[8, 9],
                    summary_log_path=summary_file,
                    jsonl_path=jsonl_file,
                )
                assert rc == 2, f"Expected exit code 2 on preflight block, got {rc}"
                assert len(rows) == 1, f"Must stop immediately on first preflight block (ai-8) and not run ai-9! Got {len(rows)} rows"
                row = rows[0]
                assert row["status"] == "PREFLIGHT_BLOCKED", f"Status must be PREFLIGHT_BLOCKED, got {row['status']}"
                assert "起手配套阻擋(xdotool_executable,shared_libraries_ldd)" == row["result"], row["result"]
                assert "libxdo.so.3" in row["reason"], row["reason"]
                assert row["preflight_failed_items"] == ["xdotool_executable", "shared_libraries_ldd"], row

                # Verify preflight_report.jsonl was written with 0600 and full check details
                assert pf_jsonl.is_file()
                assert stat.S_IMODE(pf_jsonl.lstat().st_mode) == 0o600
                pf_rec = json.loads(pf_jsonl.read_text(encoding="utf-8").splitlines()[-1])
                assert pf_rec["status"] == "PREFLIGHT_BLOCKED"
                assert pf_rec["failed_items"] == ["xdotool_executable", "shared_libraries_ldd"]
                assert "method" in pf_rec["checks"]["xdotool_executable"]
                assert "expected" in pf_rec["checks"]["xdotool_executable"]
                assert "libxdo.so.3" in pf_rec["checks"]["xdotool_executable"]["actual"]

                # Verify summary log explicitly shows PREFLIGHT_BLOCKED=1 and FAILED=0
                sum_txt = summary_file.read_text(encoding="utf-8")
                assert "FAILED=0 | PREFLIGHT_BLOCKED=1" in sum_txt, sum_txt
            finally:
                p_mod._preflight_check_xdotool_executable = old_xdo
                p_mod._preflight_check_shared_libraries_ldd = old_ldd
                p_mod._preflight_check_server_tunnel_forwards = old_tun
                p_mod._preflight_check_server_direct_carrier = old_dir
                p_mod._preflight_check_display = old_dsp
                p_mod._preflight_check_playwright_chromium = old_pw
                p_mod._preflight_check_server_rotation_json = old_rot
                p_mod._preflight_check_disk_space = old_dsk
        finally:
            p_mod.fetch_prompt_for_number = old_fetch
            p_mod.run_watcher_preflight = old_pf
            if old_pf_env is None:
                os.environ.pop("PREFLIGHT_REPORT_JSONL", None)
            else:
                os.environ["PREFLIGHT_REPORT_JSONL"] = old_pf_env
    print("PASS test_03_preflight_blocked_record_distinct_from_failed_and_full_report")


def test_04_prompt_runner_input_verify_80464_vs_80463_blocker_2():
    """61161 Blocker ②: PROMPT-A8.txt (80,463 chars ending in '\\n') read back from contenteditable innerText
    as 80,464 chars (trailing <br> -> extra '\\n') or with ZWSP must PASS when all 80,462 body chars match,
    and FAIL CLOSED if any real character is missing or altered."""
    prefix = "<entry_pass slot=\"A8\" version=\"10.7\">\n"
    suffix = "\n</terminator>\n</entry_pass>"
    body_80462 = prefix + ("X" * (80462 - len(prefix) - len(suffix))) + suffix
    prompt_80463 = body_80462 + "\n"
    assert len(prompt_80463) == 80463

    # Case A: Chromium contenteditable innerText adds 1 trailing newline -> 80,464 chars
    box_80464 = prompt_80463 + "\n"
    assert len(box_80464) == 80464
    ok_a, dtl_a = p_mod.verify_input_box_content(box_80464, prompt_80463)
    assert ok_a is True, f"80464 vs 80463 trailing newline must PASS, got: {(ok_a, dtl_a)}"
    assert "len=80463,raw_actual=80464,trailing_nl_diff=+1" in dtl_a, dtl_a

    # Case B: Chromium contenteditable strips trailing newline -> 80,462 chars
    ok_b, dtl_b = p_mod.verify_input_box_content(body_80462, prompt_80463)
    assert ok_b is True, f"80462 vs 80463 stripped trailing newline must PASS, got: {(ok_b, dtl_b)}"
    assert "trailing_nl_diff=-1" in dtl_b, dtl_b

    # Case C: ProseMirror injects zero-width space \u200b + trailing newline
    ok_c, dtl_c = p_mod.verify_input_box_content(prompt_80463 + "\u200b\n", prompt_80463)
    assert ok_c is True, f"ZWSP + trailing newline must PASS, got: {(ok_c, dtl_c)}"

    # Case D: Real 1-character truncation (missing '>' at the end of </entry_pass>) -> MUST FAIL CLOSED!
    truncated_real = body_80462[:-1] + "\n"
    assert len(truncated_real) == 80462
    ok_d, dtl_d = p_mod.verify_input_box_content(truncated_real, prompt_80463)
    assert ok_d is False and "length_mismatch" in dtl_d, f"Real truncation must FAIL CLOSED, got: {(ok_d, dtl_d)}"

    # Case E: Real 1-character extra non-newline char -> MUST FAIL CLOSED!
    extra_real = prompt_80463 + "Z"
    assert len(extra_real) == 80464
    ok_e, dtl_e = p_mod.verify_input_box_content(extra_real, prompt_80463)
    assert ok_e is False and "length_mismatch(actual=80464,expected=80463)" in dtl_e, (ok_e, dtl_e)
    print("PASS test_04_prompt_runner_input_verify_80464_vs_80463_blocker_2")


def test_05_watcher_post_send_confirm_readback_and_unconfirmed_hold_blocker_3():
    """61161 Blocker ③: After pressing Enter in watcher._do_send_once, if pre-send locator inp
    throws TimeoutError (because composer toggled contenteditable='false' during streaming) and
    body.inner_text times out on attempt 1, _box_text and _read_body_text_robust still read back
    the cleared input box and updated body via fallback and confirm ACK (True) instead of UNCONFIRMED HOLD."""

    class StaleAfterSendInput:
        def __init__(self, page):
            self.page = page
            self.sent = False

        def evaluate(self, js, *a, **kw):
            if "e.click()" in js:
                return None
            if self.sent:
                raise TimeoutError("Locator('[contenteditable=\"true\"]').first timed out because contenteditable became false")
            return ""

        def fill(self, val):
            pass

        def input_value(self, timeout=None):
            raise RuntimeError("Node is not an <input>, <textarea> or <select> element")

        def inner_text(self, timeout=None):
            if self.sent:
                raise TimeoutError("Locator('[contenteditable=\"true\"]').first timed out after send")
            return ""

        def text_content(self, timeout=None):
            if self.sent:
                raise TimeoutError("Locator('[contenteditable=\"true\"]').first timed out after send")
            return ""

    class StreamingPage:
        def __init__(self):
            self.inp = StaleAfterSendInput(self)
            self.body_text = "Previous conversation history\n"
            self.inner_text_calls = 0

            class _Keyboard:
                def __init__(self, outer):
                    self.outer = outer

                def type(self, msg, delay=0):
                    self.outer.typed_msg = msg

                def press(self, key):
                    if key == "Enter":
                        self.outer.inp.sent = True
                        self.outer.body_text += f"\nUser: {self.outer.typed_msg}\nAssistant: streaming..."

            self.keyboard = _Keyboard(self)

        def locator(self, sel):
            outer = self
            if sel == "body":
                class _BodyLoc:
                    def inner_text(self, timeout=None):
                        outer.inner_text_calls += 1
                        # Simulate body.inner_text timing out during post-send streaming layout
                        if outer.inp.sent:
                            raise TimeoutError("locator('body').inner_text timed out during streaming layout")
                        return outer.body_text

                    def text_content(self, timeout=None):
                        return outer.body_text
                return _BodyLoc()

            class _EmptyLoc:
                def count(self):
                    return 0

                @property
                def last(self):
                    return self

                @property
                def first(self):
                    return self
            return _EmptyLoc()

        def evaluate(self, js, *a, **kw):
            if "document.querySelectorAll" in js:
                # Composer was cleared and switched to [contenteditable="false"][role="textbox"]
                return ""
            if "document.body" in js:
                return self.body_text
            return None

        def wait_for_timeout(self, ms):
            pass

        def screenshot(self, **kw):
            pass

    old_find = w_mod.find_input_box
    old_gate = w_mod.ca_checkbox_gate
    old_cookie = w_mod._dismiss_cookie_consent
    old_url_guard = w_mod.ensure_rotation_url
    old_mark = w_mod._mark_session_pushed
    old_state_path = w_mod._RECALL_STATE_PATH
    try:
        with tempfile.TemporaryDirectory() as td:
            w_mod._RECALL_STATE_PATH = str(Path(td) / "watcher.recall.state")
            w_mod._recall_counter = 2147483647
            w_mod._pending_num = None
            w_mod._recall_unconfirmed_hold = False
            w_mod._recall_hold_baseline = None

            fake_page = StreamingPage()
            w_mod.find_input_box = lambda pg, sid: fake_page.inp if not fake_page.inp.sent else None
            w_mod.ca_checkbox_gate = lambda pg, sid, lbl: True
            w_mod._dismiss_cookie_consent = lambda pg, sid, timeout_ms=2000: False
            w_mod.ensure_rotation_url = lambda pg, sid: True
            w_mod._mark_session_pushed = lambda sid, page=None: None

            res = w_mod._do_send_once(fake_page, "A8")
            assert res is True, f"Expected deterministic ACK True (not UNCONFIRMED), got: {res}"
            assert w_mod._recall_unconfirmed_hold is False
            assert w_mod._recall_counter == 2147483646, w_mod._recall_counter

            # Also verify recovery when watcher.recall.state had hold=True from 61161 run
            w_mod._pending_num = 2147483646
            w_mod._recall_unconfirmed_hold = True
            w_mod._recall_hold_baseline = None
            fake_page.body_text += "\nUser: Continue SESSION 2147483646\n"
            res_hold = w_mod._do_send_once(fake_page, "A8")
            assert res_hold == "HOLD_RESOLVED", f"Expected HOLD_RESOLVED when pending message is in body and box is empty, got {res_hold}"
            assert w_mod._recall_unconfirmed_hold is False
            assert w_mod._recall_counter == 2147483645
    finally:
        w_mod.find_input_box = old_find
        w_mod.ca_checkbox_gate = old_gate
        w_mod._dismiss_cookie_consent = old_cookie
        w_mod.ensure_rotation_url = old_url_guard
        w_mod._mark_session_pushed = old_mark
        w_mod._RECALL_STATE_PATH = old_state_path
    print("PASS test_05_watcher_post_send_confirm_readback_and_unconfirmed_hold_blocker_3")




def test_06_prompt_runner_cli_missing_profiles_dir_still_runs_preflight_and_exits_2():
    """61177 + A16 PR1: When local-profiles directory does not exist, CLI run_prompt_runner must still execute
    run_watcher_preflight, write 0600 preflight_report.jsonl + canonical PREFLIGHT_BLOCKED row, and exit 2."""
    import json, os, subprocess, sys, tempfile
    script_path = Path(os.environ.get("OVERRIDE_PROMPT_RUNNER_PY") or (KIT_DIR / "scripts" / "prompt-runner.py"))
    with tempfile.TemporaryDirectory() as td:
        td_p = Path(td)
        fake_home = td_p / "home"
        missing_prof = td_p / "nonexistent_local_profiles"
        rec_jsonl = td_p / "logs" / "records.jsonl"
        sum_log = td_p / "logs" / "summary.log"
        env = dict(os.environ)
        env["HOME"] = str(fake_home)
        p = subprocess.run(
            [
                sys.executable, "-B", str(script_path),
                "--profiles-dir", str(missing_prof),
                "--records-jsonl", str(rec_jsonl),
                "--summary-log", str(sum_log),
            ],
            env=env, capture_output=True, text=True, timeout=15,
        )
        assert p.returncode == 2, f"expected rc=2, got {p.returncode}: {p.stdout} {p.stderr}"
        assert "Traceback" not in (p.stdout + p.stderr), f"unexpected traceback: {p.stderr}"
        pf_jsonl = fake_home / "workspace" / "arena-system" / "logs" / "preflight_report.jsonl"
        assert pf_jsonl.is_file() and pf_jsonl.stat().st_size > 0, "preflight_report.jsonl must be written even when local-profiles is missing"
        rows = [json.loads(line) for line in rec_jsonl.read_text(encoding="utf-8").splitlines() if line.strip()]
        assert len(rows) == 1 and rows[0]["status"] == "PREFLIGHT_BLOCKED", f"expected PREFLIGHT_BLOCKED row, got {rows}"
    print("PASS test_06_prompt_runner_cli_missing_profiles_dir_still_runs_preflight_and_exits_2")


def test_07_watcher_cli_preflight_only_without_seat_arg_exits_2_fast():
    """A16 W1: `python3 scripts/watcher.py --preflight-only` (no positional seat) must run preflight and exit 2 fast,
    never entering infinite coordinator loop."""
    import json, os, subprocess, sys, tempfile
    script_path = Path(os.environ.get("OVERRIDE_WATCHER_PY") or (KIT_DIR / "scripts" / "watcher.py"))
    with tempfile.TemporaryDirectory() as td:
        fake_home = Path(td) / "home"
        env = dict(os.environ)
        env["HOME"] = str(fake_home)
        proc = subprocess.Popen(
            [sys.executable, "-B", str(script_path), "--preflight-only"],
            env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
        )
        try:
            out, err = proc.communicate(timeout=6)
        except subprocess.TimeoutExpired:
            proc.kill()
            proc.communicate()
            raise AssertionError("watcher.py --preflight-only hung >6s instead of exiting 2 fast")
        class _P: pass
        p = _P(); p.returncode, p.stdout, p.stderr = proc.returncode, out, err
        assert p.returncode == 2, f"expected rc=2, got {p.returncode}: {p.stdout} {p.stderr}"
        pf_jsonl = fake_home / "workspace" / "arena-system" / "logs" / "preflight_report.jsonl"
        assert pf_jsonl.is_file() and pf_jsonl.stat().st_size > 0, "watcher --preflight-only must write preflight_report.jsonl"
    print("PASS test_07_watcher_cli_preflight_only_without_seat_arg_exits_2_fast")


def test_08_watcher_cli_coordinator_halts_exit_2_with_preflight_report_when_playwright_missing():
    """A16 W2: Default `python3 scripts/watcher.py` coordinator startup must execute run_watcher_preflight BEFORE
    `from playwright.sync_api import sync_playwright`, write preflight_report.jsonl, and halt coordinator with exit 2."""
    import json, os, subprocess, sys, tempfile
    script_path = Path(os.environ.get("OVERRIDE_WATCHER_PY") or (KIT_DIR / "scripts" / "watcher.py"))
    with tempfile.TemporaryDirectory() as td:
        fake_home = Path(td) / "home"
        env = dict(os.environ)
        env["HOME"] = str(fake_home)
        proc = subprocess.Popen(
            [sys.executable, "-B", str(script_path)],
            env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
        )
        try:
            out, err = proc.communicate(timeout=6)
        except subprocess.TimeoutExpired:
            proc.kill()
            proc.communicate()
            raise AssertionError("watcher.py default coordinator hung >6s in loop instead of preflight exit 2")
        class _P: pass
        p = _P(); p.returncode, p.stdout, p.stderr = proc.returncode, out, err
        assert p.returncode == 2, f"expected coordinator halt rc=2, got {p.returncode}: {p.stdout}"
        pf_jsonl = fake_home / "workspace" / "arena-system" / "logs" / "preflight_report.jsonl"
        assert pf_jsonl.is_file() and pf_jsonl.stat().st_size > 0, "coordinator preflight block must write preflight_report.jsonl"
    print("PASS test_08_watcher_cli_coordinator_halts_exit_2_with_preflight_report_when_playwright_missing")



import unittest as _unittest
class TestR13V1065PreflightAndSendConfirm61162(_unittest.TestCase):
    def test_01_xdotool_must_actually_execute_not_just_exist_and_ldd_check_case(self):
        test_01_xdotool_must_actually_execute_not_just_exist_and_ldd_check()
    def test_02_socks5_greeting_probe_catches_ssh_local_forward_impostor_case(self):
        test_02_socks5_greeting_probe_catches_ssh_local_forward_impostor()
    def test_03_preflight_blocked_record_distinct_from_failed_and_full_report_case(self):
        test_03_preflight_blocked_record_distinct_from_failed_and_full_report()
    def test_04_prompt_runner_input_verify_80464_vs_80463_blocker_2_case(self):
        test_04_prompt_runner_input_verify_80464_vs_80463_blocker_2()
    def test_05_watcher_post_send_confirm_readback_and_unconfirmed_hold_blocker_3_case(self):
        test_05_watcher_post_send_confirm_readback_and_unconfirmed_hold_blocker_3()
    def test_06_prompt_runner_cli_missing_profiles_dir_still_runs_preflight_and_exits_2_case(self):
        test_06_prompt_runner_cli_missing_profiles_dir_still_runs_preflight_and_exits_2()
    def test_07_watcher_cli_preflight_only_without_seat_arg_exits_2_fast_case(self):
        test_07_watcher_cli_preflight_only_without_seat_arg_exits_2_fast()
    def test_08_watcher_cli_coordinator_halts_exit_2_with_preflight_report_when_playwright_missing_case(self):
        test_08_watcher_cli_coordinator_halts_exit_2_with_preflight_report_when_playwright_missing()

if __name__ == "__main__":
    test_01_xdotool_must_actually_execute_not_just_exist_and_ldd_check()
    test_02_socks5_greeting_probe_catches_ssh_local_forward_impostor()
    test_03_preflight_blocked_record_distinct_from_failed_and_full_report()
    test_04_prompt_runner_input_verify_80464_vs_80463_blocker_2()
    test_05_watcher_post_send_confirm_readback_and_unconfirmed_hold_blocker_3()
    test_06_prompt_runner_cli_missing_profiles_dir_still_runs_preflight_and_exits_2()
    test_07_watcher_cli_preflight_only_without_seat_arg_exits_2_fast()
    test_08_watcher_cli_coordinator_halts_exit_2_with_preflight_report_when_playwright_missing()
    print("ALL 8/8 NEWBIE KIT V18.3 (61161 + 61162 + 61163 + 61177) TESTS PASSED!")
