#!/usr/bin/env python3
# BASE_TARGET_V094: http://149.118.48.126:8080/persistent/scripts/watcher.py (67,160B | 1,477L | md5=cb11d45f639722650e3ebe156897da51 | sha256=b634251dc94632819cd7e1d69c8b90a2fe9f052a56df11b8b40328a066f111e2 | measured_at=2026-10-06T11:36:00Z UTC)
# BASE_ROOT_8080  : http://149.118.48.126:8080/watcher.py                    (98,817B | 2,076L | md5=061d30f394370bec763ac6b063239042 | sha256=511f528458ab405a0234c857392e81d201c2b99476141ee52e272d34f8e47b25 | measured_at=2026-10-19T00:20:00Z UTC)
# BASE_R10_REV2   : https://paste.c-net.org/SocietyAngelus                   (295,640B | 5,741L | md5=5783180267c7ceb297cee43c0c10e6ce | sha256=96f3be5f882debfc09015cb9bf97e6b5a2681f9f5eb3e4c53647cf7d4ac6157c | measured_at=2026-10-18T17:10:00Z UTC)
# BASE_R11_A65    : SwannPresley on SocietyAngelus                           (292,157B | 5,719L | md5=e0fcc0bede831f1afbf47ce992a38d2d | sha256=92fdafa04aa302684e62b2c4bb52dae024e41d28edf7313bbc9f3faa67b4746a | measured_at=2026-10-19T00:20:00Z UTC)
# SPEC_V3_3_PIN   : watcher-url-rotation-spec-v3.3.txt                       (29,999B | 328L | md5=086d1debba34ca92b1640ef7d6177326 | sha256=43746d5fd5245f47fddba4b9c9ad8df32cfdeb63b3e9ac06490abfbd00d048b3 | measured_at=2026-10-06T11:36:00Z UTC)
"""
Arena 持久 DOM Watcher - 陣列式多席位系統（council-p2 r10：59641 #1-#7 + 59651/59654 #8 Google 登入自動補密碼 + 59663 --password-store=basic + 59672 last-profile 記錄 + 59754/59758 DAILY_LIMIT 自動轉同 Profile 另一 URL + F23/F35 縱深防禦）
- 內建 Coordinator（--coordinator / --all，rotation-coordinator.sh 退役）
- 每席位 K 個 Google 號（PROFILE_K），每號綁 U 條 URL（動態由 JSON 讀取，唔寫死）
- 種／運行分離：persistent workshop/profiles 唯讀種 → tmpfs ramdisk（全程最多 1 個運行中 profile，收工即清；三層縱深防禦）
- 完整流程：CP 種→ramdisk → 開 1 個 headed browser → 跑推 cycle → 跑完／自停／例外 → 閂 browser → 清 ramdisk profile → 寫 turn → 下一輪
- DAILY_LIMIT 自動換 URL（59754＋59758 覆寫舊規）：推完 reload 兩次後若無 Stop 掣又無 Keep working 掣，即呼叫 `_mark_daily_limit_hit(sid, "no_stop_no_keepworking_after_push")` 並回傳 `DAILY_LIMIT`；觸發 `DAILY_LIMIT` 時按 URL 粒度（`daily_limit_urls`）標記當前 URL，優先自動轉去**同一個 Profile 綁住嘅另一條未耗盡 URL**（`same_profile_next_url`），只有當該 Profile 名下全部 URL 今日皆觸發 `DAILY_LIMIT` 時先至標記該 Profile 今日收工並轉去下一個 Profile，全部 URL 皆耗盡時先結束本席今日輪次（兼容 K×U 如 5×2 或 1×10 任何 JSON 形狀）
- VPN 採用 Fix 2（24 個 ws-* profile round-robin headless 取 IP + 推圖 browser --disable-extensions）
- Google 登入自動補密碼（59651 #8 ＋ 59654 修訂）：Google session 過期出現 input[type="password"] 時，讀取與種目錄同位之 `.google-pw`（權限 600）→ 填密碼（絕不寫入 log，僅記「已自動填密碼」）→ 撳 Next → 等登入完成 → 繼續原流程；若自動補密碼失敗（密碼錯／彈驗證碼／其他異常）：唔好停、唔好 retry loop，上報（profile＋原因＋時間）後直接 pass 去下一個 profile 繼續推
- 跨機登入態保護（59663）：所有起 Chrome 路徑一律加 `--password-store=basic`，確保 server→workshop→ramdisk 跨機複製後 cookies/登入態完整有效
- SLOT 推完即記 Profile ID＋上報中央推播狀態 API（59672＋59680/59682）：每次成功推完一個 SLOT 即時寫入 `{state_dir}/<slot>-last-profile.txt`（純文字單行 profile ID 如 `ai-53`，唔包 JSON，唔受 rotation 影響），並同步 `POST http://149.118.48.126:8080/push-status/report`（`{"machine": ..., "slot": ..., "profile": ..., "url": ...}`）

用法:
  watcher.py <席位ID> [--once]
  watcher.py --coordinator [--once]
"""
import re
import sys
import os
import time
import json
from pathlib import Path

# 配置
SYSTEM_DIR = Path.home() / "workspace" / "arena-system"
SEATS_CONF = SYSTEM_DIR / "seats.conf"
VPN_CONF = Path.home() / "workspace" / "vpn-tunnel" / "vpn-proxies.conf"
PROFILES_DIR = Path.home() / "workspace" / "arena-system" / "local-profiles"  # 直接用 workspace，唔用 RAM（owner 2026-10-05）

# v0.93: CA 兩套 checkbox 完整跟足（owner 2026-10-05 15:38 下令）
# 第1套（橙色）：檢測 (527,409) #f6821f → 點擊 (270,420)
# 第2套（藍色 Cloudflare）：檢測 (910,420) 200x60 #1A73E8 → 點擊 (276,425)
# v0.93 第三套（紫色）
PURPLE_CHECK_X = 715
PURPLE_CHECK_Y = 415
PURPLE_CHECK_COLOR = "#f3e9f7"
PURPLE_CLICK_X = 580
PURPLE_CLICK_Y = 605

ORANGE_CHECK_X = 527
ORANGE_CHECK_Y = 409
ORANGE_CHECK_COLOR = '#f6821f'
ORANGE_CLICK_X = 270
ORANGE_CLICK_Y = 420
BLUE_CHECK_X = 910
BLUE_CHECK_Y = 420
BLUE_CHECK_W = 200
BLUE_CHECK_H = 60
BLUE_CHECK_COLOR = '#1A73E8'
BLUE_CLICK_X = 276
BLUE_CLICK_Y = 425
MASTER_PROFILES_DIR = SYSTEM_DIR / "profiles"  # 只讀 master
LOGS_DIR = SYSTEM_DIR / "logs"
RECALL_MSG = "Continue SESSION 2147483647"
RECALL_BASE = 2147483647  # 固定起始數字（owner 2026-10-04 14:58 HKT：每次推減1，重啟重置）
_recall_counter = RECALL_BASE  # 內存計數器，重啟 watcher 即重置
_last_sent_num = None  # 上次實際發出嘅數字（畀精準驗證用）

_pending_num = None  # 已打字、未經 ACK 確認嘅號（A6/8874②：要 ACK 才扣）
_recall_unconfirmed_hold = False  # 出現過 UNCONFIRMED ⇒ HOLD，唔自動重試（A7/8926、A7/8933）
_recall_hold_baseline = None  # 設 HOLD 嗰刻 body 內 pending 句嘅出現次數（讀唔到＝None）；自解要「多過基線」

def _needle_re(num):
    """pending 句嘅嚴格 pattern：右邊唔可以再跟數字（免 2147483647 撞 2147483646x）。"""
    return re.compile(rf"Continue SESSION {num}(?!\d)")

def _needle_count(text, num):
    """text 內 pending 句嘅出現次數；**text 係 None（讀唔到）⇒ 回 None**，唔可以用 0 代替。"""
    if text is None:
        return None
    return len(_needle_re(num).findall(text))

def _needle_in(text, num):
    """text 內有冇 pending 句；text 係 None（讀唔到）⇒ 回 None（＝未確認）。"""
    if text is None:
        return None
    return _needle_re(num).search(text) is not None

def get_recall_msg():
    """peek：攞下一條召回句，但**唔扣號**（A6/8850③＋A7/8852＋A4/8853 三方驗證）。"""
    global _pending_num
    _pending_num = _recall_counter
    return f"Continue SESSION {_recall_counter}"

def recall_ack_ok(body_before, body_after, box_after, num):
    """確定性 ACK（三態）：三個來源讀唔到任何一個（None）⇒ 回 None＝UNCONFIRMED，
    唔可以當 False 就重試、亦唔可以當 True 就扣號（A4/8924、A7/8926、A7/8928）。
    True：body 內 exact 句真係多過送出前 **且** 輸入框讀得到、而且已經冇 needle。
    False：三個都讀得到，但未確認送出（NO_ACK）。"""
    if body_before is None or body_after is None or box_after is None:
        return None
    if _needle_in(box_after, num):
        return False
    return _needle_count(body_after, num) > _needle_count(body_before, num)

def _box_text(inp):
    """輸入框現時嘅字；**兩條路都讀唔到＝None（＝未確認）**，唔可以當「已清空」（A4/8903、A7/8906）。"""
    for meth in ("input_value", "inner_text"):
        try:
            v = getattr(inp, meth)(timeout=1000)
            if v is not None:
                return v
        except Exception:
            continue
    return None

def commit_recall_sent():
    """**只喺 ACK 成功之後**叫：記錄實際發出嘅號並扣 1（零守：唔會變負）。"""
    global _recall_counter, _last_sent_num
    if _pending_num is None:
        return
    _last_sent_num = _pending_num
    if _recall_counter > 0:
        _recall_counter -= 1

_RECALL_STATE_PATH = os.environ.get("RECALL_STATE_PATH") or str(
    Path(globals().get("__file__", "watcher.py")).resolve().with_name("watcher.recall.state"))
_recall_commit_seen = 0  # 已套用嘅 commit_seq（防重複 commit）

def _recall_state_default():
    return {"v": 1, "pending": None, "hold": False, "baseline": None,
            "resolved": "none", "commit_seq": 0, "evidence_sha256": None, "audit_ts": None,
            "counter": None}

def _recall_state_load():
    """讀 state 檔；**缺檔＝正常（預設＋True）**；壞檔／讀唔到＝（預設＋False）⇒ caller 要當 HOLD（fail-closed）。"""
    try:
        with open(_RECALL_STATE_PATH, "r", encoding="utf-8") as f:
            st = json.load(f)
        if not isinstance(st, dict) or st.get("v") != 1:
            return _recall_state_default(), False
        return st, True
    except FileNotFoundError:
        return _recall_state_default(), True
    except Exception:
        return _recall_state_default(), False

def _recall_state_save(st):
    """原子寫：temp → fsync → os.replace；失敗＝False（caller 唔可以當成功）。"""
    tmp = _RECALL_STATE_PATH + ".tmp"
    try:
        with open(tmp, "w", encoding="utf-8") as f:
            f.write(json.dumps(st, ensure_ascii=False))
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp, _RECALL_STATE_PATH)
        return True
    except Exception:
        return False

def _recall_state_mark_hold():
    """UNCONFIRMED ⇒ 記低 pending／baseline／hold（跨 restart 保留）。"""
    st, ok = _recall_state_load()
    if not ok:
        return False
    st.update(pending=_pending_num, hold=True, baseline=_recall_hold_baseline, resolved="none",
              counter=_recall_counter)  # v6.6：計數器一齊落，跨 restart 重試先至真係同一個號
    return _recall_state_save(st)

def _recall_state_clear():
    """ACK 確認／HOLD 自解 ⇒ 清 pending／hold（state 同記憶同步）。"""
    st, ok = _recall_state_load()
    if not ok:
        return False
    st.update(pending=None, hold=False, baseline=None, resolved="none", counter=_recall_counter)
    return _recall_state_save(st)

def _recall_state_apply(sid):
    """每個 cycle 開頭叫：讀 state（HOLD／pending／baseline 跨 restart 保留）＋套用人手 reconciliation。
    回 False＝state 壞／讀唔到 ⇒ fail-closed（當 HOLD），caller 要停。"""
    global _recall_unconfirmed_hold, _pending_num, _recall_hold_baseline, _recall_commit_seen, _recall_counter
    st, ok = _recall_state_load()
    if not ok:
        log(sid, "⚠️ recall state 讀唔到／壞 ⇒ fail-closed：當 HOLD，零扣零送（要人手）")
        _recall_unconfirmed_hold = True
        return False
    if isinstance(st.get("counter"), int):
        # v6.6：restart 之後由 state 回復計數器（唔再一律 647）——即係「跳返 647」唔再等於重啟
        _recall_counter = st["counter"]
    if st.get("hold"):
        _recall_unconfirmed_hold = True
        if st.get("pending") is not None:
            _pending_num = st["pending"]
        _recall_hold_baseline = st.get("baseline")
    cs = int(st.get("commit_seq") or 0)
    if st.get("resolved") == "sent" and cs > _recall_commit_seen:
        if st.get("pending") is not None:
            _pending_num = st["pending"]
        commit_recall_sent()
        st.update(resolved="none", hold=False, pending=None, baseline=None, commit_seq=cs + 1, counter=_recall_counter)
        if not _recall_state_save(st):
            log(sid, "⚠️ state 寫入失敗（resolved=sent 已套用）——請人手跟進")
        _recall_commit_seen = cs + 1
        _recall_unconfirmed_hold = False
        _recall_hold_baseline = None
        log(sid, f"人手 reconciliation：resolved=sent ⇒ 扣號一次（下一個 {_recall_counter}）")
    elif st.get("resolved") == "not_sent" and cs > _recall_commit_seen:
        st.update(resolved="none", hold=False, commit_seq=cs + 1, counter=_recall_counter)
        if not _recall_state_save(st):
            log(sid, "⚠️ state 寫入失敗（resolved=not_sent 已套用）——請人手跟進")
        _recall_commit_seen = cs + 1
        _recall_unconfirmed_hold = False
        _recall_hold_baseline = None
        log(sid, "人手 reconciliation：resolved=not_sent ⇒ 清 HOLD；pending／號不變（重試仍係同一個號）")
    return True

CHECK_INTERVAL = 30  # 秒


# Owner 60392: watcher-side heartbeat only.  Seeing the square Stop control
# is the authoritative trigger for this local JSON observation; it is not a
# transport fallback and does not modify the council/server architecture.
_WATCHER_HEARTBEAT_EPOCH = f"{time.time_ns()}-{os.getpid()}"
_WATCHER_HEARTBEAT_SEQ = 0
_WATCHER_HEARTBEAT_SLOTS = {}
WATCHER_HEARTBEAT_MAX_BYTES = 262144


def _heartbeat_read_regular_json(path, max_bytes=1048576):
    """Read one small, owner-matching, non-symlink JSON file or return None."""
    import stat as _stat
    p = Path(path)
    try:
        st = os.lstat(p)
        if (not _stat.S_ISREG(st.st_mode) or st.st_uid != os.getuid()
                or st.st_nlink != 1 or st.st_size > int(max_bytes)):
            return None
        with p.open("r", encoding="utf-8") as fh:
            return json.load(fh)
    except Exception:
        return None


def _heartbeat_atomic_write_json(path, payload, mode=0o600):
    """Atomic temp+fsync+replace; never unlink the current heartbeat first."""
    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    raw = (json.dumps(payload, ensure_ascii=False, sort_keys=True,
                      separators=(",", ":")) + "\n").encode("utf-8")
    tmp = target.parent / f".{target.name}.tmp.{os.getpid()}.{time.monotonic_ns()}"
    flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
    if hasattr(os, "O_NOFOLLOW"):
        flags |= os.O_NOFOLLOW
    fd = None
    try:
        fd = os.open(str(tmp), flags, mode)
        os.fchmod(fd, mode)
        view = memoryview(raw)
        while view:
            wrote = os.write(fd, view)
            if wrote <= 0:
                raise OSError("heartbeat short write")
            view = view[wrote:]
        os.fsync(fd)
        os.close(fd)
        fd = None
        os.replace(str(tmp), str(target))
        try:
            dflags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
            dfd = os.open(str(target.parent), dflags)
            try:
                os.fsync(dfd)
            finally:
                os.close(dfd)
        except OSError:
            pass
        return target
    finally:
        if fd is not None:
            try:
                os.close(fd)
            except OSError:
                pass
        try:
            tmp.unlink(missing_ok=True)
        except OSError:
            pass


def _heartbeat_read_cursor(state_dir):
    """Read only bounded cursor files inside the watcher state directory."""
    for name in ("CURSOR", "runner_state.json"):
        p = Path(state_dir) / name
        try:
            if name == "CURSOR":
                import stat as _stat
                st = os.lstat(p)
                if (not _stat.S_ISREG(st.st_mode) or st.st_uid != os.getuid()
                        or st.st_nlink != 1 or st.st_size > 64):
                    continue
                text = p.read_text(encoding="utf-8").strip()
                if text.isdigit():
                    return int(text)
            else:
                obj = _heartbeat_read_regular_json(p, max_bytes=262144)
                val = obj.get("cursor") if isinstance(obj, dict) else None
                if isinstance(val, int) and val >= 0:
                    return val
        except Exception:
            continue
    return None


def _reset_seat_turn_heartbeat(sid):
    key = str(sid or "").strip()
    st = _WATCHER_HEARTBEAT_SLOTS.get(key)
    if st is not None:
        st["turn_started_ts"] = None
        st["checks_this_turn"] = 0


def _record_seat_alive_heartbeat(sid, state_dir=None, relay_cursor=None,
                                 event="stop_button_alive"):
    """Immediately record a bounded local heartbeat after a visible Stop control."""
    global _WATCHER_HEARTBEAT_SEQ
    seat = str(sid or "").strip()
    if not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", seat):
        raise ValueError("invalid heartbeat seat label")
    sdir = Path(state_dir) if state_dir is not None else Path(
        os.environ.get("WATCHER_STATE_DIR") or SYSTEM_DIR)
    sdir.mkdir(parents=True, exist_ok=True)
    now_ts = int(time.time())
    slot_path = sdir / f"{seat}-heartbeat.json"
    st = _WATCHER_HEARTBEAT_SLOTS.get(seat)
    if st is None:
        old = _heartbeat_read_regular_json(slot_path, max_bytes=65536)
        old_seq = old.get("seq", 0) if isinstance(old, dict) else 0
        old_seq = old_seq if isinstance(old_seq, int) and old_seq >= 0 else 0
        st = {"seq": old_seq, "turn_started_ts": None,
              "checks_this_turn": 0, "last_cursor": None}
        _WATCHER_HEARTBEAT_SLOTS[seat] = st
    _WATCHER_HEARTBEAT_SEQ = max(_WATCHER_HEARTBEAT_SEQ + 1,
                                 int(st.get("seq") or 0) + 1)
    st["seq"] = _WATCHER_HEARTBEAT_SEQ
    if st.get("turn_started_ts") is None:
        st["turn_started_ts"] = now_ts
        st["checks_this_turn"] = 0
    st["checks_this_turn"] = int(st.get("checks_this_turn") or 0) + 1
    cursor = relay_cursor if isinstance(relay_cursor, int) else _heartbeat_read_cursor(sdir)
    previous_cursor = st.get("last_cursor")
    advanced = bool(cursor is not None and previous_cursor is not None
                    and cursor > previous_cursor)
    if cursor is not None:
        st["last_cursor"] = cursor
    payload = {
        "schema": "WATCHER_STOP_HEARTBEAT_V1",
        "slot": seat,
        "alive": True,
        "stop_button": True,
        "event": str(event or "stop_button_alive"),
        "seq": _WATCHER_HEARTBEAT_SEQ,
        "watcher_epoch": _WATCHER_HEARTBEAT_EPOCH,
        "checks_this_turn": int(st["checks_this_turn"]),
        "turn_wall_seconds": max(0, now_ts - int(st["turn_started_ts"])),
        "relay_last_known_cursor": cursor,
        "cursor_advanced": advanced,
        "activity_state": "ACTIVE_ADVANCING" if advanced else "ALIVE_STEADY",
        "daily_limit_signal": False,
        "ts": now_ts,
    }
    _heartbeat_atomic_write_json(slot_path, payload)
    aggregate_path = sdir / "heartbeat.json"
    aggregate = _heartbeat_read_regular_json(aggregate_path, max_bytes=1048576)
    if not isinstance(aggregate, dict):
        aggregate = {}
    aggregate[seat] = payload
    _heartbeat_atomic_write_json(aggregate_path, aggregate)
    history = sdir / "heartbeat-history.jsonl"
    try:
        if history.is_file() and history.stat().st_size >= WATCHER_HEARTBEAT_MAX_BYTES:
            os.replace(str(history), str(sdir / "heartbeat-history.jsonl.1"))
        flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
        if hasattr(os, "O_NOFOLLOW"):
            flags |= os.O_NOFOLLOW
        hfd = os.open(str(history), flags, 0o600)
        try:
            line = (json.dumps(payload, ensure_ascii=False, sort_keys=True,
                               separators=(",", ":")) + "\n").encode("utf-8")
            os.write(hfd, line)
            os.fsync(hfd)
        finally:
            os.close(hfd)
    except OSError as exc:
        log(seat, f"[HEARTBEAT:HISTORY-WARN] {type(exc).__name__}")
    return payload


def _is_generating_with_heartbeat(page, sid):
    """Every positive Stop-control check writes JSON before returning True."""
    alive = is_generating(page)
    if alive:
        try:
            hb = _record_seat_alive_heartbeat(sid)
            log(sid, f"💓 [HEARTBEAT] Stop 掣在生，已即時寫 JSON seq={hb['seq']}")
        except Exception as exc:
            log(sid, f"❌ [HEARTBEAT:WRITE-FAIL] {type(exc).__name__}")
    else:
        _reset_seat_turn_heartbeat(sid)
    return alive


def classify_heartbeat_staleness(record, now_ts=None, max_age_sec=180,
                                 watcher_alive=True, pre_exit=False):
    """Keep watcher loss distinct from an explicit yield and silent seat loss."""
    if not watcher_alive or not isinstance(record, dict):
        return "WATCHER_LOSS"
    ts = record.get("ts")
    now = int(time.time() if now_ts is None else now_ts)
    if not isinstance(ts, (int, float)) or now - int(ts) > int(max_age_sec):
        return "WATCHER_LOSS"
    if record.get("alive") is True and record.get("stop_button") is True:
        return "ALIVE"
    return "SELF_YIELD" if pre_exit else "SILENT_LOSS"

# 議會 patch 2026-10-16：連續 N 個 cycle 同一錯誤 → 自動停止（防 while True 無限 wedge 死 coordinator）
# 應 59654 & A13/59657 & 59754：登入失敗唔放入自停集合；同時移除已改為 DAILY_LIMIT 之 ERROR 及無生產源之死枝 HOLD_ERROR
MAX_CONSECUTIVE_SAME_ERROR = 5
_CONSEC_ERROR_RESULTS = ("NO_INPUT", "NO_INPUT_2", "KW_CLICK_ERROR", "UNCONFIRMED")

def load_seats():
    seats = {}
    s_path = (Path(SYSTEM_DIR) / "seats.conf") if ("_DEFAULT_SYSTEM_DIR" in globals() and SYSTEM_DIR != _DEFAULT_SYSTEM_DIR and (Path(SYSTEM_DIR) / "seats.conf").exists()) else SEATS_CONF
    with open(s_path) as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            parts = [p.strip() for p in line.split("|")] if "|" in line else line.split()
            if len(parts) >= 5:
                sid, profile, vpn, url, account = parts[0], parts[1], parts[2], parts[3], parts[4]
                status = parts[5] if len(parts) > 5 else "active"
                seats[sid] = {
                    "profile": profile, "vpn": vpn, "url": url,
                    "account": account, "status": status
                }
    return seats

# Owner 2026-10-20 輪轉新規（dj_host1/60606，R13-masked v10.6.2，baseline: v10.6.1 85cccc1f…）：
# 1. 一席一輪只推一次：任何時間得一席開緊（一隻 browser）；嗰席完成一次推送（ACK 送出）後即刻寫 rotation-turn.txt 交棒下一席，順序行（A2→A3→A4／A5→A6→A7／A8→A9→A10）。
# 2. 生成緊即跳：輪到開某席時若仲喺 relay 生成緊（Stop 掣存在／上一推未完），唔等、唔加推，直接寫 turn 跳下一席。
# 3. 禁連環霸輪：嚴禁單一席位連環推多個 cycle 霸住成輪（移除 SUCCESS_NEXT_CYCLE 同席 continue 及同輪重開 Chrome continue）。
# 4. DAILY_LIMIT 語義不變（跟 profile）：撞限額嗰席標記該 profile 當日收工，即刻閂 browser 照樣交棒下一席。
#
# 議會架構定案 2026-10-17（dj_host1/59641，baseline: council-p1 b77bdedb…）：
# 1. Coordinator 打包入 watcher（單一 Python 程序內建 turn loop，讀 rotation-turn.txt＋rotation-seats.txt，跳過 rotation-paused.txt）
# 2. 每席 5 個 profiles，每個 profile 綁 2 條 URL（由 JSON 定義，動態決定 CP 邊個 profile，絕不寫死）
# 3. 種／運行分離：workshop 目錄存種（persistent disk，永遠唔掂）；運行前由種 CP 去 ramdisk（tmpfs），ramdisk 全程只放當前跑嗰一個 profile
# 4. 流程：CP 種→ramdisk → 開 browser（全程只准一個 headed browser）→ 跑推 cycle → 跑完／自停／例外 → 閂 browser → 清 ramdisk 嗰個 profile → 寫 turn → 下一個 profile
# 5. DAILY_LIMIT 自動轉同 Profile 另一條 URL（59754＋59758 覆寫舊 #5）：推完兩次 reload 無 Stop 無 Keep working 即報 DAILY_LIMIT；觸發 DAILY_LIMIT 時先轉同一個 profile 嘅另一條未耗盡 URL，同 profile 全部 URL 今日耗盡後先轉下一個 profile，絕不停喺度或第一次撞 limit 就收全席一日
# 6. VPN 沿用 Fix 2 由現有 24 個 WS profiles 輪流收割 serverCredentials＋proxy hosts 經 userland chain proxy；push browser 唔 load Windscribe extension；唔起新 WS profile
# 7. council-p1 嘅 5-cycle 自停／turn 交棒／paused 跳過機制全部保留
_ROT_COUNCIL_TURN_FILE = os.path.expanduser("~/workspace/arena-system/rotation-turn.txt")
_ROT_COUNCIL_PAUSED_FILE = os.path.expanduser("~/workspace/arena-system/rotation-paused.txt")
_ROT_COUNCIL_SEATS_FILE = os.path.expanduser("~/workspace/arena-system/rotation-seats.txt")
COORD_ALL_PAUSED_SLEEP_S = int(os.environ.get("WATCHER_COORD_PAUSED_SLEEP_S", "60") or "60")
COORD_TURN_PAUSE_S = float(os.environ.get("WATCHER_COORD_TURN_PAUSE_S", "2") or "2")
# 應 Owner 60606 #1/#2/#3：硬鎖「一席一輪只推一次」與「生成緊即跳下一席」，禁止環境變數設 0 繞過導致單席霸輪
WATCHER_EXIT_TURN_ON_DONE = True
WATCHER_EXIT_TURN_ON_SKIP_GENERATING = True
WATCHER_STRICT_ONE_PUSH_PER_TURN = True
MAX_PUSH_CYCLES_PER_TURN = 1
WATCHER_ADVANCE_URL_ON_TURN_DONE = os.environ.get("WATCHER_ADVANCE_URL_ON_TURN_DONE", "0") == "1"
_MACHINE_SEAT_GROUPS = (
    ("A2", "A3", "A4"),
    ("A5", "A6", "A7"),
    ("A8", "A9", "A10"),
)

def _machine_seat_group_for_sid(sid):
    s = str(sid or "").strip().upper()
    if not s:
        return None
    for grp in _MACHINE_SEAT_GROUPS:
        if s in grp:
            return list(grp)
    return None

def _rot_council_turn_path():
    env_p = os.environ.get("ROTATION_TURN_FILE")
    if env_p:
        return Path(env_p)
    if "SYSTEM_DIR" in globals() and "_DEFAULT_SYSTEM_DIR" in globals() and SYSTEM_DIR != _DEFAULT_SYSTEM_DIR:
        return Path(SYSTEM_DIR) / "rotation-turn.txt"
    return Path(_ROT_COUNCIL_TURN_FILE)

def _rot_council_paused_path():
    env_p = os.environ.get("ROTATION_PAUSED_FILE")
    if env_p:
        return Path(env_p)
    if "SYSTEM_DIR" in globals() and "_DEFAULT_SYSTEM_DIR" in globals() and SYSTEM_DIR != _DEFAULT_SYSTEM_DIR:
        return Path(SYSTEM_DIR) / "rotation-paused.txt"
    return Path(_ROT_COUNCIL_PAUSED_FILE)

def _rot_council_seats_path():
    env_p = os.environ.get("ROTATION_SEATS_FILE")
    if env_p:
        return Path(env_p)
    if "SYSTEM_DIR" in globals() and "_DEFAULT_SYSTEM_DIR" in globals() and SYSTEM_DIR != _DEFAULT_SYSTEM_DIR:
        return Path(SYSTEM_DIR) / "rotation-seats.txt"
    return Path(_ROT_COUNCIL_SEATS_FILE)

def _rot_council_load_seats(default_fallback=False, hint_sid=None):
    sp = _rot_council_seats_path()
    try:
        if sp.is_file():
            seats = [l.strip().upper() for l in sp.read_text(encoding="utf-8", errors="ignore").splitlines() if l.strip() and not l.strip().startswith("#")]
            if seats:
                return seats
    except Exception:
        pass
    if default_fallback:
        try:
            loaded = load_seats()
            active = [k.upper() for k, v in loaded.items() if v.get("status") == "active"]
            if len(active) >= 2:
                return active
            if len(active) == 1:
                grp = _machine_seat_group_for_sid(hint_sid or active[0])
                if grp:
                    return grp
                return active
        except Exception:
            pass
        grp = _machine_seat_group_for_sid(hint_sid)
        if grp:
            return grp
        return ["A2", "A3", "A4"]
    return []

def _rot_council_get_paused():
    pp = _rot_council_paused_path()
    try:
        if pp.is_file():
            return [l.strip().upper() for l in pp.read_text(encoding="utf-8", errors="ignore").splitlines() if l.strip() and not l.strip().startswith("#")]
    except Exception:
        pass
    return []

def _rot_council_next_seat(sid, seats=None, paused=None):
    """給定當前席位 sid，按 rotation-seats.txt／本機席位組順序（A2→A3→A4／A5→A6→A7／A8→A9→A10）搵下一隻未喺 rotation-paused.txt 嘅席位；全部暫停回 None。"""
    seats_list = list(seats) if seats is not None else _rot_council_load_seats(default_fallback=True, hint_sid=sid)
    if not seats_list:
        return None
    paused_set = set(paused if paused is not None else _rot_council_get_paused())
    cur = str(sid or "").strip().upper()
    try:
        idx = seats_list.index(cur)
    except ValueError:
        idx = -1
    for i in range(1, len(seats_list) + 1):
        cand = seats_list[(idx + i) % len(seats_list)]
        if cand not in paused_set:
            return cand
    return None

def _rot_council_read_turn(seats=None, hint_sid=None):
    """讀取 rotation-turn.txt；若檔案唔存在或席位唔喺清單，初始化為第一隻席位並寫入。"""
    seats_list = list(seats) if seats is not None else _rot_council_load_seats(default_fallback=True, hint_sid=hint_sid)
    tp = _rot_council_turn_path()
    cur = ""
    try:
        if tp.is_file():
            cur = tp.read_text(encoding="utf-8", errors="ignore").strip().upper()
    except Exception:
        cur = ""
    if seats_list and cur not in seats_list:
        cur = seats_list[0]
        try:
            tp.parent.mkdir(parents=True, exist_ok=True)
            tp.write_text(cur + "\n", encoding="utf-8")
        except Exception:
            pass
    return cur

def _rot_council_write_next_turn(sid, seats=None):
    """應 Owner 60606 #1/#4：run_watcher 退出前（完成 1 次推送／生成緊跳過／DAILY_LIMIT 收工／例外）即刻寫下一隻未暫停席位入 rotation-turn.txt（即使無 rotation-seats.txt 亦按 seats.conf 或本機組 A2→A3→A4／A5→A6→A7／A8→A9→A10 交棒）。"""
    try:
        seats_list = list(seats) if seats is not None else _rot_council_load_seats(default_fallback=True, hint_sid=sid)
        if not seats_list:
            return None
        paused = _rot_council_get_paused()
        nxt = _rot_council_next_seat(sid, seats=seats_list, paused=paused)
        if not nxt:
            log(sid, "⚠️ [ROTATION] 全部席位已暫停（rotation-paused.txt），保持原 turn 檔")
            return None
        tp = _rot_council_turn_path()
        tp.parent.mkdir(parents=True, exist_ok=True)
        tmp_tp = tp.with_suffix(".tmp")
        tmp_tp.write_text(nxt + "\n", encoding="utf-8")
        tmp_tp.replace(tp)
        log(sid, f"🔄 [ROTATION] 退出前寫入下一席位：{nxt}（{tp.name}）")
        return nxt
    except Exception as e:
        try:
            log(sid, f"⚠️ [ROTATION] 寫 rotation-turn.txt 失敗：{e}")
        except Exception:
            pass
        return None

# === URL 輪換 + Zoom 100% 硬鎖 + _seat_window_id / W1-W5 視窗定位 v5.8 (Spec v3.3 Conformance) ===
# BASE_TARGET_V094: http://149.118.48.126:8080/persistent/scripts/watcher.py (67,160B | 1,477L | md5=cb11d45f639722650e3ebe156897da51 | sha256=b634251dc94632819cd7e1d69c8b90a2fe9f052a56df11b8b40328a066f111e2 | measured_at=2026-10-06T11:36:00Z UTC)
# BASE_ROOT_8080  : http://149.118.48.126:8080/watcher.py                    (98,817B | 2,076L | md5=061d30f394370bec763ac6b063239042 | sha256=511f528458ab405a0234c857392e81d201c2b99476141ee52e272d34f8e47b25 | measured_at=2026-10-19T00:20:00Z UTC)
# BASE_R10_REV2   : https://paste.c-net.org/SocietyAngelus                   (295,640B | 5,741L | md5=5783180267c7ceb297cee43c0c10e6ce | sha256=96f3be5f882debfc09015cb9bf97e6b5a2681f9f5eb3e4c53647cf7d4ac6157c | measured_at=2026-10-18T17:10:00Z UTC)
# BASE_R11_A65    : SwannPresley on SocietyAngelus                           (292,157B | 5,719L | md5=e0fcc0bede831f1afbf47ce992a38d2d | sha256=92fdafa04aa302684e62b2c4bb52dae024e41d28edf7313bbc9f3faa67b4746a | measured_at=2026-10-19T00:20:00Z UTC)
# SPEC_V3_3_PIN   : watcher-url-rotation-spec-v3.3.txt                       (29,999B | 328L | md5=086d1debba34ca92b1640ef7d6177326 | sha256=43746d5fd5245f47fddba4b9c9ad8df32cfdeb63b3e9ac06490abfbd00d048b3 | measured_at=2026-10-06T11:36:00Z UTC)
import fcntl, json, os, re, shutil, subprocess, time, urllib.request, urllib.error
ROTATION_TAILS = {"A2": "2", "A3": "3", "A4": "4"}
ROTATION_SERVER_URL_TEMPLATE = "http://149.118.48.126:8080/url-rotation/url-rotation-tail{tail}.json"
ROTATION_HTTP_TIMEOUT_S = 3
_DEFAULT_SYSTEM_DIR = SYSTEM_DIR
TARGET_VIEWPORT_W = 1400
TARGET_VIEWPORT_H = 900
EXPECTED_WIN_W = 1408
EXPECTED_WIN_H = 900
_LAST_VALID_ENTRIES = {}
_LAST_VALID_INDEX = {}
_LAST_VALID_LABEL = {}
_PREFS_CLEANED_AT_BOOT = set()
_SEAT_DPR_BASELINE = {"A2": 1.0, "A3": 1.0, "A4": 1.0}
_BASELINE_LOGGED = set()

_VALID_PROFILE_NAME_RE = re.compile(r"^[A-Za-z0-9._-]+\Z")

def _is_valid_profile_name(name):
    """應 F8 & 58489：驗證 profile 名稱必須為單一安全路徑組件（拒絕 ../、/、空字串）。"""
    s = str(name or "").strip()
    if not s or s in (".", "..") or "/" in s or "\\" in s:
        return False
    return bool(_VALID_PROFILE_NAME_RE.match(s))

def _seats_fallback_url(sid):
    try:
        sconf = SYSTEM_DIR / "seats.conf"
        if sconf.exists():
            for line in sconf.read_text(encoding="utf-8", errors="ignore").splitlines():
                line = line.strip()
                if not line or line.startswith("#"):
                    continue
                parts = [p.strip() for p in line.split("|")] if "|" in line else line.split()
                if len(parts) >= 4 and parts[0] == sid:
                    return parts[3]
    except Exception:
        pass
    return ""

def _seats_fallback_profile(sid):
    """應 58489 & A2/58491 #5：當 JSON 條目缺 profile 欄位時，向下兼容退回 seats.conf 第二欄 profile（或 sid）。"""
    try:
        sconf = SYSTEM_DIR / "seats.conf"
        if sconf.exists():
            for line in sconf.read_text(encoding="utf-8", errors="ignore").splitlines():
                line = line.strip()
                if not line or line.startswith("#"):
                    continue
                parts = [p.strip() for p in line.split("|")] if "|" in line else line.split()
                if len(parts) >= 2 and parts[0] == sid and _is_valid_profile_name(parts[1]):
                    return parts[1]
    except Exception:
        pass
    s = str(sid or "").strip()
    return s if _is_valid_profile_name(s) else ""

def _resolve_rotation_tail(sid):
    """解析席位對應之 rotation tail（A2..A4 恆開；A5..A10 於正式環境或存在對應 tail JSON／rotation-seats 時啟用，沙盒測試無 tail5.json 時保持 R7 向下兼容）。"""
    s = str(sid or "").strip().upper()
    if s in ROTATION_TAILS:
        return ROTATION_TAILS[s]
    m = re.match(r"^A(\d+)\Z", s)
    if not m:
        return None
    n = int(m.group(1))
    tail = "10" if (n % 10 == 0) else str(n % 10)
    if SYSTEM_DIR != _DEFAULT_SYSTEM_DIR:
        jpath = Path(SYSTEM_DIR) / f"url-rotation-tail{tail}.json"
        if not jpath.exists() and s not in _rot_council_load_seats(default_fallback=False):
            return None
    return tail

def _extract_tail_entries_from_raw(sid, raw_data, source_tag):
    """應 58489 & 59641 #2：解析每席 5 個 profiles × 每個 profile 綁 2 條 URL 之 JSON（兼容新舊 JSON 結構：
    ① 頂層或 seats[sid] 內含 profiles 陣列/字典 [{profile, urls:[...]}, ...] 或 {profile: [url1, url2]}
    ② 傳統 urls 陣列 [{label, url, profile}, ...]
    watcher 睇 JSON 決定 CP 邊個 profile，絕不寫死 profile 名）。"""
    default_prof = _seats_fallback_profile(sid)
    raw_items = []

    def _push_item(lbl_val, url_val, prof_val, has_explicit_prof):
        raw_items.append({
            "label": lbl_val,
            "url": url_val,
            "profile": prof_val,
            "_explicit_prof": has_explicit_prof,
        })

    def _consume_profile_block(prof_name, block, fallback_label_prefix=""):
        if isinstance(block, dict):
            u_list = block.get("urls")
            if u_list is None:
                u_list = [block[k] for k in ("url1", "url2", "primary_url", "secondary_url", "url") if block.get(k)]
        elif isinstance(block, (list, tuple)):
            u_list = list(block)
        else:
            u_list = []
        for idx_u, u_entry in enumerate(u_list):
            if isinstance(u_entry, str):
                lbl = f"{fallback_label_prefix or sid}-{prof_name}-{idx_u + 1}"
                _push_item(lbl, u_entry, prof_name, True)
            elif isinstance(u_entry, dict):
                lbl = u_entry.get("label") if u_entry.get("label") is not None else u_entry.get("seat", "")
                p_override = u_entry.get("profile") if "profile" in u_entry and u_entry.get("profile") is not None else prof_name
                _push_item(lbl, u_entry.get("url", ""), p_override, True)

    target = raw_data
    if isinstance(target, dict):
        s_upper = str(sid or "").strip().upper()
        if isinstance(target.get("seats"), dict) and s_upper in target["seats"] and isinstance(target["seats"][s_upper], (dict, list)):
            target = target["seats"][s_upper]
        elif s_upper in target and isinstance(target[s_upper], (dict, list)):
            target = target[s_upper]

    if isinstance(target, dict):
        profs_node = target.get("profiles")
        if isinstance(profs_node, list) and profs_node:
            for p_obj in profs_node:
                if not isinstance(p_obj, dict):
                    continue
                p_name = p_obj.get("profile") if p_obj.get("profile") is not None else (p_obj.get("name") if p_obj.get("name") is not None else p_obj.get("id", ""))
                _consume_profile_block(p_name, p_obj, fallback_label_prefix=sid)
        elif isinstance(profs_node, dict) and profs_node:
            for p_name, p_block in profs_node.items():
                _consume_profile_block(p_name, p_block, fallback_label_prefix=sid)
        elif isinstance(target.get("urls"), list):
            for item in target["urls"]:
                if isinstance(item, dict):
                    has_p = "profile" in item and item.get("profile") is not None and str(item.get("profile", "")).strip() != ""
                    _push_item(
                        item.get("label") if item.get("label") is not None else item.get("seat", ""),
                        item.get("url", ""),
                        item.get("profile", "") if has_p else default_prof,
                        has_p,
                    )
    elif isinstance(target, list):
        for item in target:
            if not isinstance(item, dict):
                continue
            if "urls" in item and isinstance(item.get("urls"), (list, tuple)):
                p_name = item.get("profile") if item.get("profile") is not None else (item.get("name") if item.get("name") is not None else item.get("id", ""))
                _consume_profile_block(p_name, item, fallback_label_prefix=sid)
            else:
                has_p = "profile" in item and item.get("profile") is not None and str(item.get("profile", "")).strip() != ""
                _push_item(
                    item.get("label") if item.get("label") is not None else item.get("seat", ""),
                    item.get("url", ""),
                    item.get("profile", "") if has_p else default_prof,
                    has_p,
                )

    valid = []
    for item in raw_items:
        u = str(item.get("url", "")).strip()
        if not u:
            continue
        lbl = str(item.get("label") or "").strip() or str(sid or "").strip()
        if not item.get("_explicit_prof"):
            prof = default_prof
        else:
            raw_p = str(item.get("profile", "")).strip()
            if not _is_valid_profile_name(raw_p):
                log(sid, f"⚠️ [URL-ROT] [PROFILE_INVALID] {source_tag} 含非法 profile={raw_p!r}，拒絕該條目（fail-closed）")
                continue
            prof = raw_p
        valid.append({"label": lbl, "url": u, "profile": prof})
    return valid

def _group_entries_by_profile(entries):
    """按 JSON 出現順序將條目歸組為 [{profile, urls:[...], indices:[...]}]，供以 Profile 為單位跳轉與檢視。"""
    groups = []
    by_prof = {}
    for idx, item in enumerate(entries or []):
        prof = str(item.get("profile") or "").strip()
        if prof not in by_prof:
            grp = {"profile": prof, "urls": [], "indices": []}
            by_prof[prof] = grp
            groups.append(grp)
        by_prof[prof]["urls"].append(item)
        by_prof[prof]["indices"].append(idx)
    return groups

def _slot_target_y(sid):
    """應 60527（owner 指令）：coordinator 輪開一次只開一個 browser，所有席位目標座標一律固定 (0,0) 即 y=0，防止 enforce_window_geometry 將 A3/A4 推返 (0,900)/(0,1800)。"""
    if "SLOT_Y_POS" in globals() and sid in SLOT_Y_POS:
        return int(SLOT_Y_POS[sid])
    return 0

def _save_corrupt_copy(bad_path):
    try:
        ts_utc = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())
        bak = bad_path.with_name(f"{bad_path.name}.corrupt-{ts_utc}")
        if not bak.exists():
            shutil.copy2(bad_path, bak)
        return bak.name
    except Exception:
        return f"{bad_path.name}.corrupt-err"

def _fetch_server_tail_entries(sid, tail):
    # Tier 1 (主持 47600)：先經 HTTP 讀 http://149.118.48.126:8080/url-rotation/url-rotation-tail{tail}.json（server 唯一本）
    if SYSTEM_DIR != _DEFAULT_SYSTEM_DIR:
        return None
    srv_url = ROTATION_SERVER_URL_TEMPLATE.format(tail=tail)
    try:
        req = urllib.request.Request(srv_url, headers={"Cache-Control": "no-cache"})
        with urllib.request.urlopen(req, timeout=ROTATION_HTTP_TIMEOUT_S) as resp:
            if getattr(resp, "status", 200) != 200:
                log(sid, f"⚠️ [URL-ROT] [HTTP_FALLBACK] Server HTTP {getattr(resp, 'status', None)} ({srv_url})，fallback 本機 JSON")
                return None
            raw_text = resp.read().decode("utf-8")
        data = json.loads(raw_text)
        if not isinstance(data, (dict, list)):
            log(sid, f"⚠️ [URL-ROT] [HTTP_FALLBACK] {srv_url} 格式錯誤，fallback 本機 JSON")
            return None
        valid = _extract_tail_entries_from_raw(sid, data, srv_url)
        if not valid:
            log(sid, f"⚠️ [URL-ROT] [HTTP_FALLBACK] {srv_url} urls/profiles 無合法條目，fallback 本機 JSON")
            return None
        _LAST_VALID_ENTRIES[sid] = valid
        log(sid, f"ℹ️ [URL-ROT] [SERVER_JSON] 讀自 server 唯一本 {srv_url} ({len(valid)} 條)")
        return valid
    except Exception as e:
        log(sid, f"⚠️ [URL-ROT] [HTTP_FALLBACK] 讀取 server 唯一本 {srv_url} 失敗 ({type(e).__name__}: {e})，fallback 本機 JSON")
        return None

def _parse_tail_entries(sid, tail):
    jpath = SYSTEM_DIR / f"url-rotation-tail{tail}.json"
    if os.environ.get("WATCHER_PREFER_LOCAL_ROTATION_JSON", "0") == "1" and jpath.exists():
        try:
            local_data = json.loads(jpath.read_text(encoding="utf-8"))
            local_valid = _extract_tail_entries_from_raw(sid, local_data, jpath.name)
            if local_valid:
                _LAST_VALID_ENTRIES[sid] = local_valid
                return local_valid, "json"
        except Exception:
            pass
    srv_valid = _fetch_server_tail_entries(sid, tail)
    if srv_valid is not None:
        return srv_valid, "json"
    if not jpath.exists():
        log(sid, f"⚠️ [URL-ROT] [JSON_MISSING] {jpath.name} urls 設定檔唔存在 (missing)")
        missing_reason = "missing"
        return None, missing_reason
    try:
        data = json.loads(jpath.read_text(encoding="utf-8"))
        if not isinstance(data, (dict, list)):
            log(sid, f"⚠️ [URL-ROT] [JSON_CORRUPT] {jpath.name} urls 為空或格式錯誤")
            return _LAST_VALID_ENTRIES.get(sid), "corrupt"
        valid = _extract_tail_entries_from_raw(sid, data, jpath.name)
        if not valid:
            log(sid, f"⚠️ [URL-ROT] [JSON_CORRUPT] {jpath.name} urls 無合法條目")
            return _LAST_VALID_ENTRIES.get(sid), "corrupt"
        _LAST_VALID_ENTRIES[sid] = valid
        return valid, "json"
    except json.JSONDecodeError as e:
        log(sid, f"⚠️ [URL-ROT] [JSON_CORRUPT] {jpath.name} JSON 語法錯誤／Torn Read ({e})，Fail-Closed 保留快取")
        return _LAST_VALID_ENTRIES.get(sid), "corrupt"
    except Exception as e:
        log(sid, f"⚠️ [URL-ROT] [JSON_CORRUPT] {jpath.name} 讀取異常 ({type(e).__name__}: {e})")
        return _LAST_VALID_ENTRIES.get(sid), "corrupt"

def _state_read_idx(sid, total):
    st_file = SYSTEM_DIR / "url-rotation.json"
    tail = _resolve_rotation_tail(sid) or ROTATION_TAILS.get(sid, sid[-1] if sid else "")
    per_tail = SYSTEM_DIR / f"url-rotation-tail{tail}.state.json"
    if not st_file.exists() and not per_tail.exists():
        _LAST_VALID_INDEX.pop(sid, None)
        log(sid, "ℹ️ [URL-ROT] [INDEX_INIT] 狀態檔唔存在（首次初始化），由 index=0 起行")
        return 0
    # 59426-fix：per-tail 狀態檔優先（操作員手動改 index 即生效）→ 全域 url-rotation.json → 記憶體快取
    if per_tail.exists():
        try:
            obj = json.loads(per_tail.read_text(encoding="utf-8"))
            idx = obj.get("index") if isinstance(obj, dict) else None
            if isinstance(idx, int) and not isinstance(idx, bool) and 0 <= idx < total:
                _LAST_VALID_INDEX[sid] = idx
                log(sid, f"ℹ️ [URL-ROT] [INDEX_SRC] per-tail 狀態檔 {per_tail.name} index={idx}（手動改檔即跟隨）")
                return idx
            raise ValueError(f"out-of-bounds or invalid per_tail index={idx!r} (total={total})")
        except Exception as e:
            bak_name = _save_corrupt_copy(per_tail)
            log(sid, f"⚠️ [URL-ROT] [INDEX_CORRUPT] {per_tail.name} 損毀或越界 ({type(e).__name__}: {e})，已存化驗副本 {bak_name}，嚴守 §四 鐵律保持原 index={_LAST_VALID_INDEX.get(sid)}（永不覆寫壞檔、嚴禁歸零）")
    if st_file.exists():
        try:
            obj = json.loads(st_file.read_text(encoding="utf-8"))
            if isinstance(obj, dict):
                if sid in obj:
                    v = obj[sid]
                    idx = v.get("index") if isinstance(v, dict) else v
                elif any(re.match(r"^A\d+\Z", str(k)) for k in obj.keys()):
                    if sid in _LAST_VALID_INDEX:
                        return _LAST_VALID_INDEX[sid]
                    log(sid, f"ℹ️ [URL-ROT] [INDEX_INIT] {per_tail.name} 未建立且 url-rotation.json 無 {sid} 記錄，本席由 index=0 起行")
                    return 0
                else:
                    idx = obj.get("index")
                if isinstance(idx, int) and not isinstance(idx, bool) and 0 <= idx < total:
                    _LAST_VALID_INDEX[sid] = idx
                    log(sid, f"ℹ️ [URL-ROT] [INDEX_SRC] 全域 url-rotation.json index={idx}")
                    return idx
                raise ValueError(f"out-of-bounds or invalid index={idx!r} (total={total})")
            raise ValueError("url-rotation.json root not dict")
        except Exception as e:
            bak_name = _save_corrupt_copy(st_file)
            log(sid, f"⚠️ [URL-ROT] [INDEX_CORRUPT] url-rotation.json 損毀或越界 ({type(e).__name__}: {e})，已存化驗副本 {bak_name}，嚴守 §四 鐵律保持原 index={_LAST_VALID_INDEX.get(sid)}（永不覆寫壞檔、嚴禁歸零）")
            if sid in _LAST_VALID_INDEX:
                return _LAST_VALID_INDEX[sid]
    if sid in _LAST_VALID_INDEX:
        return _LAST_VALID_INDEX[sid]
    return None

_DAILY_LIMIT_PROFILES_BY_DATE = {}
_DAILY_LIMIT_URLS_BY_DATE = {}
_DAILY_LIMIT_STATE_SEMANTICS = "url-first-v1"

def _today_date_str():
    return os.environ.get("WATCHER_TODAY_DATE") or time.strftime("%Y-%m-%d")

def _get_daily_limited_urls_today(sid):
    """應 59758 & A13/F35：讀取本席今日已觸發 DAILY_LIMIT 嘅 URL 集合（跨重啟由 state 檔恢復，隔日自動清零）。"""
    s_key = str(sid or "").strip().upper()
    today = _today_date_str()
    mem_set = set(_DAILY_LIMIT_URLS_BY_DATE.get((s_key, today), set()))
    tail = _resolve_rotation_tail(s_key) or ROTATION_TAILS.get(s_key, s_key[-1] if s_key else "")
    per_tail = SYSTEM_DIR / f"url-rotation-tail{tail}.state.json"
    if per_tail.exists():
        try:
            obj = json.loads(per_tail.read_text(encoding="utf-8"))
            # 正式 versioned state，或 A66 r10 預發布期間已產生但未有 version 欄嘅 URL ledger，均可保留。
            # 舊 r9 根本無 daily_limit_urls，故不會誤承接舊 profile-first 語義。
            url_date = obj.get("daily_limit_url_date") or obj.get("daily_limit_date") if isinstance(obj, dict) else None
            provisional_r10 = isinstance(obj, dict) and obj.get("daily_limit_semantics") is None and isinstance(obj.get("daily_limit_urls"), list)
            if (isinstance(obj, dict) and url_date == today
                    and (obj.get("daily_limit_semantics") == _DAILY_LIMIT_STATE_SEMANTICS or provisional_r10)):
                for u in (obj.get("daily_limit_urls") or ()):
                    if isinstance(u, str) and u.strip():
                        mem_set.add(u.strip())
        except Exception:
            pass
    _DAILY_LIMIT_URLS_BY_DATE[(s_key, today)] = set(mem_set)
    return mem_set

def _is_url_daily_limited_today(sid, url):
    u = str(url or "").strip()
    if not u:
        return False
    return u in _get_daily_limited_urls_today(sid)

def _mark_url_daily_limit_today(sid, url, reason=""):
    """應 59758 & A13/F35：標記指定 URL 今日已觸發 DAILY_LIMIT，寫入 per-tail state 檔。"""
    s_key = str(sid or "").strip().upper()
    u = str(url or "").strip()
    if not u:
        return _get_daily_limited_urls_today(s_key)
    today = _today_date_str()
    cur_set = _get_daily_limited_urls_today(s_key)
    cur_set.add(u)
    _DAILY_LIMIT_URLS_BY_DATE[(s_key, today)] = set(cur_set)
    tail = _resolve_rotation_tail(s_key) or ROTATION_TAILS.get(s_key, s_key[-1] if s_key else "")
    per_tail = SYSTEM_DIR / f"url-rotation-tail{tail}.state.json"
    if per_tail.exists():
        try:
            obj = json.loads(per_tail.read_text(encoding="utf-8"))
            if isinstance(obj, dict):
                if obj.get("daily_limit_semantics") != _DAILY_LIMIT_STATE_SEMANTICS:
                    # r9 嘅 profile-first 標記只證明至少一條 URL hit，唔可以繼續封死整個 profile。
                    # URL ledger（若由預發布 r10 產生）已在 cur_set 保留。
                    obj["daily_limit_profiles"] = []
                    obj.pop("last_daily_limit_reason", None)
                obj["daily_limit_semantics"] = _DAILY_LIMIT_STATE_SEMANTICS
                obj["daily_limit_url_date"] = today
                obj["daily_limit_date"] = today
                obj["daily_limit_urls"] = sorted(cur_set)
                if reason:
                    obj["last_daily_limit_reason"] = str(reason)
                tmp_s = per_tail.with_suffix(".tmp")
                tmp_s.write_text(json.dumps(obj, ensure_ascii=False) + "\n", encoding="utf-8")
                tmp_s.replace(per_tail)
        except Exception:
            pass
    return cur_set

def _get_daily_limited_profiles_today(sid):
    """應 59641 #5 & 59758：讀取本席今日名下全部 URL 皆已觸發 DAILY_LIMIT 收工嘅 profile 集合（跨重啟由 state 檔恢復，隔日自動清零）。"""
    s_key = str(sid or "").strip().upper()
    today = _today_date_str()
    mem_set = set(_DAILY_LIMIT_PROFILES_BY_DATE.get((s_key, today), set()))
    tail = _resolve_rotation_tail(s_key) or ROTATION_TAILS.get(s_key, s_key[-1] if s_key else "")
    per_tail = SYSTEM_DIR / f"url-rotation-tail{tail}.state.json"
    if per_tail.exists():
        try:
            obj = json.loads(per_tail.read_text(encoding="utf-8"))
            if (isinstance(obj, dict)
                    and obj.get("daily_limit_semantics") == _DAILY_LIMIT_STATE_SEMANTICS
                    and obj.get("daily_limit_date") == today):
                for p in (obj.get("daily_limit_profiles") or ()):
                    if isinstance(p, str) and p.strip():
                        mem_set.add(p.strip())
        except Exception:
            pass
    _DAILY_LIMIT_PROFILES_BY_DATE[(s_key, today)] = set(mem_set)
    return mem_set

def _is_profile_daily_limited_today(sid, profile_name):
    prof = str(profile_name or "").strip()
    if not prof:
        return False
    return prof in _get_daily_limited_profiles_today(sid)

def _mark_profile_daily_limit_today(sid, profile_name, reason=""):
    """應 59641 #5、59758 & Owner 60606 #4（DAILY_LIMIT 語義跟 profile：撞限額嗰席當日收工）：標記該 profile 今日收工並寫入 per-tail state 檔（即使 state 檔原本未存在亦建立落盤）。"""
    s_key = str(sid or "").strip().upper()
    prof = str(profile_name or "").strip()
    if not prof:
        return set()
    today = _today_date_str()
    cur_set = _get_daily_limited_profiles_today(s_key)
    cur_set.add(prof)
    _DAILY_LIMIT_PROFILES_BY_DATE[(s_key, today)] = set(cur_set)
    tail = _resolve_rotation_tail(s_key) or ROTATION_TAILS.get(s_key, s_key[-1] if s_key else "")
    per_tail = SYSTEM_DIR / f"url-rotation-tail{tail}.state.json"
    try:
        obj = {}
        if per_tail.exists():
            loaded_obj = json.loads(per_tail.read_text(encoding="utf-8"))
            if isinstance(loaded_obj, dict):
                obj = loaded_obj
        obj.setdefault("seat", s_key)
        obj.setdefault("index", int(_LAST_VALID_INDEX.get(s_key, 0)))
        obj.setdefault("profile", prof)
        obj["daily_limit_semantics"] = _DAILY_LIMIT_STATE_SEMANTICS
        obj["daily_limit_url_date"] = today
        obj["daily_limit_date"] = today
        obj["daily_limit_profiles"] = sorted(cur_set)
        obj["daily_limit_urls"] = sorted(_get_daily_limited_urls_today(s_key))
        if reason:
            obj["last_daily_limit_reason"] = str(reason)
        obj["updated_at"] = int(time.time())
        per_tail.parent.mkdir(parents=True, exist_ok=True)
        tmp_s = per_tail.with_suffix(".tmp")
        tmp_s.write_text(json.dumps(obj, ensure_ascii=False) + "\n", encoding="utf-8")
        tmp_s.replace(per_tail)
    except Exception:
        pass
    return cur_set

def _state_write_idx(sid, idx, label="", url="", profile=""):
    idx = int(idx)
    _LAST_VALID_INDEX[sid] = idx
    if label:
        _LAST_VALID_LABEL[sid] = label
    prof = str(profile or "").strip() or _seats_fallback_profile(sid)
    tail = _resolve_rotation_tail(sid) or ROTATION_TAILS.get(sid, sid[-1] if sid else "")
    per_tail = SYSTEM_DIR / f"url-rotation-tail{tail}.state.json"
    st_file = SYSTEM_DIR / "url-rotation.json"
    today = _today_date_str()
    dl_profs = sorted(_get_daily_limited_profiles_today(sid))
    dl_urls = sorted(_get_daily_limited_urls_today(sid))
    try:
        payload = {
            "seat": sid, "index": idx, "label": label, "url": url, "profile": prof,
            "daily_limit_semantics": _DAILY_LIMIT_STATE_SEMANTICS,
            "daily_limit_url_date": today, "daily_limit_urls": dl_urls,
            "daily_limit_date": today, "daily_limit_profiles": dl_profs,
            "updated_at": int(time.time()),
        }
        tmp_s = per_tail.with_suffix(".tmp")
        tmp_s.write_text(json.dumps(payload, ensure_ascii=False) + "\n", encoding="utf-8")
        tmp_s.replace(per_tail)
    except Exception:
        pass
    try:
        state = {"index": idx}
        if st_file.exists():
            try:
                loaded = json.loads(st_file.read_text(encoding="utf-8"))
                if isinstance(loaded, dict):
                    state = loaded
            except Exception:
                pass
        state["index"] = idx
        state[sid] = idx
        if label:
            amap = state.get("active_seats") if isinstance(state.get("active_seats"), dict) else {}
            amap[sid] = label
            state["active_seats"] = amap
        if prof:
            pmap = state.get("active_profiles") if isinstance(state.get("active_profiles"), dict) else {}
            pmap[sid] = prof
            state["active_profiles"] = pmap
        tmp_f = st_file.with_suffix(".json.tmp")
        tmp_f.write_text(json.dumps(state, ensure_ascii=False) + "\n", encoding="utf-8")
        tmp_f.replace(st_file)
    except Exception:
        pass

def load_rotation_entries(sid):
    # 主持 47600 同名入口：1. 先經 HTTP 讀 server 唯一本 -> 2. fallback 本機 JSON -> 3. fallback seats.conf
    return load_url_rotation(sid)

def load_url_rotation(sid):
    """Seam 1 (R2/R3/R4/R7 & 58489 & 59641 #2/#5)：每次攞 URL 重讀 JSON；回傳 {rotation,label,url,profile,index,count,source}。"""
    tail = _resolve_rotation_tail(sid)
    fb_prof = _seats_fallback_profile(sid)
    if not tail:
        return {"rotation": False, "label": sid, "url": _seats_fallback_url(sid), "profile": fb_prof, "index": 0, "count": 0, "source": "ineligible"}
    entries, _ = _parse_tail_entries(sid, tail)
    if not entries:
        log(sid, f"⚠️ [URL-ROT] [FALLBACK-START:tail{tail}] 退回 seats.conf 預設 URL")
        return {"rotation": True, "label": sid, "url": _seats_fallback_url(sid), "profile": fb_prof, "index": -1, "count": 0, "source": "fallback"}
    idx = _state_read_idx(sid, len(entries))
    if idx is None:
        log(sid, f"⚠️ [URL-ROT] [INDEX_CORRUPT] [FALLBACK-START:tail{tail}] 重啟後狀態檔損毀且無記憶體 index，嚴禁歸零或覆寫壞檔，退回 seats.conf")
        return {"rotation": True, "label": sid, "url": _seats_fallback_url(sid), "profile": fb_prof, "index": -1, "count": 0, "source": "fallback"}
    chosen = entries[idx]
    chosen_prof = chosen.get("profile") or fb_prof
    prev_lbl = _LAST_VALID_LABEL.get(sid)
    if prev_lbl and prev_lbl != chosen["label"]:
        log(sid, f"⚠️ [URL-ROT] [INDEX_LABEL_MISMATCH] index={idx} 標籤由 {prev_lbl} 變為 {chosen['label']}（只准 append 唔准重排）")
    _LAST_VALID_LABEL[sid] = chosen["label"]
    log(sid, f"URL 輪換：用第 {idx + 1}/{len(entries)} 條（{chosen['label']}｜profile={chosen_prof}） {chosen['url']}")
    return {"rotation": True, "label": chosen["label"], "url": chosen["url"], "profile": chosen_prof, "index": idx, "count": len(entries), "source": "json"}

def rotation_advance(sid):
    """Seam 2 (R5/R6 & 58489 & 59758)：單條 URL 耗盡（如 TOO_LONG）時嚴格只向前 +1（wrap），跳過今日已觸發 DAILY_LIMIT 之 URL/profile，persist 狀態（含 profile），永不後退。"""
    tail = _resolve_rotation_tail(sid)
    fb_prof = _seats_fallback_profile(sid)
    if not tail:
        return {"rotation": False, "label": sid, "url": _seats_fallback_url(sid), "profile": fb_prof, "index": 0, "count": 0, "source": "ineligible"}
    entries, _ = _parse_tail_entries(sid, tail)
    if not entries:
        log(sid, f"⚠️ [URL-ROT] [FALLBACK-START:tail{tail}] 退回 seats.conf 預設 URL")
        return {"rotation": True, "label": sid, "url": _seats_fallback_url(sid), "profile": fb_prof, "index": -1, "count": 0, "source": "fallback"}
    cur_idx = _state_read_idx(sid, len(entries))
    if cur_idx is None:
        log(sid, f"⚠️ [URL-ROT] [INDEX_CORRUPT] [FALLBACK-START:tail{tail}] 重啟後狀態檔損毀且無記憶體 index，嚴禁歸零或覆寫壞檔，退回 seats.conf")
        return {"rotation": True, "label": sid, "url": _seats_fallback_url(sid), "profile": fb_prof, "index": -1, "count": 0, "source": "fallback"}
    dl_today = _get_daily_limited_profiles_today(sid)
    dl_urls_today = _get_daily_limited_urls_today(sid)
    next_idx = (cur_idx + 1) % len(entries)
    for step in range(1, len(entries) + 1):
        cand_idx = (cur_idx + step) % len(entries)
        cand_prof = str(entries[cand_idx].get("profile") or fb_prof).strip()
        cand_url = str(entries[cand_idx].get("url") or "").strip()
        if cand_prof not in dl_today and cand_url not in dl_urls_today:
            next_idx = cand_idx
            break
    chosen = entries[next_idx]
    chosen_prof = chosen.get("profile") or fb_prof
    _state_write_idx(sid, next_idx, chosen["label"], chosen["url"], chosen_prof)
    log(sid, f"URL 輪換：用第 {next_idx + 1}/{len(entries)} 條（{chosen['label']}｜profile={chosen_prof}） {chosen['url']}")
    return {"rotation": True, "label": chosen["label"], "url": chosen["url"], "profile": chosen_prof, "index": next_idx, "count": len(entries), "source": "json"}

def rotation_advance_on_daily_limit(sid, exhausted_profile=None, reason=""):
    """應 Owner 60606 #4（DAILY_LIMIT 語義跟 profile：撞限額嗰席當日收工，照樣交棒下一席）& 59754/59758：
    1. 撞到 DAILY_LIMIT 時標記該 Profile（及當前 URL）今日收工（_mark_profile_daily_limit_today）。
    2. 若為單一 profile 席位（無 JSON entries 或僅有單一 profile）或全部 profile 均已收工，回傳 all_profiles_exhausted=True。
    3. 若 JSON 內尚有其他未收工 Profile，預先推進 state index 至下一個未收工 Profile 供下一輪使用，本輪照樣交棒下一席。"""
    tail = _resolve_rotation_tail(sid)
    fb_prof = _seats_fallback_profile(sid)
    bad_prof_init = str(exhausted_profile or fb_prof).strip()
    if not tail:
        if bad_prof_init:
            _mark_profile_daily_limit_today(sid, bad_prof_init, reason=reason)
        return {"rotation": False, "label": sid, "url": _seats_fallback_url(sid), "profile": fb_prof, "index": 0, "count": 0, "source": "ineligible", "skipped_profile": bad_prof_init or None, "all_profiles_exhausted": True}
    entries, _ = _parse_tail_entries(sid, tail)
    if not entries:
        fb_url = _seats_fallback_url(sid)
        if fb_url:
            _mark_url_daily_limit_today(sid, fb_url, reason=reason)
        if bad_prof_init:
            _mark_profile_daily_limit_today(sid, bad_prof_init, reason=reason)
        log(sid, f"🚨 [DAILY-LIMIT:PROFILE-DONE] {sid} (profile={bad_prof_init}) 觸發 DAILY_LIMIT 當日收工（seats.conf 單一 profile），交棒下一席")
        return {"rotation": True, "label": sid, "url": fb_url, "profile": fb_prof, "index": -1, "count": 0, "source": "fallback", "skipped_profile": bad_prof_init or None, "all_profiles_exhausted": True}
    cur_idx = _state_read_idx(sid, len(entries))
    if cur_idx is None:
        log(sid, f"⚠️ [URL-ROT] [INDEX_CORRUPT] [FALLBACK-START:tail{tail}] 重啟後狀態檔損毀且無記憶體 index，嚴禁歸零或覆寫壞檔，退回 seats.conf")
        return {"rotation": True, "label": sid, "url": _seats_fallback_url(sid), "profile": fb_prof, "index": -1, "count": 0, "source": "fallback", "all_profiles_exhausted": False}
    cur_entry = entries[cur_idx]
    bad_url = str(cur_entry.get("url") or "").strip()
    bad_prof = str(exhausted_profile or cur_entry.get("profile") or fb_prof).strip()
    dl_urls_today = _mark_url_daily_limit_today(sid, bad_url, reason=reason)

    # Step 1 (應 59758)：優先搵同一個 Profile 綁住嘅另一條今日未耗盡 URL
    same_prof_next_idx = None
    for step in range(1, len(entries) + 1):
        cand_idx = (cur_idx + step) % len(entries)
        if cand_idx == cur_idx:
            continue
        cand_prof = str(entries[cand_idx].get("profile") or fb_prof).strip()
        cand_url = str(entries[cand_idx].get("url") or "").strip()
        if cand_prof == bad_prof and cand_url not in dl_urls_today:
            same_prof_next_idx = cand_idx
            break

    if same_prof_next_idx is not None:
        chosen = entries[same_prof_next_idx]
        chosen_prof = chosen.get("profile") or fb_prof
        _state_write_idx(sid, same_prof_next_idx, chosen["label"], chosen["url"], chosen_prof)
        log(sid, f"🚨 [DAILY-LIMIT:SAME-PROFILE-NEXT-URL] {sid} URL ({cur_entry['label']}) 觸發 DAILY_LIMIT (reason={reason})，即刻自動轉去同一個 profile={chosen_prof} 嘅另一條 URL（第 {same_prof_next_idx + 1}/{len(entries)} 條｜{chosen['label']}） {chosen['url']}")
        return {
            "rotation": True, "label": chosen["label"], "url": chosen["url"], "profile": chosen_prof,
            "index": same_prof_next_idx, "count": len(entries), "source": "json",
            "same_profile_next_url": True, "skipped_url": bad_url,
            "skipped_profile": None, "all_profiles_exhausted": False,
        }

    # Step 2：該 Profile 名下全部 URL 今日均已耗盡 → 標記該 Profile 今日收工，再搵下一個未收工 Profile 嘅未耗盡 URL
    dl_today = _mark_profile_daily_limit_today(sid, bad_prof, reason=reason)
    next_idx = None
    for step in range(1, len(entries) + 1):
        cand_idx = (cur_idx + step) % len(entries)
        cand_prof = str(entries[cand_idx].get("profile") or fb_prof).strip()
        cand_url = str(entries[cand_idx].get("url") or "").strip()
        if cand_url not in dl_urls_today and cand_prof not in dl_today:
            next_idx = cand_idx
            break

    if next_idx is None:
        next_idx = (cur_idx + 1) % len(entries)
        chosen = entries[next_idx]
        chosen_prof = chosen.get("profile") or fb_prof
        _state_write_idx(sid, next_idx, chosen["label"], chosen["url"], chosen_prof)
        log(sid, f"🚨 [DAILY-LIMIT:ALL-PROFILES-DONE] {sid} profile={bad_prof} 觸發 DAILY_LIMIT，本席今日全部 URL/profile 均已收工 (done_profiles={sorted(dl_today)}, done_urls={len(dl_urls_today)}/{len(entries)})")
        return {
            "rotation": True, "label": chosen["label"], "url": chosen["url"], "profile": chosen_prof,
            "index": next_idx, "count": len(entries), "source": "json",
            "same_profile_next_url": False, "skipped_url": bad_url,
            "skipped_profile": bad_prof, "all_profiles_exhausted": True,
        }

    chosen = entries[next_idx]
    chosen_prof = chosen.get("profile") or fb_prof
    _state_write_idx(sid, next_idx, chosen["label"], chosen["url"], chosen_prof)
    log(sid, f"🚨 [DAILY-LIMIT:PROFILE-SKIP] {sid} profile={bad_prof} 名下全部 URL 今日收工，直接轉去下一個 profile={chosen_prof}（第 {next_idx + 1}/{len(entries)} 條｜{chosen['label']}） {chosen['url']}")
    return {
        "rotation": True, "label": chosen["label"], "url": chosen["url"], "profile": chosen_prof,
        "index": next_idx, "count": len(entries), "source": "json",
        "same_profile_next_url": False, "skipped_url": bad_url,
        "skipped_profile": bad_prof, "all_profiles_exhausted": False,
    }

_LOGIN_FAILED_PROFILES_SESSION = {}

def rotation_advance_to_next_profile(sid, failed_profile=None, reason="google_login_failed"):
    """應 59654（第 8 項第 5 點修訂）：自動補密碼／登入失敗時唔好停、唔好 retry loop，上報後直接 pass 去下一個 profile 繼續推（跳過同一個失敗 profile 綁住嘅另一條 URL）。"""
    tail = _resolve_rotation_tail(sid)
    fb_prof = _seats_fallback_profile(sid)
    if not tail:
        return {"rotation": False, "label": sid, "url": _seats_fallback_url(sid), "profile": fb_prof, "index": 0, "count": 0, "source": "ineligible", "all_profiles_exhausted": True}
    entries, _ = _parse_tail_entries(sid, tail)
    if not entries:
        return {"rotation": True, "label": sid, "url": _seats_fallback_url(sid), "profile": fb_prof, "index": -1, "count": 0, "source": "fallback", "all_profiles_exhausted": True}
    cur_idx = _state_read_idx(sid, len(entries))
    if cur_idx is None:
        return {"rotation": True, "label": sid, "url": _seats_fallback_url(sid), "profile": fb_prof, "index": -1, "count": 0, "source": "fallback", "all_profiles_exhausted": True}
    cur_entry = entries[cur_idx]
    bad_prof = str(failed_profile or cur_entry.get("profile") or fb_prof).strip()
    s_key = str(sid or "").strip().upper()
    failed_set = _LOGIN_FAILED_PROFILES_SESSION.setdefault(s_key, set())
    failed_set.add(bad_prof)
    dl_today = _get_daily_limited_profiles_today(sid)
    next_idx = None
    for step in range(1, len(entries) + 1):
        cand_idx = (cur_idx + step) % len(entries)
        cand_prof = str(entries[cand_idx].get("profile") or fb_prof).strip()
        if cand_prof != bad_prof and cand_prof not in failed_set and cand_prof not in dl_today:
            next_idx = cand_idx
            break
    if next_idx is None:
        for step in range(1, len(entries) + 1):
            cand_idx = (cur_idx + step) % len(entries)
            cand_prof = str(entries[cand_idx].get("profile") or fb_prof).strip()
            if cand_prof != bad_prof and cand_prof not in dl_today:
                next_idx = cand_idx
                break
        if next_idx is None:
            next_idx = (cur_idx + 1) % len(entries)
        chosen = entries[next_idx]
        chosen_prof = chosen.get("profile") or fb_prof
        _state_write_idx(sid, next_idx, chosen["label"], chosen["url"], chosen_prof)
        log(sid, f"🚨 [GOOGLE-PW:ALL-PROFILES-TRIED] {sid} profile={bad_prof} 登入失敗 ({reason})，本輪全部可用 profile 已嘗試完畢 (tried={sorted(failed_set)})")
        return {
            "rotation": True, "label": chosen["label"], "url": chosen["url"], "profile": chosen_prof,
            "index": next_idx, "count": len(entries), "source": "json",
            "skipped_profile": bad_prof, "all_profiles_exhausted": True,
        }
    chosen = entries[next_idx]
    chosen_prof = chosen.get("profile") or fb_prof
    _state_write_idx(sid, next_idx, chosen["label"], chosen["url"], chosen_prof)
    log(sid, f"⏭️ [GOOGLE-PW:PASS-NEXT-PROFILE] {sid} profile={bad_prof} 登入失敗 ({reason})，直接 pass 去下一個 profile={chosen_prof}（第 {next_idx + 1}/{len(entries)} 條｜{chosen['label']}） {chosen['url']}")
    return {
        "rotation": True, "label": chosen["label"], "url": chosen["url"], "profile": chosen_prof,
        "index": next_idx, "count": len(entries), "source": "json",
        "skipped_profile": bad_prof, "all_profiles_exhausted": False,
    }

WATCHER_STATUS_API_URL = os.environ.get("WATCHER_STATUS_API_URL", "http://149.118.48.126:8080/push-status")

def _infer_machine_for_seat(sid):
    env_m = os.environ.get("WATCHER_MACHINE_NAME", "").strip()
    if env_m:
        return env_m
    tail = _resolve_rotation_tail(sid)
    if tail is None:
        m = re.match(r"^A(\d+)$", str(sid or "").strip().upper())
        if m:
            n = int(m.group(1))
            tail = "10" if (n >= 10 and n % 10 == 0) else str(n % 10)
    tail_str = str(tail or "").strip()
    if tail_str in ("2", "3", "4"):
        return "host"
    if tail_str in ("5", "6", "7"):
        return "watcher-a567"
    if tail_str in ("8", "9", "10"):
        return "watcher-a810"
    return "host"

def _load_push_status_key():
    env_k = os.environ.get("WATCHER_PUSH_STATUS_KEY", "").strip()
    if env_k:
        return env_k
    for kfile in (Path(SYSTEM_DIR) / "push-status.key", Path(SYSTEM_DIR) / ".push-status-key"):
        try:
            if kfile.exists():
                v = kfile.read_text(encoding="utf-8", errors="ignore").strip()
                if v:
                    return v
        except Exception:
            pass
    return ""

def _post_slot_status_report(sid, profile_name, slot_label=None, url=None, status_api_url=None):
    """應 59680/59682/59687：僅由 watcher 程序本身於每個 SLOT 推完即 POST http://149.118.48.126:8080/push-status/report 上報
    （JSON：{"machine":"host","slot":"A2","profile":"ai-53","url":"..."}，支援 WATCHER_PUSH_STATUS_KEY / push-status.key）。"""
    base = str(status_api_url if status_api_url is not None else WATCHER_STATUS_API_URL).strip().rstrip("/")
    if not base or os.environ.get("WATCHER_DISABLE_STATUS_API") == "1":
        return False
    import datetime as _dt, urllib.request as _ureq
    now_utc = _dt.datetime.now(_dt.timezone.utc)
    now_hkt = now_utc.astimezone(_dt.timezone(_dt.timedelta(hours=8)))
    hkt_str = now_hkt.strftime("%Y-%m-%d %H:%M:%S HKT")
    seat_val = str(sid or slot_label or "").strip()
    machine_val = _infer_machine_for_seat(seat_val)
    payload = {
        "machine": machine_val,
        "slot": seat_val,
        "profile": str(profile_name or "").strip(),
        "url": str(url or "").strip(),
        "slot_label": str(slot_label or seat_val).strip(),
        "updated_hkt": hkt_str,
        "timestamp": int(now_utc.timestamp()),
    }
    hdrs = {"Content-Type": "application/json"}
    api_key = _load_push_status_key()
    if api_key:
        hdrs["X-Push-Status-Key"] = api_key
        hdrs["Authorization"] = f"Bearer {api_key}"
    try:
        req = _ureq.Request(
            f"{base}/report",
            data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
            headers=hdrs,
            method="POST",
        )
        with _ureq.urlopen(req, timeout=5) as resp:
            _ = resp.read()
        log(sid, f"📡 [PUSH-STATUS] 已 POST {base}/report：machine={machine_val} slot={seat_val} profile={profile_name}")
        return True
    except Exception as e:
        log(sid, f"⚠️ [PUSH-STATUS] POST {base}/report 未通 ({type(e).__name__})")
        return False

def _record_slot_last_profile(sid, profile_name, slot_label=None, state_dir=None, url=None, post_api=None):
    """應 59672 & 59680（owner 2026-10-17 23:12/23:18 HKT）：每當成功推完一個 SLOT，即時喺 {state_dir}/<slot>-last-profile.txt 寫低純文字 profile ID（如 ai-53，唔包 JSON，唔受 rotation 影響），並 POST :18888/report 更新 updated_hkt heartbeat。"""
    prof = str(profile_name or "").strip()
    if not sid or not prof:
        return None
    sdir = Path(state_dir) if state_dir is not None else Path(os.environ.get("WATCHER_STATE_DIR") or SYSTEM_DIR)
    sdir.mkdir(parents=True, exist_ok=True)
    slots = []
    for raw_s in (sid, slot_label):
        s_clean = str(raw_s or "").strip()
        if s_clean and re.match(r"^[A-Za-z0-9_-]+$", s_clean) and s_clean not in slots:
            slots.append(s_clean)
    written_main = None
    for sl in slots:
        target = sdir / f"{sl}-last-profile.txt"
        tmp = sdir / f".{sl}-last-profile.txt.tmp.{os.getpid()}"
        try:
            tmp.write_text(f"{prof}\n", encoding="utf-8")
            tmp.replace(target)
            if written_main is None:
                written_main = target
        except Exception as e:
            log(sid, f"⚠️ [LAST-PROFILE] 寫入 {target} 失敗: {type(e).__name__}")
            try:
                if tmp.exists():
                    tmp.unlink()
            except OSError:
                pass
    if written_main is not None:
        log(sid, f"📝 [LAST-PROFILE] 已記錄最後成功使用 profile：{prof} -> {written_main}")
    do_post = (state_dir is None) if post_api is None else bool(post_api)
    if do_post:
        _post_slot_status_report(sid, prof, slot_label=slot_label, url=url)
    return written_main

def ensure_rotation_url(page, sid):
    """Seam 4（主持 58250）：操作前必驗當前 URL 喺本 tail JSON；唔係即導航返指定 URL；重驗唔中即 abort。"""
    tail = _resolve_rotation_tail(sid)
    if not tail:
        return True
    entries, _ = _parse_tail_entries(sid, tail)
    if not entries:
        return True
    norm = lambda u: (u or "").strip().rstrip("/")
    allowed = {norm(e["url"]) for e in entries}
    if norm(page.url) in allowed:
        return True
    r = load_url_rotation(sid)
    log(sid, f"❌ [URL-GUARD] 當前 URL 唔喺 tail{tail} JSON：{page.url[:100]} → 導航返 {r['url'][:100]}")
    try:
        page.goto(r["url"], wait_until="domcontentloaded", timeout=60000)
    except Exception as e:
        log(sid, f"❌ [URL-GUARD] 導航失敗（{type(e).__name__}: {e}）——操作中止")
        return False
    if norm(page.url) in allowed:
        log(sid, f"✅ [URL-GUARD] 已返 JSON 內 URL：{page.url[:100]}")
        return True
    log(sid, "❌ [URL-GUARD] 導航後仍唔喺 JSON——操作中止（fail-closed）")
    return False

_WS_PROFILE_NAME_RE = re.compile(r"^ws-(?:core|[1-9]|1\d|2[0-4])\Z")
_QUOTE_OR_HISTORY_MARKERS = (
    "quoted", "transcript", "prior transcript", "old quoted",
    "not the current page error", "no current error banner",
)

# 應主持 58489 & bm.js (WS1_EXT_MERGE_V1..V4 + VPN_TOGGLE_V2) 對齊常數
VPN_EXTENSION_ID = "hnmpcagpplmpfojmgmnngilcnanddlhb"
VPN_POPUP_URL = f"chrome-extension://{VPN_EXTENSION_ID}/popup.html"
VPN_TOGGLE_SELECTOR = "button.joyride-element-proxy-button"
VPN_STATUS_SELECTORS = (
    "[class*='status' i]", "[class*='state' i]", "[class*='power' i]",
    "[data-testid*='status' i]", "[data-testid*='state' i]",
    "[role='status']", "h1", "h2", "p",
)
# 應 dj_host1 59308/59310（Fix 1）：刪走寫死嘅 Emotion ON/OFF class，狀態一律改讀文字。
VPN_POPUP_STATE_KNOWN_TIMEOUT_MS = 25000
VPN_CLICK_CONFIRM_TIMEOUT_MS = 15000
# 應主持 58524（A93 修復版）：啟動路徑 VPN latch 修復開關
# 默認 0＝fail-closed：本 profile 搵唔到 unpacked ws-* extension 都當失敗（跟全案 fail-closed 口徑）
# 設 1＝放行（只印 WARN，上 latch 跳過），適用於「嗰個席本來就唔用 Extension VPN」嘅已知配置
VPN_BOOT_ALLOW_NO_EXT = os.environ.get("VPN_BOOT_ALLOW_NO_EXT", "0") == "1"
VPN_FAIL_OPEN = os.environ.get("VPN_FAIL_OPEN", "0") == "1"
VPN_MAX_STRICT_RETRIES = int(os.environ.get("VPN_MAX_STRICT_RETRIES", "2") or "2")
# 應 A13/59716 & 59755 G2/G3：禁用 core dump 並清除 PWDEBUG 及 DEBUG=pw:*，防止崩潰或 debug 時將記憶體憑證落地
try:
    import resource as _resource
    _resource.setrlimit(_resource.RLIMIT_CORE, (0, 0))
except Exception:
    pass
os.environ.pop("PWDEBUG", None)
if "pw:" in str(os.environ.get("DEBUG", "")):
    os.environ.pop("DEBUG", None)
# 應 dj_host1 59406/59409/59412 & OWNER 59414（Fix 2 兩階段＋內建 Userland Chain Proxy 模組）：
VPN_USE_CHAIN_PROXY = os.environ.get("VPN_USE_CHAIN_PROXY", "1") != "0"
VPN_CHAIN_BASE_PORT = int(os.environ.get("VPN_CHAIN_PORT", "18080") or "18080")
VPN_STAGE_A_TIMEOUT_MS = int(os.environ.get("VPN_STAGE_A_TIMEOUT_MS", "15000") or "15000")
VPN_JP1_TUNNEL_IPS = frozenset(
    ip.strip() for ip in os.environ.get("VPN_JP1_TUNNEL_IPS", "161.33.178.218").split(",") if ip.strip()
)
# Hard floors from host 60012/60025.  They may not be lowered by environment.
WATCHER_MIN_PLAYWRIGHT_VERSION = "1.64.0"
WATCHER_MIN_CHROMIUM_REVISION = 1248
WATCHER_MIN_RAMDISK_FREE_MB = int(os.environ.get("WATCHER_MIN_RAMDISK_FREE_MB", "128") or "128")
WATCHER_MIN_DISK_FREE_MB = int(os.environ.get("WATCHER_MIN_DISK_FREE_MB", "128") or "128")

def _is_valid_public_exit_ip(ip_str):
    """應 A87 60032 §二：驗證基準 IP 與出口 IP 必須為合法公網 IP（拒絕 loopback / RFC1918 私網 / link-local 169.254/16 / multicast / reserved），防止 NAT/容器私網位址觸發 ip != baseline 靜默假通過。"""
    import ipaddress as _ipaddress
    s = str(ip_str or "").strip()
    if not s:
        return False
    try:
        addr = _ipaddress.ip_address(s)
    except ValueError:
        return False
    if (
        addr.is_loopback
        or addr.is_private
        or addr.is_link_local
        or addr.is_multicast
        or addr.is_unspecified
        or addr.is_reserved
    ):
        return False
    return bool(getattr(addr, "is_global", True))

def _is_public_routable_ip(value):
    """Cross-implementation spelling for the strict global-unicast guard."""
    return _is_valid_public_exit_ip(value)


def _is_public_exit_ip(value):
    """A66 compatibility spelling for the same strict guard."""
    return _is_valid_public_exit_ip(value)


# 應 Owner 59821 + 59822 & A56 59823：自學習本地 IP 黑名單（自動偵測 arena.ai 403 封鎖 → 寫入 ip-blacklist.json 0600 → 下次自動跳過）
IP_BLACKLIST_SEED_IPS = {}

def _mask_ip_for_log(ip):
    s = str(ip or "").strip()
    parts = s.split(".")
    if len(parts) == 4:
        return f"{parts[0]}.x.x.{parts[3]}"
    return "MASKED_IP" if s else "UNKNOWN"
_ARENA_403_BLOCK_MARKERS = (
    "access denied",
    "sorry, you have been blocked",
    "you are unable to access",
    "the owner of this website has banned your ip",
    "ip address has been blocked",
    "error 1005",
    "error 1006",
    "error 1007",
    "error 1008",
    "error 1020",
    "error code: 1005",
    "error code: 1006",
    "error code: 1007",
    "error code: 1008",
    "error code: 1020",
)
_ARENA_CF_CHALLENGE_MARKERS = (
    "just a moment...",
    "verify you are human",
    "cf-turnstile",
    "challenge-platform",
    "checking if the site connection is secure",
)

def _ip_blacklist_state_path():
    return Path(SYSTEM_DIR) / "ip-blacklist.json"

def _save_ip_blacklist(data):
    st_path = _ip_blacklist_state_path()
    try:
        st_path.parent.mkdir(parents=True, exist_ok=True)
        tmp_path = st_path.with_suffix(".tmp")
        payload = json.dumps(data, ensure_ascii=False, indent=2) + "\n"
        fd = os.open(str(tmp_path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
        try:
            os.write(fd, payload.encode("utf-8"))
        finally:
            os.close(fd)
        os.chmod(tmp_path, 0o600)
        tmp_path.replace(st_path)
        os.chmod(st_path, 0o600)
        return True
    except Exception:
        return False

def _load_ip_blacklist():
    st_path = _ip_blacklist_state_path()
    data = {"version": 1, "blocked_ips": {}}
    dirty = False
    if st_path.is_file():
        try:
            loaded = json.loads(st_path.read_text(encoding="utf-8"))
            if isinstance(loaded, dict) and isinstance(loaded.get("blocked_ips"), dict):
                data["version"] = int(loaded.get("version") or 1)
                for k, v in loaded["blocked_ips"].items():
                    ks = str(k or "").strip()
                    if ks:
                        data["blocked_ips"][ks] = dict(v) if isinstance(v, dict) else {"reason": str(v)}
        except Exception:
            pass
    else:
        dirty = True
    for seed_ip, seed_meta in IP_BLACKLIST_SEED_IPS.items():
        if seed_ip not in data["blocked_ips"]:
            data["blocked_ips"][seed_ip] = dict(seed_meta)
            dirty = True
    seed_txt = Path(SYSTEM_DIR) / "ip-blacklist.seed.txt"
    if seed_txt.is_file():
        try:
            for sline in seed_txt.read_text(encoding="utf-8", errors="ignore").splitlines():
                sline = sline.split("#", 1)[0].strip()
                if not sline:
                    continue
                sparts = [x.strip() for x in sline.replace("|", ":").split(":")]
                sip = sparts[0]
                sport = int(sparts[1]) if len(sparts) > 1 and sparts[1].isdigit() else None
                if sip and sip not in data["blocked_ips"]:
                    data["blocked_ips"][sip] = {
                        "first_seen": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
                        "last_seen": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
                        "reason": "seed_file_arena_403",
                        "port": sport,
                        "hit_count": 1,
                    }
                    dirty = True
        except Exception:
            pass
    env_extra = os.environ.get("ARENA_BLACKLISTED_IPS", "")
    for raw_ip in env_extra.split(","):
        cand = raw_ip.strip()
        if not cand:
            continue
        sparts = [x.strip() for x in cand.replace("|", ":").split(":")]
        sip = sparts[0]
        sport = int(sparts[1]) if len(sparts) > 1 and sparts[1].isdigit() else None
        if sip and sip not in data["blocked_ips"]:
            entry = {
                "first_seen": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
                "last_seen": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
                "reason": "env_ARENA_BLACKLISTED_IPS",
                "hit_count": 1,
            }
            if sport is not None:
                entry["port"] = sport
            data["blocked_ips"][sip] = entry
            dirty = True
    if dirty:
        _save_ip_blacklist(data)
    return data

def _is_ip_blacklisted(ip):
    cand = str(ip or "").strip()
    if not cand or cand == "-":
        return False
    return cand in _load_ip_blacklist().get("blocked_ips", {})

def _record_blacklisted_ip(ip, reason="arena_http_403", sid=None, port=None, upstream_host=None, url=None):
    cand = str(ip or "").strip()
    if not cand or cand in ("-", "127.0.0.1", "0.0.0.0", "::1"):
        return False
    if not re.match(r"^[0-9a-fA-F:.]{3,45}$", cand):
        return False
    now_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    data = _load_ip_blacklist()
    blocked = data.setdefault("blocked_ips", {})
    prev = blocked.get(cand) if isinstance(blocked.get(cand), dict) else {}
    entry = {
        "first_seen": prev.get("first_seen") or now_iso,
        "last_seen": now_iso,
        "reason": str(reason or prev.get("reason") or "arena_http_403"),
        "port": int(port) if port is not None else prev.get("port"),
        "sid": str(sid or prev.get("sid") or ""),
        "upstream_host": str(upstream_host or prev.get("upstream_host") or ""),
        "url": str(url or prev.get("url") or ""),
        "hit_count": int(prev.get("hit_count") or 0) + 1,
    }
    blocked[cand] = entry
    _save_ip_blacklist(data)
    if sid:
        log(sid, f"🚫 [IP-BLACKLIST:ADD] 已將被 arena.ai 403 封鎖之出口 ({_mask_ip_for_log(cand)}) 加入本地黑名單 ({_ip_blacklist_state_path()})：reason={reason} port={port} upstream={upstream_host}")
    try:
        chain = _get_active_chain_proxy(sid) if sid else None
    except Exception:
        chain = None
    _demote_chain_upstream_host(chain, upstream_host)
    return True


def _demote_chain_upstream_host(chain, host=None):
    """Move a 403/blacklisted upstream to the tail so the next attempt rotates."""
    if chain is None:
        return False
    bad_host = str(host or getattr(chain, "last_ok_host", None) or "").strip()
    if not bad_host:
        return False
    lock = getattr(chain, "_lock", None)
    acquired = False
    try:
        if lock is not None:
            lock.acquire()
            acquired = True
        hosts = list(getattr(chain, "_upstream_hosts", ()) or ())
        if bad_host not in hosts:
            return False
        chain._upstream_hosts = [h for h in hosts if h != bad_host] + [bad_host]
        if getattr(chain, "last_ok_host", None) == bad_host:
            chain.last_ok_host = None
        return True
    finally:
        if acquired:
            lock.release()


def _is_arena_403_ip_block_response(status_code, body_text="", headers=None):
    """區分真 arena.ai/Cloudflare IP 403 封鎖與普通 Cloudflare JS/Turnstile 驗證頁。"""
    low = str(body_text or "").lower()
    hdr_dict = {}
    if isinstance(headers, dict):
        hdr_dict = {str(k).lower(): str(v).lower() for k, v in headers.items()}
    has_explicit_block = any(m in low for m in _ARENA_403_BLOCK_MARKERS)
    if has_explicit_block and (status_code in (403, None) or "403" in low or "blocked" in low or "access denied" in low):
        return True
    if status_code == 403:
        if "challenge" in hdr_dict.get("cf-mitigated", ""):
            return False
        if any(cm in low for cm in _ARENA_CF_CHALLENGE_MARKERS):
            return False
        return True
    return False

def _probe_arena_ip_blocked(proxy_url, exit_ip=None, sid=None, port=None, upstream_host=None, timeout=6.0):
    """應 59822 #1 & 59823 §2(a)：探測指定 proxy 出口是否被 arena.ai 403 封鎖；若確認封鎖則自動寫入 ip-blacklist.json。"""
    if exit_ip and _is_ip_blacklisted(exit_ip):
        return True, "already-in-ip-blacklist"
    if not proxy_url:
        return False, None
    try:
        r = subprocess.run(
            ["curl", "-sS", "-i", "--max-time", str(int(max(3, timeout))), "-x", str(proxy_url), "https://arena.ai/agent"],
            capture_output=True, text=True, timeout=timeout + 2, env=_clean_proxy_env(),
        )
        if r.returncode != 0 or not r.stdout:
            return False, None
        raw_out = r.stdout
        sep = "\r\n\r\n" if "\r\n\r\n" in raw_out else "\n\n"
        hdr_block, body = raw_out.split(sep, 1) if sep in raw_out else (raw_out, "")
        status_code = None
        hdrs = {}
        for line in hdr_block.splitlines():
            s = line.strip()
            if s.upper().startswith("HTTP/"):
                parts = s.split()
                if len(parts) >= 2 and parts[1].isdigit():
                    status_code = int(parts[1])
                hdrs = {}
            elif ":" in s:
                k, v = s.split(":", 1)
                hdrs[k.strip().lower()] = v.strip()
        if _is_arena_403_ip_block_response(status_code, body, hdrs):
            if exit_ip:
                _record_blacklisted_ip(exit_ip, reason="probe_arena_403", sid=sid, port=port, upstream_host=upstream_host, url="https://arena.ai/agent")
            return True, f"probe-arena-403(status={status_code})"
    except Exception:
        pass
    return False, None

def _with_rotation_flock(fn, *args, **kwargs):
    """應 F12：跨程序單寫鎖 (url-rotation.lock)，防止 watcher 與 guard 雙寫競爭。"""
    import fcntl
    lock_path = SYSTEM_DIR / ".url-rotation.lock"
    try:
        lock_path.parent.mkdir(parents=True, exist_ok=True)
        with open(lock_path, "a+", encoding="utf-8") as lf:
            fcntl.flock(lf.fileno(), fcntl.LOCK_EX)
            try:
                return fn(*args, **kwargs)
            finally:
                fcntl.flock(lf.fileno(), fcntl.LOCK_UN)
    except Exception:
        return fn(*args, **kwargs)

# 應 59641 #3/#4/#6：種／運行分離（workshop 存種 persistent disk 永遠唔掂；運行前單一 profile CP 去 ramdisk tmpfs；收工即清 ramdisk）
WORKSHOP_SEED_DIR = Path(os.environ.get("WATCHER_SEED_PROFILES_DIR") or (Path.home() / "workspace" / "workshop" / "profiles"))
RAMDISK_PROFILES_DIR = Path(
    os.environ.get("WATCHER_RAMDISK_DIR")
    or ("/dev/shm/watcher-profiles" if Path("/dev/shm").is_dir() else "/tmp/watcher-profiles")
)
_WS_ROTATION_CURSOR = {}

def _score_ws_profiles_dir(root):
    """Score already-extracted WS trees without opening archives or starting browsers."""
    root = Path(root)
    if not root.is_dir():
        return 0
    score = 0
    try:
        profiles = [item for item in root.iterdir() if item.is_dir() and _WS_PROFILE_NAME_RE.match(item.name)]
    except OSError:
        return 0
    for profile in profiles:
        default = profile / "Default"
        if (default / "Preferences").is_file():
            score += 1
        ext_root = default / "Extensions" / VPN_EXTENSION_ID
        try:
            if ext_root.is_dir() and any(ext_root.glob("*/manifest.json")):
                score += 20
        except OSError:
            pass
        ldb = default / "Local Extension Settings" / VPN_EXTENSION_ID
        try:
            files = [fp for fp in ldb.iterdir() if fp.is_file() and fp.suffix in (".ldb", ".log")] if ldb.is_dir() else []
        except OSError:
            files = []
        for fp in files:
            try:
                text = fp.read_bytes().decode("utf-8", errors="ignore").replace('\\"', '"')
            except OSError:
                continue
            if '"serverCredentials"' in text and '"username"' in text and '"password"' in text:
                score += 100
                break
    return score


def _resolve_ws_profiles_dir(profiles_dir=None):
    """Select the best extracted WS tree, including a single nested ws-profiles layer."""
    roots = []
    if profiles_dir is not None:
        roots.append(Path(profiles_dir))
    env_ws = os.environ.get("WATCHER_WS_PROFILES_DIR")
    if env_ws:
        roots.append(Path(env_ws))
    roots.extend([
        Path(PROFILES_DIR),
        Path(SYSTEM_DIR) / "local-profiles",
        Path(SYSTEM_DIR) / "ws-profiles",
        Path(MASTER_PROFILES_DIR),
        Path(WORKSHOP_SEED_DIR),
        Path.home() / "workspace" / "workshop" / "ws-profiles",
        Path.home() / "workspace" / "workshop" / "profiles",
    ])
    candidates = []
    seen = set()
    for root in roots:
        for cand in (root, root / "ws-profiles"):
            try:
                resolved = cand.resolve()
            except Exception:
                resolved = cand
            if resolved in seen:
                continue
            seen.add(resolved)
            score = _score_ws_profiles_dir(cand)
            if score > 0:
                candidates.append((score, len(candidates), cand))
    if candidates:
        candidates.sort(key=lambda item: (-item[0], item[1]))
        return candidates[0][2]
    return Path(profiles_dir if profiles_dir is not None else PROFILES_DIR)

def _resolve_seed_profile_dir(profile_name, seed_root=None):
    """應 59641 #3：由 persistent disk（workshop 種目錄）定位指定 profile 種，絕不修改種目錄。"""
    prof = str(profile_name or "").strip()
    cands = []
    if seed_root is not None:
        cands.append(Path(seed_root))
    env_s = os.environ.get("WATCHER_SEED_PROFILES_DIR")
    if env_s:
        cands.append(Path(env_s))
    cands.extend([
        Path(SYSTEM_DIR) / "workshop" / "profiles",
        Path(WORKSHOP_SEED_DIR),
        Path(SYSTEM_DIR) / "workshop-profiles",
        Path(MASTER_PROFILES_DIR),
        Path(PROFILES_DIR),
    ])
    for root in cands:
        cand = root / prof
        if cand.is_dir():
            return cand
    base = Path(seed_root) if seed_root is not None else (Path(env_s) if env_s else Path(PROFILES_DIR))
    return base / prof

def _resolve_ramdisk_root(ramdisk_root=None):
    if ramdisk_root is not None:
        return Path(ramdisk_root)
    env_r = os.environ.get("WATCHER_RAMDISK_DIR")
    if env_r:
        return Path(env_r)
    return Path(RAMDISK_PROFILES_DIR)

_STAGED_PROFILE_DIR_RE = re.compile(r"^(?:ai-\d+|A\d+)\Z")

def _is_safe_ramdisk_root(rroot_res, sid=None):
    """應 A13/59649 P2-1 (F23)：三層縱深防禦保護——
    ① ramdisk root resolve 後必須嚴格位於 /dev/shm 或 /tmp 子目錄之下（白名單，且唔准等於 /dev/shm 或 /tmp 根目錄本身）；
    ② 任何受保護路徑（PROFILES_DIR / MASTER_PROFILES_DIR / WORKSHOP_SEED_DIR / SYSTEM_DIR）位於 rroot 相等、之內（祖先）或包裹 rroot 即拒絕；
    ③ 拒絕 symlink root。"""
    try:
        allowed_bases = []
        for b in ("/dev/shm", "/tmp"):
            bp = Path(b)
            if bp.exists():
                allowed_bases.append(bp.resolve())
        if not any(rroot_res != base and base in rroot_res.parents for base in allowed_bases):
            if sid:
                log(sid, f"🚨 [RAMDISK:GUARD] 拒絕非 /dev/shm 或 /tmp 專用子目錄之 ramdisk root：{rroot_res}")
            return False
        for p in (PROFILES_DIR, MASTER_PROFILES_DIR, WORKSHOP_SEED_DIR, SYSTEM_DIR):
            if p is None:
                continue
            try:
                rp = Path(p).resolve()
            except Exception:
                continue
            if rroot_res == rp or rroot_res in rp.parents or rp in rroot_res.parents:
                if sid:
                    log(sid, f"🚨 [RAMDISK:GUARD] 拒絕與受保護路徑重疊或包含之 ramdisk root：{rroot_res} (protected={rp})")
                return False
        return True
    except Exception:
        return False

def _clean_ramdisk_profiles(ramdisk_root=None, keep_profile=None, sid=None):
    """應 59641 #3/#4 & A13/59649 P2-1 (F23)：清理 ramdisk (tmpfs) 內嘅 staged profile，確保 ramdisk 全程最多只放當前跑嗰一個 profile（收工後清為 0 個），且種與無關檔案永遠唔掂。"""
    rroot = _resolve_ramdisk_root(ramdisk_root)
    if not rroot.exists() or rroot.is_symlink():
        return 0
    try:
        rroot_res = rroot.resolve()
    except Exception:
        return 0
    if not _is_safe_ramdisk_root(rroot_res, sid=sid):
        return 0
    if sid:
        log(sid, f"🧹 [RAMDISK:SCAN] 準備清理 ramdisk root={rroot_res} (keep={keep_profile})")
    removed = 0
    for item in list(rroot_res.iterdir()):
        if keep_profile and item.name == keep_profile:
            continue
        if item.is_symlink() or not item.is_dir():
            continue
        if not _is_valid_profile_name(item.name):
            continue
        is_staged_prof = (
            (item / ".staged_by_watcher").is_file()
            or (item / "Default").is_dir()
            or bool(_STAGED_PROFILE_DIR_RE.match(item.name))
        )
        if not is_staged_prof:
            continue
        try:
            shutil.rmtree(item, ignore_errors=True)
            removed += 1
        except Exception as e:
            if sid:
                log(sid, f"⚠️ [RAMDISK] 清理 {item} 異常：{e}")
    if removed and sid:
        log(sid, f"🧹 [RAMDISK] 已清理 ramdisk 舊 profile ({removed} 個，目錄={rroot_res})")
    return removed

def _verified_tree_copy(source_root, dest_root, ignore_names=(), skip_paths=()):
    """Byte-verify an error-path copy before it may be accepted."""
    import hashlib as _hashlib
    source_root = Path(source_root).resolve()
    dest_root = Path(dest_root)
    ignored = set(ignore_names)
    skipped = {Path(x).resolve() for x in skip_paths}
    expected = set()

    def is_skipped(path):
        resolved = Path(path).resolve()
        return any(resolved == skip or skip in resolved.parents for skip in skipped)

    def digest(path):
        h = _hashlib.sha256()
        with Path(path).open("rb") as fh:
            for chunk in iter(lambda: fh.read(1024 * 1024), b""):
                h.update(chunk)
        return h.digest()

    stack = [Path(source_root)]
    try:
        while stack:
            parent = stack.pop()
            for entry in parent.iterdir():
                if entry.name in ignored or is_skipped(entry):
                    continue
                rel = entry.relative_to(source_root)
                expected.add(str(rel))
                target = dest_root / rel
                if entry.is_symlink():
                    if not target.is_symlink() or target.readlink() != entry.readlink():
                        return False
                elif entry.is_dir():
                    if not target.is_dir() or target.is_symlink():
                        return False
                    stack.append(entry)
                elif entry.is_file():
                    if not target.is_file() or target.is_symlink():
                        return False
                    if entry.stat().st_size != target.stat().st_size or digest(entry) != digest(target):
                        return False
                else:
                    return False
        actual = set()
        stack = [dest_root]
        while stack:
            parent = stack.pop()
            for entry in parent.iterdir():
                rel = entry.relative_to(dest_root)
                actual.add(str(rel))
                if entry.is_dir() and not entry.is_symlink():
                    stack.append(entry)
        return actual == expected
    except (OSError, ValueError):
        return False


def _scriptlet_retry_paths(seed_dir, exc):
    markers = ("extension scripts", "scriptlet")
    raw_items = exc.args[0] if isinstance(exc, shutil.Error) and exc.args and isinstance(exc.args[0], list) else []
    if not raw_items:
        raw_items = [(getattr(exc, "filename", ""), getattr(exc, "filename2", ""), str(exc))]
    skip = set()
    for item in raw_items:
        fields = tuple(item) if isinstance(item, (tuple, list)) else (item,)
        text = " ".join(str(x) for x in fields).lower()
        if not any(marker in text for marker in markers):
            return None
        if fields and fields[0]:
            try:
                source = Path(str(fields[0])).resolve()
                source.relative_to(Path(seed_dir).resolve())
                skip.add(source)
            except Exception:
                pass
    return skip


def _copy_seed_profile_to_ramdisk(seed_dir, ram_dir, sid=None):
    base_names = {"SingletonLock", "SingletonCookie", "SingletonSocket", ".google-pw", ".arena-common-pw"}
    try:
        shutil.copytree(seed_dir, ram_dir, symlinks=True, ignore=shutil.ignore_patterns(*base_names))
        return "complete"
    except (shutil.Error, PermissionError, OSError) as e:
        if _verified_tree_copy(seed_dir, ram_dir, ignore_names=base_names):
            if sid:
                log(sid, "⚠️ [RAMDISK:CP] copytree 報錯但 byte-verified 完整；接納已核實目的樹")
            return "verified-complete-after-error"
        skip_paths = _scriptlet_retry_paths(seed_dir, e)
        shutil.rmtree(ram_dir, ignore_errors=True)
        if skip_paths is None:
            raise
        if ram_dir.exists() or ram_dir.is_symlink():
            raise RuntimeError("seed-copy-partial-destination-not-clean") from e
        def retry_ignore(cur, names):
            ignored = {name for name in names if name in base_names}
            for name in names:
                try:
                    if (Path(cur) / name).resolve() in skip_paths:
                        ignored.add(name)
                except OSError:
                    pass
            return ignored
        if sid:
            log(sid, "⚠️ [RAMDISK:CP] scriptlet collision；清除 partial 後略過精確失敗 cache path 重試一次")
        try:
            shutil.copytree(seed_dir, ram_dir, symlinks=True, ignore=retry_ignore)
        except (shutil.Error, PermissionError, OSError):
            if _verified_tree_copy(seed_dir, ram_dir, ignore_names=base_names, skip_paths=skip_paths):
                if sid:
                    log(sid, "⚠️ [RAMDISK:CP] retry 報錯但目的樹按允許 skip 清單 byte-verified 完整")
                return "retry-verified-complete"
            shutil.rmtree(ram_dir, ignore_errors=True)
            raise
        if not _verified_tree_copy(seed_dir, ram_dir, ignore_names=base_names, skip_paths=skip_paths):
            shutil.rmtree(ram_dir, ignore_errors=True)
            raise RuntimeError("seed-copy-retry-verification-failed")
        return "retry-without-failed-scriptlet-cache"


def _stage_seed_profile_to_ramdisk(sid, profile_name, seed_root=None, ramdisk_root=None):
    """應 59641 #3/#4 & A13/59649 P2-1/P2-2：運行前先清走 ramdisk 其它 profile，再由 persistent workshop 種 CP 當前單一 profile 去 ramdisk（種永遠唔掂；缺種預設 fail-closed）。"""
    prof = str(profile_name or "").strip()
    if not _is_valid_profile_name(prof):
        raise ValueError(f"非法 profile 名稱：{prof!r}")
    rroot = _resolve_ramdisk_root(ramdisk_root)
    rroot.mkdir(parents=True, exist_ok=True)
    rroot_res = rroot.resolve()
    if not _is_safe_ramdisk_root(rroot_res, sid=sid):
        raise RuntimeError(f"不安全嘅 ramdisk root：{rroot_res}（必須位於 /dev/shm 或 /tmp 專用子目錄且與種目錄完全隔離）")
    seed_dir = _resolve_seed_profile_dir(prof, seed_root=seed_root)
    ram_dir = rroot_res / prof
    try:
        if seed_dir.exists() and seed_dir.resolve() == ram_dir.resolve():
            raise RuntimeError(f"seed_dir 與 ram_dir 指向同一路徑 ({seed_dir})，違反種／運行分離")
    except RuntimeError:
        raise
    except Exception:
        pass
    # 先清走 ramdisk 上所有 profile（包括同名舊殘留），保證 ramdisk 全程只放當前呢一個 profile
    _clean_ramdisk_profiles(rroot_res, keep_profile=None, sid=sid)
    if seed_dir.is_dir():
        _copy_seed_profile_to_ramdisk(seed_dir, ram_dir, sid=sid)
        log(sid, f"📦 [RAMDISK:CP] 已由種 CP 去 ramdisk：{seed_dir} -> {ram_dir}（種保持唯讀，ramdisk 現存 1 個 profile）")
    else:
        # 應 A13/59649 P2-2：WATCHER_ALLOW_EMPTY_SEED 預設改為 "0"（fail-closed）
        if os.environ.get("WATCHER_ALLOW_EMPTY_SEED", "0") != "1":
            raise FileNotFoundError(f"找不到 profile 種目錄：{seed_dir}（fail-closed）")
        ram_dir.mkdir(parents=True, exist_ok=True)
        log(sid, f"⚠️ [RAMDISK:CP] 種目錄 {seed_dir} 尚未存在，WATCHER_ALLOW_EMPTY_SEED=1 於 ramdisk 建立空白運行目錄：{ram_dir}")
    try:
        (ram_dir / ".staged_by_watcher").write_text(f"{sid}:{prof}:{int(time.time())}\n", encoding="utf-8")
    except Exception:
        pass
    _clear_stale_singleton_locks(ram_dir)
    _sanitize_profile_zoom_prefs(ram_dir, sid)
    _SEAT_ACTIVE_PROFILE_DIR[str(sid or "").upper()] = str(ram_dir)
    return ram_dir

def _cleanup_ramdisk_profile(sid, ram_profile_dir=None, ramdisk_root=None):
    """應 59641 #4：閂 browser 後即刻清走 ramdisk 嗰個 profile，釋放 tmpfs RAM。"""
    rroot = _resolve_ramdisk_root(ramdisk_root)
    if rroot.exists() and not rroot.is_symlink():
        try:
            rroot_res = rroot.resolve()
        except Exception:
            rroot_res = None
        if rroot_res is not None and _is_safe_ramdisk_root(rroot_res, sid=sid):
            if ram_profile_dir is not None:
                rdir = Path(ram_profile_dir)
                try:
                    rdir_res = rdir.resolve()
                    if rdir_res.exists() and rroot_res in rdir_res.parents:
                        shutil.rmtree(rdir_res, ignore_errors=True)
                        log(sid, f"🧹 [RAMDISK:CLEAN] 已清除 ramdisk profile：{rdir_res}")
                except Exception as e:
                    log(sid, f"⚠️ [RAMDISK:CLEAN] 清除 {rdir} 異常：{e}")
            _clean_ramdisk_profiles(rroot_res, keep_profile=None, sid=sid)
    _SEAT_ACTIVE_PROFILE_DIR.pop(str(sid or "").upper(), None)

def _resolve_google_pw_path(seed_root=None):
    """應 59651 #8.1 & A13/59652 P8-5：定位與 workshop 種目錄根同位之 `.google-pw`（例：server `/root/profiles/.google-pw`；各 watcher 機係自己個 workshop 種目錄根入面嘅 `.google-pw`，絕不放入單一 profile 子目錄或 runtime 目錄以免隨 staging 抄入 tmpfs）。"""
    cands = []
    env_pw = os.environ.get("WATCHER_GOOGLE_PW_FILE")
    if env_pw:
        cands.append(Path(env_pw))
    if seed_root is not None:
        cands.append(Path(seed_root) / ".google-pw")
    env_s = os.environ.get("WATCHER_SEED_PROFILES_DIR")
    if env_s:
        cands.append(Path(env_s) / ".google-pw")
        cands.append(Path(env_s).parent / ".google-pw")
    cands.extend([
        Path(WORKSHOP_SEED_DIR) / ".google-pw",
        Path(WORKSHOP_SEED_DIR).parent / ".google-pw",
        Path(SYSTEM_DIR) / "workshop" / "profiles" / ".google-pw",
        Path(SYSTEM_DIR) / "workshop" / ".google-pw",
        Path.home() / "workspace" / "workshop" / "profiles" / ".google-pw",
        Path.home() / "workspace" / "workshop" / ".google-pw",
        Path("/root/profiles/.google-pw"),
    ])
    for c in cands:
        try:
            if c.exists() or c.is_symlink():
                return c
        except OSError:
            continue
    base = Path(seed_root) if seed_root is not None else (Path(env_s) if env_s else Path(WORKSHOP_SEED_DIR))
    return base / ".google-pw"

def _read_google_password(sid, seed_root=None):
    """應 59651 #8.1-#8.4：讀取 `.google-pw`（必須為普通檔案、非 symlink、權限 0600、非空；絕不將密碼寫入 log）。"""
    import stat as _stat
    pw_path = _resolve_google_pw_path(seed_root=seed_root)
    try:
        st = pw_path.lstat()
    except FileNotFoundError:
        log(sid, f"⚠️ [GOOGLE-PW] 找不到密碼檔：{pw_path}（fail-closed）")
        return None
    except OSError as e:
        log(sid, f"⚠️ [GOOGLE-PW] 無法檢查密碼檔 {pw_path} ({type(e).__name__})（fail-closed）")
        return None
    if _stat.S_ISLNK(st.st_mode) or not _stat.S_ISREG(st.st_mode):
        log(sid, f"⚠️ [GOOGLE-PW] 密碼檔非普通檔案或為 symlink：{pw_path}（fail-closed）")
        return None
    mode = _stat.S_IMODE(st.st_mode)
    if mode != 0o600:
        log(sid, f"⚠️ [GOOGLE-PW] 密碼檔權限非 600 (mode={oct(mode)}, path={pw_path})，拒絕讀取（fail-closed）")
        return None
    try:
        pw = pw_path.read_text(encoding="utf-8").strip("\r\n")
    except Exception as e:
        log(sid, f"⚠️ [GOOGLE-PW] 讀取密碼檔異常 ({type(e).__name__})（fail-closed）")
        return None
    if not pw:
        log(sid, f"⚠️ [GOOGLE-PW] 密碼檔為空：{pw_path}（fail-closed）")
        return None
    return pw

def _list_available_ws_profiles(profiles_dir=None, include_core=False):
    """應 58325 & 58489 & 59641 #6：列出可用嘅現有 24 個精簡版 ws-* profile（ws-core + ws-1..ws-24），唔起新 WS profile。"""
    pdir = _resolve_ws_profiles_dir(profiles_dir)
    found = []
    try:
        if not pdir.is_dir():
            return found
        for item in sorted(pdir.iterdir(), key=lambda d: (0 if d.name == "ws-core" else (int(d.name.split("-")[1]) if d.name.startswith("ws-") and d.name.split("-")[1].isdigit() else 999))):
            if not item.is_dir() or not _WS_PROFILE_NAME_RE.match(item.name):
                continue
            if item.name == "ws-core" and not include_core:
                continue
            if (item / "Default" / "Preferences").is_file() or (item / "Default" / "Extensions").is_dir() or (item / "Default" / "Local Extension Settings").is_dir():
                found.append(item.name)
    except OSError:
        return []
    return found

def _copy_or_merge_dir(src_dir, dst_dir, ignore_names=None):
    """應 60025 #2：當 shutil.copytree 因 Windscribe extension scriptlet 或特殊檔拋出 shutil.Error / OSError 時，逐檔容錯複製保底，絕不因單一檔案異常而整棵崩潰。"""
    s_root = Path(src_dir)
    d_root = Path(dst_dir)
    if not s_root.exists():
        return
    ignored = set(ignore_names or ())
    try:
        d_root.mkdir(parents=True, exist_ok=True)
    except OSError:
        return
    try:
        items = list(s_root.iterdir())
    except OSError:
        return
    for item in items:
        if item.name in ignored:
            continue
        target = d_root / item.name
        try:
            st = item.lstat()
            import stat as _st
            if _st.S_ISLNK(st.st_mode):
                if target.exists() or target.is_symlink():
                    target.unlink()
                os.symlink(os.readlink(item), target)
            elif _st.S_ISDIR(st.st_mode):
                _copy_or_merge_dir(item, target, ignore_names=ignored)
            elif _st.S_ISREG(st.st_mode):
                if target.exists() and target.is_symlink():
                    target.unlink()
                shutil.copyfile(item, target)
                try:
                    shutil.copymode(item, target)
                except OSError:
                    pass
        except (shutil.Error, PermissionError, OSError):
            continue

def _merge_ws_extension_layer(src_ws_dir, dst_seat_dir, only_dirs=None):
    """應 58489 & 60025 #2 & bm.js WS1_EXT_MERGE_V1..V4：將單一 ws-* profile 嘅 Extension 與設定合併入席位 profile（零 Cache/History/Cookies/憑證寫入；三處 copytree 全包 try/except 防 scriptlet shutil.Error crash）。"""
    import shutil as _shutil
    src_def = Path(src_ws_dir) / "Default"
    dst_def = Path(dst_seat_dir) / "Default"
    if not src_def.is_dir():
        return False
    dst_def.mkdir(parents=True, exist_ok=True)
    ext_dirs = tuple(only_dirs) if only_dirs is not None else (
        "Extensions", "Local Extension Settings", "Sync Extension Settings",
        "Managed Extension Settings", "Extension State", "Extension Rules",
        "Extension Scripts", "DNR Extension Rules",
    )
    for dname in ext_dirs:
        s_sub = src_def / dname
        if s_sub.is_dir():
            d_sub = dst_def / dname
            if d_sub.exists():
                _shutil.rmtree(d_sub, ignore_errors=True)
            try:
                _shutil.copytree(s_sub, d_sub, symlinks=True, dirs_exist_ok=True)
            except (_shutil.Error, PermissionError, OSError) as _e_sub:
                _copy_or_merge_dir(s_sub, d_sub)
    if only_dirs is not None:
        return True
    # MV3 Storage/ext (對齊 bm.js L306)
    s_st_ext = src_def / "Storage" / "ext"
    if s_st_ext.is_dir():
        d_st_ext = dst_def / "Storage" / "ext"
        if d_st_ext.exists():
            _shutil.rmtree(d_st_ext, ignore_errors=True)
        d_st_ext.parent.mkdir(parents=True, exist_ok=True)
        try:
            _shutil.copytree(s_st_ext, d_st_ext, symlinks=True, dirs_exist_ok=True)
        except (_shutil.Error, PermissionError, OSError) as _e_st:
            _copy_or_merge_dir(s_st_ext, d_st_ext)
    s_idb = src_def / "IndexedDB"
    if s_idb.is_dir():
        d_idb = dst_def / "IndexedDB"
        d_idb.mkdir(parents=True, exist_ok=True)
        try:
            idb_items = list(s_idb.iterdir())
        except OSError:
            idb_items = []
        for item in idb_items:
            if item.is_dir() and item.name.startswith("chrome-extension_"):
                target = d_idb / item.name
                if target.exists():
                    _shutil.rmtree(target, ignore_errors=True)
                try:
                    _shutil.copytree(item, target, symlinks=True, dirs_exist_ok=True)
                except (_shutil.Error, PermissionError, OSError) as _e_idb:
                    _copy_or_merge_dir(item, target)
    for pfile in ("Preferences", "Secure Preferences"):
        sp = src_def / pfile
        dp = dst_def / pfile
        if sp.is_file():
            try:
                s_obj = json.loads(sp.read_text(encoding="utf-8"))
                d_obj = json.loads(dp.read_text(encoding="utf-8")) if dp.is_file() else {}
                if not isinstance(d_obj, dict):
                    d_obj = {}
                if isinstance(s_obj, dict) and isinstance(s_obj.get("extensions"), dict):
                    d_ext = d_obj.get("extensions")
                    if isinstance(d_ext, dict):
                        for k, v in s_obj["extensions"].items():
                            d_ext[k] = v
                    else:
                        d_obj["extensions"] = s_obj["extensions"]
                if isinstance(s_obj, dict) and isinstance(s_obj.get("protection"), dict):
                    s_macs = s_obj["protection"].get("macs", {}).get("extensions")
                    if isinstance(s_macs, dict):
                        d_obj.setdefault("protection", {}).setdefault("macs", {})["extensions"] = s_macs
                dp.write_text(json.dumps(d_obj, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8")
            except Exception:
                pass
    return True

def _ws_rotation_state_path():
    return Path(SYSTEM_DIR) / "ws-rotation.state.json"

def _read_last_ws_profile(sid, seat_dir=None):
    s_key = str(sid or "").strip().upper()
    if seat_dir is not None:
        meta_path = Path(seat_dir) / ".active_ws_extension.json"
        if meta_path.is_file():
            try:
                cur = json.loads(meta_path.read_text(encoding="utf-8")).get("ws_profile")
                if cur:
                    return str(cur)
            except Exception:
                pass
    st_path = _ws_rotation_state_path()
    if st_path.is_file():
        try:
            obj = json.loads(st_path.read_text(encoding="utf-8"))
            if isinstance(obj, dict):
                v = obj.get(s_key) or obj.get("last_ws_profile")
                if isinstance(v, str) and v.strip():
                    return v.strip()
        except Exception:
            pass
    return _WS_ROTATION_CURSOR.get(s_key)

def _write_last_ws_profile(sid, ws_name):
    s_key = str(sid or "").strip().upper()
    if not ws_name:
        return
    _WS_ROTATION_CURSOR[s_key] = str(ws_name)
    st_path = _ws_rotation_state_path()
    try:
        obj = {}
        if st_path.is_file():
            try:
                loaded = json.loads(st_path.read_text(encoding="utf-8"))
                if isinstance(loaded, dict):
                    obj = loaded
            except Exception:
                obj = {}
        obj[s_key] = str(ws_name)
        obj["last_ws_profile"] = str(ws_name)
        obj["updated_at"] = int(time.time())
        tmp_p = st_path.with_suffix(".tmp")
        tmp_p.write_text(json.dumps(obj, ensure_ascii=False) + "\n", encoding="utf-8")
        tmp_p.replace(st_path)
    except Exception:
        pass

def _apply_ws_extension_to_seat_profile(profile_dir, ws_name, profiles_dir=None, sid=None):
    """應 58325 #3 & 58489 & 59641 #6：套用現有 24 個 ws-* Extension 設定至 ramdisk 運行 profile 供 Stage A 收割（唔掂種目錄、唔起新 WS profile）。"""
    pdir = _resolve_ws_profiles_dir(profiles_dir)
    seat_dir = Path(profile_dir)
    if not _WS_PROFILE_NAME_RE.match(str(ws_name or "")):
        return False
    ws_dir = pdir / ws_name
    if not ws_dir.is_dir():
        return False
    core_dir = pdir / "ws-core"
    ok = _merge_ws_extension_layer(ws_dir, seat_dir)
    if core_dir.is_dir() and ws_name != "ws-core" and not _discover_unpacked_extensions(seat_dir):
        _merge_ws_extension_layer(core_dir, seat_dir, only_dirs=("Extensions", "Extension Rules", "Extension Scripts", "DNR Extension Rules"))
    if ok:
        meta_path = seat_dir / ".active_ws_extension.json"
        try:
            meta_path.write_text(json.dumps({
                "ws_profile": ws_name,
                "updated_at": int(time.time()),
            }, ensure_ascii=False) + "\n", encoding="utf-8")
        except Exception:
            pass
        _write_last_ws_profile(sid, ws_name)
        s_key = str(sid or "").strip().upper()
        if s_key:
            _SEAT_UPSTREAM_ROTATION_IDX[s_key] = 0
            _SEAT_LAST_UPSTREAM_HOST.pop(s_key, None)
        if sid:
            log(sid, f"✅ [VPN-EXT] 已由現有 WS 池輪流載入收割源：{ws_name} -> {seat_dir.name}")
    return ok

def _seat_has_ws_runtime_material(seat_dir, profiles_dir=None):
    if _discover_unpacked_extensions(seat_dir):
        return True
    if VPN_USE_CHAIN_PROXY and _harvest_ws_config_from_leveldb(seat_dir, profiles_dir).get("ok"):
        return True
    return False

def _select_and_apply_startup_ws_extension(sid, profile_dir, profiles_dir=None):
    """應 59641 #6：由現有 24 個 WS profiles 輪流揀選下一個 ws-* 供 Fix 2 Stage A 收割（唔起新 WS profile）。"""
    pdir = _resolve_ws_profiles_dir(profiles_dir)
    seat_dir = Path(profile_dir)
    candidates = _list_available_ws_profiles(pdir, include_core=False)
    if not candidates:
        candidates = _list_available_ws_profiles(pdir, include_core=True)
    if not candidates:
        return None
    prev_ws = _read_last_ws_profile(sid, seat_dir=seat_dir)
    if prev_ws in candidates:
        nxt_idx = (candidates.index(prev_ws) + 1) % len(candidates)
        chosen = candidates[nxt_idx]
    else:
        chosen = candidates[0]
    if not _apply_ws_extension_to_seat_profile(seat_dir, chosen, pdir, sid=sid):
        log(sid, f"❌ [VPN-EXT] startup 套用 WS 收割 profile 失敗：{chosen}")
        return None
    if not _seat_has_ws_runtime_material(seat_dir, pdir):
        log(sid, f"❌ [VPN-EXT] startup 套用後仍無可用 WS extension 或 LevelDB 憑證：{chosen}")
        return None
    return chosen

def _switch_ws_extension_for_seat(sid, profile_dir, profiles_dir=None, rng=None):
    """應 58325 #3c & 58489 & 59641 #6：由現有 24 個 WS profiles 輪流切換下一個 ws-*（若傳入自訂 rng 則兼容測試隨機揀選）。"""
    pdir = _resolve_ws_profiles_dir(profiles_dir)
    seat_dir = Path(profile_dir)
    candidates = _list_available_ws_profiles(pdir, include_core=False)
    if not candidates:
        candidates = _list_available_ws_profiles(pdir, include_core=True)
    if not candidates:
        return None
    prev_ws = _read_last_ws_profile(sid, seat_dir=seat_dir)
    if rng is not None:
        pool = [c for c in candidates if c != prev_ws] if len(candidates) > 1 else list(candidates)
        chosen = rng.choice(pool)
    elif prev_ws in candidates and len(candidates) > 1:
        chosen = candidates[(candidates.index(prev_ws) + 1) % len(candidates)]
    else:
        pool = [c for c in candidates if c != prev_ws] if len(candidates) > 1 else list(candidates)
        chosen = pool[0]
    if not _apply_ws_extension_to_seat_profile(seat_dir, chosen, pdir, sid=sid):
        if sid:
            log(sid, f"❌ [VPN-EXT] 輪換套用 WS 收割 profile 失敗：{chosen}")
        return None
    if not _seat_has_ws_runtime_material(seat_dir, pdir):
        if sid:
            log(sid, f"❌ [VPN-EXT] 輪換套用後仍無可用 WS extension 或 LevelDB 憑證：{chosen}")
        return None
    if sid:
        log(sid, f"🔁 [VPN-EXT] 輪流切換 WS 收割 profile：{prev_ws or 'NONE'} -> {chosen}")
    return chosen

def _vpn_strict_retry_limit():
    """至少遍歷完整 WS profile pool 一次；零候選時仍作有限次修復嘗試，之後 clean stop/交棒。"""
    pdir = _resolve_ws_profiles_dir()
    candidates = _list_available_ws_profiles(pdir, include_core=False)
    if not candidates:
        candidates = _list_available_ws_profiles(pdir, include_core=True)
    return max(1, int(VPN_MAX_STRICT_RETRIES), len(candidates))

def _compare_ext_version_tuple(v_str):
    """對齊 bm.js compareVersionStrings：將版本字串轉為可比較 tuple。"""
    parts = []
    for p in str(v_str or "").replace("_", ".").split("."):
        parts.append((0, int(p)) if p.isdigit() else (1, p))
    return tuple(parts)

def _discover_unpacked_extensions(profile_dir):
    """對齊 bm.js collectRamExtensionDirs：每個 <ext_id> 取最新含 manifest.json 之版本目錄。"""
    ext_root = Path(profile_dir) / "Default" / "Extensions"
    paths = []
    try:
        if ext_root.is_dir():
            for ext_dir in sorted(ext_root.iterdir(), key=lambda d: d.name):
                if not ext_dir.is_dir():
                    continue
                ver_dirs = []
                for vd in ext_dir.iterdir():
                    if vd.is_dir() and (vd / "manifest.json").is_file():
                        ver_dirs.append(vd)
                if ver_dirs:
                    ver_dirs.sort(key=lambda d: _compare_ext_version_tuple(d.name))
                    paths.append(str(ver_dirs[-1].resolve()))
    except OSError:
        pass
    return paths

def _build_chromium_launch_args(profile_dir, load_extensions=True):
    """應 58325 #3a & 58489 & 59406（Fix 2）& 59663：Stage A 掛載 extension 收割；Stage B Watch browser 強制 --disable-extensions 及 --disable-quic；
    應 59663（owner 實證）：起 Chrome 一律加 --password-store=basic，避免 OS keyring 綁死單機導致跨機（server→workshop→ramdisk）Google 登入態失效。"""
    ext_paths = _discover_unpacked_extensions(profile_dir) if load_extensions else []
    base_args = [
        "--password-store=basic",
        "--test-type",
        "--no-sandbox",
        "--disable-setuid-sandbox",
        "--disable-gpu",
        "--disable-dev-shm-usage",
        "--disable-blink-features=AutomationControlled",
        "--disable-infobars",
        "--no-first-run",
        "--no-default-browser-check",
        "--disable-crash-reporter",
        "--disable-breakpad",
        "--disable-component-update",
        "--disable-quic",
    ]
    if ext_paths:
        csv_paths = ",".join(ext_paths)
        base_args.append(f"--disable-extensions-except={csv_paths}")
        base_args.append(f"--load-extension={csv_paths}")
    else:
        base_args.append("--disable-extensions")
    base_args.extend([
        "--hide-crash-restore-bubble",
        "--disable-session-crashed-bubble",
        "--disable-features=TranslateUI,PrivacySandboxSettings4,OptimizationGuideModelExecution,ChromeWhatsNewUI,AutomationControlled,RestoreOnStartup",
        "--use-gl=swiftshader",
        "--disable-popup-blocking",
        "--disable-notifications",
        "--force-device-scale-factor=1",
        "--high-dpi-support=1",
        "--window-position=0,0",
        "--window-size=1408,900",
    ])
    return base_args

import atexit as _atexit, base64 as _base64, socket as _socket, ssl as _ssl, struct as _struct, threading as _threading

_SEAT_CHAIN_PROXIES = {}
_SEAT_CHAIN_LOCK = _threading.Lock()
_SEAT_UPSTREAM_ROTATION_IDX = {}
_SEAT_LAST_UPSTREAM_HOST = {}
_SEAT_LAST_EXIT_IP = {}

def _ws_b64_decode(val):
    if not isinstance(val, str) or not val:
        return ""
    s = val.strip()
    try:
        dec = _base64.b64decode(s + ("=" * ((-len(s)) % 4)), validate=False).decode("utf-8")
        if dec and all(32 <= ord(c) <= 126 for c in dec):
            return dec
    except Exception:
        pass
    return s

def _collect_ws_hosts_recursive(obj, add_host_fn, depth=0):
    """由 chrome.storage.local 內嘅 serverList / locations / nodes / PAC 遞迴提取所有可用 Windscribe proxy hosts。"""
    if depth > 6 or obj is None:
        return
    if isinstance(obj, str):
        if "HTTPS " in obj:
            for m in re.finditer(r"HTTPS\s+([A-Za-z0-9.-]+\.[A-Za-z]{2,}):(\d+)", obj):
                add_host_fn(m.group(1))
        return
    if isinstance(obj, (list, tuple)):
        for item in obj:
            _collect_ws_hosts_recursive(item, add_host_fn, depth + 1)
        return
    if isinstance(obj, dict):
        for hk in ("hostname", "host", "proxyHost"):
            hv = obj.get(hk)
            if (
                isinstance(hv, str)
                and hv != obj.get("ovpn_x509")
                and "." in hv
                and " " not in hv
                and not re.match(r"^m\d+\.", hv.strip())
            ):
                add_host_fn(hv)
        for lk in ("hosts", "nodes", "groups", "locations", "serverList", "data", "info", "pro"):
            if lk in obj:
                lv = obj.get(lk)
                if lk == "hosts" and isinstance(lv, (list, tuple)):
                    for h_item in lv:
                        if isinstance(h_item, str):
                            add_host_fn(h_item)
                        elif isinstance(h_item, dict):
                            add_host_fn(h_item.get("hostname") or h_item.get("host"))
                else:
                    _collect_ws_hosts_recursive(lv, add_host_fn, depth + 1)

def _unwrap_json_dict(d):
    """將 dict 入面可能係 JSON 字串嘅 value 解開成 dict/list。"""
    if not isinstance(d, dict):
        return {}
    out = {}
    for k, v in d.items():
        if isinstance(v, str) and (
            (v.strip().startswith("{") and v.strip().endswith("}"))
            or (v.strip().startswith("[") and v.strip().endswith("]"))
        ):
            try:
                out[k] = json.loads(v)
                continue
            except Exception:
                pass
        out[k] = v
    return out

def _find_nested_dict_by_pred(obj, pred, depth=0):
    if depth > 6 or not isinstance(obj, dict):
        return None
    if pred(obj):
        return obj
    for k, v in obj.items():
        if str(k).startswith("admin."):
            continue
        if isinstance(v, dict):
            found = _find_nested_dict_by_pred(v, pred, depth + 1)
            if found is not None:
                return found
    return None

# Windscribe MV2/MV3 publicly advertise exactly these secure-proxy ports and
# generate PAC entries as ``HTTPS host:port``.  Never infer plaintext from a
# TLS error and never probe arbitrary ports.
_WS_SECURE_PROXY_PORTS = (443, 9443)


def _coerce_ws_secure_proxy_port(value, depth=0):
    """Extract a supported Windscribe HTTPS-proxy port from Redux wrappers."""
    if depth > 4 or isinstance(value, bool) or value is None:
        return None
    if isinstance(value, (int, float)):
        iv = int(value)
        return iv if iv == value and iv in _WS_SECURE_PROXY_PORTS else None
    if isinstance(value, str):
        s = value.strip().strip("\"'")
        return int(s) if s in tuple(str(p) for p in _WS_SECURE_PROXY_PORTS) else None
    if isinstance(value, dict):
        for key in ("state", "value", "proxyPort", "port", "payload"):
            if key in value:
                found = _coerce_ws_secure_proxy_port(value.get(key), depth + 1)
                if found is not None:
                    return found
    if isinstance(value, (list, tuple)):
        for item in value:
            found = _coerce_ws_secure_proxy_port(item, depth + 1)
            if found is not None:
                return found
    return None


def _coerce_bounded_tcp_port(value):
    """Compatibility for hermetic injected TLS listeners; harvest never uses it."""
    if isinstance(value, bool):
        return None
    try:
        port = int(value)
    except (TypeError, ValueError):
        return None
    return port if 1 <= port <= 65535 else None


def _ws_secure_proxy_port_candidates(configured_port):
    """Configured port first; alternate only for real Windscribe TLS ports."""
    configured = _coerce_ws_secure_proxy_port(configured_port)
    if configured is not None:
        return (configured,) + tuple(p for p in _WS_SECURE_PROXY_PORTS if p != configured)
    # Existing hermetic suites inject an ephemeral local TLS proxy.  Preserve
    # that one port without inventing an alternate.  Real harvest metadata is
    # separately allowlisted by _coerce_ws_secure_proxy_port.
    injected = _coerce_bounded_tcp_port(configured_port)
    return (injected,) if injected is not None else _WS_SECURE_PROXY_PORTS


def _ws_should_try_alternate_secure_port(exc):
    """Retry only the observed TLS protocol/port mismatch, never generic failures."""
    if not isinstance(exc, _ssl.SSLError):
        return False
    reason = str(getattr(exc, "reason", "") or "").upper()
    text = str(exc).upper()
    return "WRONG_VERSION_NUMBER" in reason or "WRONG_VERSION_NUMBER" in text or "WRONG VERSION NUMBER" in text


def _extract_ws_config_from_storage(storage_dict):
    """由 chrome.storage.local.get(null) 提取 serverCredentials（base64 decode）、proxy.hosts 及 serverList 跨節點 hosts、proxyPort（純 RAM 處理，零憑證 log）。"""
    if not isinstance(storage_dict, dict):
        return {"ok": False, "hosts": [], "port": 443, "username": "", "password": "", "reason": "non-dict-storage"}
    unwrapped = _unwrap_json_dict(storage_dict)
    # 應 59423：Windscribe chrome.storage.local 結構嵌套喺 key "1" 入面（{"1": {"serverCredentials": ..., "proxy": ...}, "admin.*": ...}）
    if isinstance(unwrapped.get("1"), dict):
        ws_root = _unwrap_json_dict(unwrapped["1"])
        for sub_k, sub_v in ws_root.items():
            unwrapped[sub_k] = sub_v
    else:
        for top_k, top_v in list(unwrapped.items()):
            if str(top_k).startswith("admin.") or not isinstance(top_v, dict):
                continue
            sub_d = _unwrap_json_dict(top_v)
            if "serverCredentials" in sub_d or "proxy" in sub_d:
                for sub_k, sub_v in sub_d.items():
                    unwrapped.setdefault(sub_k, sub_v)
    raw_plain = bool(unwrapped.get("_plain_credentials"))
    creds = unwrapped.get("serverCredentials")
    if isinstance(creds, str):
        try:
            creds = json.loads(creds)
        except Exception:
            creds = None
    if not isinstance(creds, dict) or not (creds.get("username") and creds.get("password")):
        creds = None
        for k, v in unwrapped.items():
            if str(k).startswith("admin."):
                continue
            if isinstance(v, dict) and v.get("username") and v.get("password"):
                creds = v
                if "cred" in str(k).lower() or "server" in str(k).lower():
                    break
        if creds is None:
            creds = _find_nested_dict_by_pred(
                unwrapped,
                lambda d: isinstance(d.get("serverCredentials"), dict)
                and bool(d["serverCredentials"].get("username") and d["serverCredentials"].get("password")),
            )
            if isinstance(creds, dict) and isinstance(creds.get("serverCredentials"), dict):
                creds = creds["serverCredentials"]
            else:
                creds = _find_nested_dict_by_pred(
                    unwrapped,
                    lambda d: bool(d.get("username") and d.get("password")),
                )
    username = password = ""
    if isinstance(creds, dict):
        u_raw, p_raw = str(creds.get("username") or "").strip(), str(creds.get("password") or "").strip()
        username = u_raw if (raw_plain or creds.get("_plain")) else _ws_b64_decode(u_raw)
        password = p_raw if (raw_plain or creds.get("_plain")) else _ws_b64_decode(p_raw)
    hosts, proxy_port = [], None
    def _add_host(h):
        if isinstance(h, dict):
            h = h.get("hostname") or h.get("host") or h.get("proxyHost")
        if isinstance(h, str):
            hc = h.strip()
            if hc and "." in hc and " " not in hc and hc not in hosts:
                hosts.append(hc)
    proxy_obj = unwrapped.get("proxy")
    if isinstance(proxy_obj, str):
        try:
            proxy_obj = json.loads(proxy_obj)
        except Exception:
            proxy_obj = None
    if not isinstance(proxy_obj, dict):
        holder = _find_nested_dict_by_pred(
            unwrapped,
            lambda d: isinstance(d.get("proxy"), dict) and bool(d["proxy"].get("hosts") or d["proxy"].get("host")),
        )
        if isinstance(holder, dict):
            proxy_obj = holder.get("proxy")
    if isinstance(proxy_obj, dict):
        for h in (proxy_obj.get("hosts") or ()):
            _add_host(h)
        _add_host(proxy_obj.get("host"))
        for pk in ("proxyPort", "port"):
            if proxy_obj.get(pk) is not None:
                proxy_port = _coerce_ws_secure_proxy_port(proxy_obj.get(pk))
                if proxy_port is not None:
                    break
    if unwrapped.get("proxyPort") is not None and proxy_port is None:
        proxy_port = _coerce_ws_secure_proxy_port(unwrapped.get("proxyPort"))
    # 應 59419 問題二：除咗當前 proxy.hosts，一併由 serverList / locations 收集備選跨地區/多節點 hosts 供換 URL 時輪換新 IP
    for k, v in unwrapped.items():
        if k in ("proxy", "serverCredentials") or str(k).startswith("admin."):
            continue
        if isinstance(v, dict):
            for h in (v.get("hosts") or v.get("nodes") or ()):
                _add_host(h.get("hostname") or h.get("host") if isinstance(h, dict) else h)
            _collect_ws_hosts_recursive(v, _add_host, depth=1)
        elif isinstance(v, (list, tuple)):
            _collect_ws_hosts_recursive(v, _add_host, depth=1)
        elif isinstance(v, str) and "HTTPS " in v:
            for m in re.finditer(r"HTTPS\s+([A-Za-z0-9.-]+\.[A-Za-z]{2,}):(\d+)", v):
                _add_host(m.group(1))
                if proxy_port is None:
                    proxy_port = _coerce_ws_secure_proxy_port(m.group(2))
    port_final = _coerce_ws_secure_proxy_port(proxy_port) or 443
    if not username or not password:
        return {"ok": False, "hosts": hosts, "port": port_final, "username": "", "password": "", "reason": "missing-serverCredentials"}
    if not hosts:
        return {"ok": False, "hosts": [], "port": port_final, "username": "", "password": "", "reason": "missing-proxy-hosts"}
    return {"ok": True, "hosts": hosts, "port": port_final, "username": username, "password": password, "reason": None}

def _harvest_ws_config_from_leveldb(profile_dir, profiles_dir=None):
    """直接由磁碟 LevelDB (Default/Local Extension Settings/<ext_id>/*.ldb 及 *.log) 提取最新 fulfilled serverCredentials 與 proxy.hosts（.ldb 先、.log 後以覆蓋舊 idle 狀態，免起臨時 browser 亦防 service worker 重置）。"""
    cand_dirs = []
    if profile_dir is not None:
        cand_dirs.append(Path(profile_dir) / "Default" / "Local Extension Settings" / VPN_EXTENSION_ID)
        meta_p = Path(profile_dir) / ".active_ws_extension.json"
        if meta_p.is_file():
            try:
                ws_nm = json.loads(meta_p.read_text(encoding="utf-8")).get("ws_profile")
                if ws_nm and _WS_PROFILE_NAME_RE.match(str(ws_nm)):
                    pdir = _resolve_ws_profiles_dir(profiles_dir)
                    cand_dirs.append(Path(pdir) / str(ws_nm) / "Default" / "Local Extension Settings" / VPN_EXTENSION_ID)
            except Exception:
                pass
    for ldb_dir in cand_dirs:
        if not ldb_dir.is_dir():
            continue
        try:
            files = [
                f for f in ldb_dir.iterdir()
                if f.is_file() and f.suffix in (".ldb", ".log")
            ]
        except OSError:
            continue
        if not files:
            continue
        files.sort(key=lambda f: (1 if f.suffix == ".log" else 0, f.name))
        username = password = ""
        proxy_hosts = []
        fallback_hosts = []
        proxy_port = None
        for fp in files:
            try:
                text = fp.read_bytes().decode("utf-8", errors="ignore").replace('\\"', '"')
            except Exception:
                continue
            # Preserve transport metadata from the newest Redux/LevelDB record.
            # The old fast path discarded this field and always returned 443,
            # even when the extension was configured for its other HTTPS port.
            port_hits = []
            for port_rx in (
                r'"proxyPort"\s*:\s*["\']?(443|9443)["\']?',
                r'"proxyPort"\s*:\s*\{[^{}]{0,512}?"state"\s*:\s*["\']?(443|9443)["\']?',
            ):
                for pm in re.finditer(port_rx, text):
                    port_hits.append((pm.start(), pm.group(1)))
            for _pos, port_s in sorted(port_hits):
                parsed_port = _coerce_ws_secure_proxy_port(port_s)
                if parsed_port is not None:
                    proxy_port = parsed_port
            for m in re.finditer(r'"serverCredentials"\s*:\s*\{([^}]+)\}', text):
                try:
                    d = json.loads("{" + m.group(1) + "}")
                    u = str(d.get("username") or "").strip()
                    pw = str(d.get("password") or "").strip()
                    if u and pw:
                        username = _ws_b64_decode(u)
                        password = _ws_b64_decode(pw)
                except Exception:
                    pass
            for m in re.finditer(r'"proxy"\s*:\s*\{[^{}]*"hosts"\s*:\s*(\[[^\]]+\])', text):
                raw_arr = m.group(1)
                cur = []
                try:
                    arr = json.loads(raw_arr)
                    for item in arr:
                        h = (item.get("hostname") or item.get("host") or item.get("proxyHost")) if isinstance(item, dict) else item
                        if isinstance(h, str) and "." in h and " " not in h and h.strip() not in cur:
                            cur.append(h.strip())
                except Exception:
                    for hm in re.finditer(r"([a-z]{2,}[a-z0-9-]*-\d+\.[a-z0-9.-]+)", raw_arr):
                        if hm.group(1) not in cur:
                            cur.append(hm.group(1))
                if cur:
                    proxy_hosts = cur
            for m in re.finditer(r"\b([a-z]{2,}[a-z0-9-]*-\d+\.totallyacdn\.com)\b", text):
                h = m.group(1)
                if h not in fallback_hosts:
                    fallback_hosts.append(h)
        hosts = list(proxy_hosts) + [h for h in fallback_hosts if h not in proxy_hosts]
        port_final = _coerce_ws_secure_proxy_port(proxy_port) or 443
        port_source = "leveldb-persisted" if proxy_port is not None else "leveldb-default"
        if username and password and hosts:
            return {"ok": True, "hosts": hosts, "port": port_final, "port_source": port_source, "username": username, "password": password, "reason": None, "source": "leveldb"}
    return {"ok": False, "hosts": [], "port": 443, "port_source": "leveldb-default", "username": "", "password": "", "reason": "leveldb-empty"}

def _stage_a_harvest_windscribe(p, sid, profile_dir, socks_port, timeout_ms=None):
    """應 59406 Stage A：優先由磁碟 LevelDB (.ldb/.log) 直接收割 fulfilled serverCredentials 與 proxy.hosts；若無則以 socks5://127.0.0.1:<socks_port> ＋ --load-extension 開 popup 收割，收割完即關 browser。"""
    ldb_parsed = _harvest_ws_config_from_leveldb(profile_dir)
    if ldb_parsed.get("ok"):
        log(sid, f"✅ [VPN-CHAIN:STAGE-A] LevelDB 直接收割成功（免開臨時 browser）：hosts={ldb_parsed['hosts'][:4]} (共 {len(ldb_parsed['hosts'])} 粒) port={ldb_parsed['port']} port_source={ldb_parsed.get('port_source', 'unknown')} creds_present=True")
        return ldb_parsed
    t_ms = int(timeout_ms if timeout_ms is not None else VPN_STAGE_A_TIMEOUT_MS)
    stage_a_browser = ext_page = None
    last_reason = "stage-a-not-run"
    storage_js = """() => new Promise((resolve) => {
        try {
            if (typeof chrome === 'undefined' || !chrome.storage || !chrome.storage.local)
                return resolve({ __err: 'no-chrome-storage-local' });
            chrome.storage.local.get(null, (items) => {
                if (chrome.runtime && chrome.runtime.lastError)
                    resolve({ __err: String(chrome.runtime.lastError.message || 'lastError') });
                else resolve(items || {});
            });
        } catch (e) { resolve({ __err: String(e && e.message || e) }); }
    })"""
    try:
        _clear_stale_singleton_locks(profile_dir)
        log(sid, f"[VPN-CHAIN:STAGE-A] 啟動收割 browser（proxy=socks5://127.0.0.1:{socks_port}, load_extensions=True）")
        stage_a_browser = p.chromium.launch_persistent_context(
            str(profile_dir), headless=False, device_scale_factor=1,
            proxy={"server": f"socks5://127.0.0.1:{socks_port}"},
            args=_build_chromium_launch_args(profile_dir, load_extensions=True),
            ignore_default_args=["--enable-automation"], viewport={"width": 1400, "height": 900},
        )
        if stage_a_browser is None:
            return {"ok": False, "hosts": [], "port": 443, "username": "", "password": "", "reason": "launch-returned-none"}
        ext_page = stage_a_browser.new_page() if hasattr(stage_a_browser, "new_page") else (
            stage_a_browser.pages[0] if getattr(stage_a_browser, "pages", None) else None
        )
        if ext_page is None:
            return {"ok": False, "hosts": [], "port": 443, "username": "", "password": "", "reason": "no-ext-page"}
        ext_page.goto(VPN_POPUP_URL, wait_until="domcontentloaded", timeout=min(30000, max(5000, t_ms)))
        deadline = time.time() + max(0.5, float(t_ms) / 1000.0)
        while True:
            try:
                raw_items = ext_page.evaluate(storage_js)
                if isinstance(raw_items, dict):
                    if raw_items.get("__err"):
                        last_reason = f"storage-err:{raw_items.get('__err')}"
                    else:
                        parsed = _extract_ws_config_from_storage(raw_items)
                        if parsed.get("ok"):
                            log(sid, f"✅ [VPN-CHAIN:STAGE-A] 收割成功（未撳 Connect）：hosts={parsed['hosts']} port={parsed['port']} socks=127.0.0.1:{socks_port} auth_ready=True")
                            return parsed
                        last_reason = parsed.get("reason") or "incomplete-storage"
                else:
                    last_reason = f"bad-eval-type:{type(raw_items).__name__}"
            except Exception as eval_e:
                last_reason = f"eval-exc:{type(eval_e).__name__}"
            if time.time() >= deadline:
                break
            time.sleep(0.4)
    except Exception as e:
        last_reason = f"stage-a-exc:{type(e).__name__}:{e}"
    finally:
        for obj in (ext_page, stage_a_browser):
            if obj is not None:
                try:
                    obj.close()
                except Exception:
                    pass
        try:
            _clear_stale_singleton_locks(profile_dir)
        except Exception:
            pass
        time.sleep(0.2)
    log(sid, f"❌ [VPN-CHAIN:STAGE-A] 收割失敗（reason={last_reason}）")
    return {"ok": False, "hosts": [], "port": 443, "username": "", "password": "", "reason": last_reason}

def _seat_chain_preferred_port(sid, socks_port=None):
    env_p = os.environ.get(f"VPN_CHAIN_PORT_{str(sid or '').upper()}") or os.environ.get("VPN_CHAIN_PORT")
    if env_p:
        try:
            return int(env_p)
        except Exception:
            pass
    s = str(sid or "").upper()
    if s == "A2":
        return 18080
    m = re.search(r"(\d+)$", s)
    if m:
        return 18080 + (int(m.group(1)) % 100)
    return 18080 + (int(socks_port) - 11080) if socks_port else VPN_CHAIN_BASE_PORT

_GOOGLE_ACCOUNT_EXACT_HOSTS = frozenset({
    "accounts.google.com",
    "myaccount.google.com",
    "ogs.google.com",
    "apis.google.com",
    "accounts.youtube.com",
    "ssl.gstatic.com",
    "www.gstatic.com",
    "gstatic.com",
    "www.googleapis.com",
    "oauth2.googleapis.com",
    "content-autofill.googleapis.com",
})
_GOOGLE_ACCOUNT_DOMAIN_SUFFIXES = (
    ".accounts.google.com",
    ".myaccount.google.com",
    ".gstatic.com",
    ".googleusercontent.com",
    ".googleapis.com",
)
_SERVER_DIRECT_CONF_KEYS = frozenset({"SERVER_DIRECT", "DIRECT", "SERVER", "GOOGLE_DIRECT", "OWNER_SERVER_DIRECT"})
_DEFAULT_SERVER_DIRECT_SOCKS_PORT = 11090
_EXPECTED_SERVER_DIRECT_EXIT_IP = "149.118.48.126"
_SERVER_DIRECT_DOWN_HINT = (
    "[R13:SERVER-DIRECT-DOWN] Google server-direct carrier 11090 無 listener。"
    "請喺 VM 執行 ssh -D 11090 經 server 出，或者喺 vpn-proxies.conf 加 SERVER_DIRECT 行。"
    "絕不 fallback 經 tunnel 池或 VM 直出。"
)


def _is_google_account_destination(dest_host):
    """應 Owner 60454/60455 + A65 V2-037 + A87 60458：嚴格白名單判定 Google account 相關頁面（嚴禁模糊 substring 或 browser bypass-list）。"""
    h = str(dest_host or "").strip().strip("[]").lower().rstrip(".")
    if not h or "/" in h or ":" in h or " " in h:
        return False
    if re.match(r"^(?:\d{1,3}\.){3}\d{1,3}$", h):
        return False
    if h in _GOOGLE_ACCOUNT_EXACT_HOSTS:
        return True
    for sfx in _GOOGLE_ACCOUNT_DOMAIN_SUFFIXES:
        if h.endswith(sfx) and len(h) > len(sfx):
            return True
    return False


def _classify_destination_route(dest_host):
    """每次 CONNECT / HTTP 請求動態分類：明確 Google account 目的地行 google_server_direct（經 149.118.48.126 直出），其餘所有目的地一律行 ws_tunnel_chain（經 11080..11086 + 62 粒 WS hosts）。"""
    if _is_google_account_destination(dest_host):
        return "google_server_direct"
    return "ws_tunnel_chain"


def _resolve_server_direct_socks_ports(explicit_ports=None, exclude_ports=()):
    """應 Owner 60454/60455 + A65 60456/60457：解析通往 Owner Server (149.118.48.126) 直出嘅本機核准 SOCKS5 forward 端口；嚴格排除 11080..11086 WireGuard tunnel 端口及 watcher 自身端口。若未配置或不可達則 fail-closed。"""
    excl = set(_DEFAULT_SERVER_TUNNEL_PORTS) if "_DEFAULT_SERVER_TUNNEL_PORTS" in globals() else {11080, 11081, 11082, 11083, 11084, 11085, 11086}
    for x in (exclude_ports or ()):
        px = _coerce_bounded_tcp_port(x)
        if px is not None:
            excl.add(px)
    raw_list = []
    if explicit_ports is not None:
        raw_list = list(explicit_ports)
    else:
        env_raw = os.environ.get("WATCHER_SERVER_DIRECT_SOCKS_PORTS") or os.environ.get("WATCHER_SERVER_DIRECT_SOCKS_PORT") or ""
        if env_raw.strip():
            for tok in re.split(r"[\s,;]+", env_raw.strip()):
                if tok:
                    raw_list.append(tok)
        if not raw_list:
            try:
                v_path = (Path(SYSTEM_DIR) / "vpn-proxies.conf") if ("_DEFAULT_SYSTEM_DIR" in globals() and SYSTEM_DIR != _DEFAULT_SYSTEM_DIR and (Path(SYSTEM_DIR) / "vpn-proxies.conf").exists()) else VPN_CONF
                if Path(v_path).exists():
                    with open(v_path) as f:
                        for line in f:
                            line = line.strip()
                            if not line or line.startswith("#"):
                                continue
                            parts = [p.strip() for p in line.split("|")] if "|" in line else line.split()
                            if len(parts) >= 2 and parts[0].strip().upper() in _SERVER_DIRECT_CONF_KEYS:
                                raw_list.append(parts[1])
            except Exception:
                pass
        if not raw_list:
            raw_list.append(_DEFAULT_SERVER_DIRECT_SOCKS_PORT)
    out = []
    for item in raw_list:
        p_int = _coerce_bounded_tcp_port(item)
        if p_int is None or p_int in excl or p_int in out:
            continue
        if "_is_port_owned_by_watcher_runtime" in globals() and _is_port_owned_by_watcher_runtime(p_int):
            continue
        out.append(p_int)
    return tuple(out[:4])


class _WindscribeChainProxy:
    """應 59406 Stage B & 59414：內建純 Python Chain Proxy（Browser HTTP CONNECT -> 席位 SOCKS5 -> TLS -> Windscribe HTTPS Proxy）。"""
    def __init__(self, sid, preferred_port=18080, ssl_context=None):
        self.sid = str(sid or "UNKNOWN").upper()
        self.preferred_port = int(preferred_port or 18080)
        self.listen_port = None
        self.ssl_context = ssl_context
        self._lock = _threading.Lock()
        self._socks_host = "127.0.0.1"
        self._socks_port = None
        self._server_tunnel_ports = ()
        self._server_direct_ports = None
        self._upstream_hosts = []
        self._upstream_port = 443
        self._upstream_ports = _ws_secure_proxy_port_candidates(443)
        self._auth_b64 = None
        self._server_sock = None
        self._running = False
        self.tunnel_ok_count = 0
        self.tunnel_err_count = 0
        self.google_direct_ok_count = 0
        self.google_direct_err_count = 0
        self.last_ok_host = None
        self.last_ok_tunnel_port = None
        self.last_ok_direct_port = None
        self.last_route_decision = None
        self.last_error = None

    def update_upstream(self, socks_port, hosts, proxy_port, username, password, socks_host="127.0.0.1", server_tunnel_ports=None, server_direct_ports=None):
        clean_hosts = [str(h).strip() for h in (hosts or []) if str(h).strip()]
        if not clean_hosts or not username or not password:
            raise ValueError("Chain proxy requires non-empty upstream hosts and credentials")
        token = _base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
        configured_port = _coerce_ws_secure_proxy_port(proxy_port) or _coerce_bounded_tcp_port(proxy_port)
        if configured_port is None:
            raise ValueError("invalid secure-proxy port")
        t_ports = []
        for tp in ([socks_port] + list(server_tunnel_ports or ())):
            p_i = _coerce_bounded_tcp_port(tp)
            if p_i is not None and p_i not in t_ports:
                t_ports.append(p_i)
        with self._lock:
            self._socks_host, self._socks_port = str(socks_host or "127.0.0.1"), int(socks_port)
            self._server_tunnel_ports = tuple(t_ports[:7])
            if server_direct_ports is not None:
                self._server_direct_ports = tuple(
                    int(p) for p in server_direct_ports if _coerce_bounded_tcp_port(p) is not None
                )
            self._upstream_hosts, self._upstream_port = clean_hosts, configured_port
            self._upstream_ports = _ws_secure_proxy_port_candidates(configured_port)
            self._auth_b64 = token

    @property
    def socks_port(self):
        with self._lock:
            return self._socks_port

    @property
    def upstream_hosts(self):
        with self._lock:
            return list(self._upstream_hosts)

    @property
    def upstream_port(self):
        with self._lock:
            return self._upstream_port

    def is_ready(self):
        with self._lock:
            return bool(self._running and self.listen_port and self._socks_port and self._upstream_hosts and self._auth_b64)

    def start(self):
        if self._running and self._server_sock is not None and self.listen_port:
            return self.listen_port
        for cp in [self.preferred_port] + [p for p in range(18080, 18190) if p != self.preferred_port] + [0]:
            s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
            s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
            try:
                s.bind(("127.0.0.1", cp))
                s.listen(128)
                self._server_sock, self.listen_port, self._running = s, s.getsockname()[1], True
                _threading.Thread(target=self._accept_loop, name=f"ws-chain-{self.sid}", daemon=True).start()
                return self.listen_port
            except OSError:
                s.close()
        raise RuntimeError("無法於 127.0.0.1 綁定本地 Chain Proxy port")

    def stop(self):
        self._running = False
        srv, self._server_sock = self._server_sock, None
        if srv is not None:
            try:
                srv.close()
            except Exception:
                pass
        with self._lock:
            self._auth_b64 = None

    def _accept_loop(self):
        while self._running and self._server_sock is not None:
            try:
                cli_sock, _ = self._server_sock.accept()
                try:
                    cli_sock.setsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 1)
                except Exception:
                    pass
                _threading.Thread(target=self._handle_client, args=(cli_sock,), daemon=True).start()
            except OSError:
                break
            except Exception:
                continue

    @staticmethod
    def _recv_exact(sock, n):
        buf = bytearray()
        while len(buf) < n:
            chunk = sock.recv(n - len(buf))
            if not chunk:
                raise ConnectionError("EOF during handshake")
            buf.extend(chunk)
        return bytes(buf)

    @classmethod
    def _socks5_connect(cls, socks_host, socks_port, dest_host, dest_port, timeout=15.0):
        s = _socket.create_connection((socks_host, int(socks_port)), timeout=timeout)
        try:
            s.setsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 1)
            s.sendall(b"\x05\x01\x00")
            ver, method = cls._recv_exact(s, 2)
            if ver != 5 or method != 0:
                raise RuntimeError(f"SOCKS5 auth failed: {ver}/{method}")
            hb = dest_host.encode("idna")
            s.sendall(b"\x05\x01\x00\x03" + bytes([len(hb)]) + hb + _struct.pack("!H", int(dest_port)))
            ver, rep, _rsv, atyp = cls._recv_exact(s, 4)
            if ver != 5 or rep != 0:
                raise RuntimeError(f"SOCKS5 connect {dest_host}:{dest_port} failed: rep={rep}")
            cls._recv_exact(s, 6 if atyp == 1 else (cls._recv_exact(s, 1)[0] + 2 if atyp == 3 else 18))
            return s
        except Exception:
            s.close()
            raise

    @staticmethod
    def _read_http_headers(sock, max_bytes=65536):
        buf = bytearray()
        while b"\r\n\r\n" not in buf:
            chunk = sock.recv(4096)
            if not chunk:
                break
            buf.extend(chunk)
            if len(buf) > max_bytes:
                raise ValueError("HTTP header too large")
        idx = buf.find(b"\r\n\r\n")
        if idx < 0:
            raise ConnectionError("incomplete HTTP headers")
        return bytes(buf[:idx + 4]), bytes(buf[idx + 4:])

    def _open_windscribe_tls_tunnel(self, target_host, target_port, timeout=6.0):
        with self._lock:
            socks_host, socks_port = self._socks_host, self._socks_port
            tunnel_ports = tuple(self._server_tunnel_ports) or ((int(socks_port),) if socks_port else ())
            hosts = list(self._upstream_hosts)
            up_ports = tuple(self._upstream_ports)
            auth_b64 = self._auth_b64
        if not socks_port or not hosts or not auth_b64:
            raise RuntimeError("Chain proxy upstream not configured")
        last_exc = None
        attempts = []
        per_host_timeout = min(max(float(timeout), 0.5), 4.5)
        for ws_host in hosts:
            for up_port in up_ports:
                raw_sock = tls_sock = None
                try:
                    chosen_tp = None
                    last_sock_err = None
                    for tp in tunnel_ports:
                        try:
                            raw_sock = self._socks5_connect(
                                socks_host, tp, ws_host, up_port, timeout=per_host_timeout,
                            )
                            chosen_tp = int(tp)
                            break
                        except Exception as se:
                            last_sock_err = se
                            raw_sock = None
                    if raw_sock is None:
                        raise (last_sock_err or RuntimeError("socks-connect-failed"))
                    ctx = self.ssl_context
                    if ctx is None:
                        ctx = _ssl.create_default_context()
                        try:
                            ctx.set_alpn_protocols(["http/1.1"])
                        except Exception:
                            pass
                    tls_sock, raw_sock = ctx.wrap_socket(raw_sock, server_hostname=ws_host), None
                    req = (
                        f"CONNECT {target_host}:{int(target_port)} HTTP/1.1\r\n"
                        f"Host: {target_host}:{int(target_port)}\r\n"
                        f"Proxy-Authorization: Basic {auth_b64}\r\n"
                        f"Proxy-Connection: keep-alive\r\n\r\n"
                    ).encode("latin-1")
                    tls_sock.sendall(req)
                    hdr_b, extra_b = self._read_http_headers(tls_sock)
                    parts = hdr_b.split(b"\r\n", 1)[0].decode("latin-1", errors="replace").split()
                    code = int(parts[1]) if len(parts) >= 2 and parts[1].isdigit() else 0
                    if code != 200:
                        raise RuntimeError(f"Upstream {ws_host}:{up_port} HTTP {code}")
                    tls_sock.settimeout(None)
                    with self._lock:
                        self.tunnel_ok_count += 1
                        self.last_ok_host, self.last_error = ws_host, None
                        self.last_ok_tunnel_port = chosen_tp
                        if chosen_tp is not None:
                            self._socks_port = chosen_tp
                            self._server_tunnel_ports = (chosen_tp,) + tuple(p for p in self._server_tunnel_ports if p != chosen_tp)
                        self._upstream_port = up_port
                        self._upstream_ports = (up_port,) + tuple(p for p in self._upstream_ports if p != up_port)
                        if ws_host in self._upstream_hosts and self._upstream_hosts[0] != ws_host:
                            self._upstream_hosts = [ws_host] + [h for h in self._upstream_hosts if h != ws_host]
                    return tls_sock, extra_b
                except Exception as e:
                    last_exc = e
                    attempts.append((int(up_port), type(e).__name__, bool(_ws_should_try_alternate_secure_port(e))))
                    for sck in (tls_sock, raw_sock):
                        if sck is not None:
                            try:
                                sck.close()
                            except Exception:
                                pass
                    if up_port == up_ports[0] and _ws_should_try_alternate_secure_port(e):
                        continue
                    break
            with self._lock:
                if ws_host in self._upstream_hosts:
                    self._upstream_hosts = [h for h in self._upstream_hosts if h != ws_host] + [ws_host]
        attempt_summary = ",".join(f"{p}:{cls}" for p, cls, _wrong in attempts)
        both_official_wrong = (
            {p for p, _cls, wrong in attempts if wrong} == set(_WS_SECURE_PROXY_PORTS)
            and all(wrong for _p, _cls, wrong in attempts)
        )
        diagnosis = "TLS_PATH_BLOCKED_BOTH_SECURE_PORTS" if both_official_wrong else "TLS_UPSTREAM_FAILED"
        structured = f"{diagnosis}:attempts={attempt_summary}:last={type(last_exc).__name__}"
        with self._lock:
            self.tunnel_err_count += 1
            self.last_error = structured
        raise RuntimeError(structured)

    @staticmethod
    def _pipe_stream(src, dst):
        try:
            while True:
                data = src.recv(65536)
                if not data:
                    break
                dst.sendall(data)
        except Exception:
            pass
        finally:
            try:
                dst.shutdown(_socket.SHUT_WR)
            except Exception:
                pass

    def _relay_bidirectional(self, sock_a, sock_b):
        t = _threading.Thread(target=self._pipe_stream, args=(sock_a, sock_b), daemon=True)
        t.start()
        self._pipe_stream(sock_b, sock_a)
        t.join(timeout=2.0)

    def _open_google_server_direct_tunnel(self, target_host, target_port, timeout=4.0):
        """應 Owner 60454/60455 + A65 V2-037 + A87 60458：Google account 頁面必須經 Owner Server (149.118.48.126) 直出 SOCKS5 carrier（ATYP=0x03 遠端 DNS），嚴禁經主持 VM 直出或混入 Windscribe；若 carrier 缺失即 fail-closed。"""
        with self._lock:
            socks_host = self._socks_host
            explicit_direct = self._server_direct_ports
            own_ports = (self.listen_port, self._socks_port) + tuple(self._server_tunnel_ports or ())
        direct_candidates = _resolve_server_direct_socks_ports(
            explicit_ports=explicit_direct, exclude_ports=own_ports
        )
        if not direct_candidates:
            unavail = f"SERVER_DIRECT_CARRIER_UNAVAILABLE:host={target_host}:no-configured-server-direct-port"
            with self._lock:
                self.google_direct_err_count += 1
                self.last_error = unavail
                self.last_route_decision = ("google_server_direct_blocked", str(target_host), None)
            raise RuntimeError(unavail)
        last_err = None
        per_timeout = min(max(float(timeout), 0.5), 4.5)
        for dp in direct_candidates:
            raw_sock = None
            try:
                raw_sock = self._socks5_connect(
                    socks_host, int(dp), str(target_host).strip("[]"), int(target_port), timeout=per_timeout
                )
                raw_sock.settimeout(None)
                with self._lock:
                    self.google_direct_ok_count += 1
                    self.last_ok_direct_port = int(dp)
                    self.last_error = None
                    self.last_route_decision = ("google_server_direct", str(target_host), int(dp))
                return raw_sock, b""
            except Exception as e:
                last_err = e
                if raw_sock is not None:
                    try:
                        raw_sock.close()
                    except Exception:
                        pass
        unavail = f"SERVER_DIRECT_CARRIER_UNAVAILABLE:host={target_host}:ports={direct_candidates}:last={type(last_err).__name__}"
        with self._lock:
            self.google_direct_err_count += 1
            self.last_error = unavail
            self.last_route_decision = ("google_server_direct_blocked", str(target_host), None)
        raise RuntimeError(unavail)

    def _open_routed_tunnel(self, target_host, target_port, timeout=4.0):
        """應 Owner 60454/60455 + A65 V2-037：每次 CONNECT / HTTP 請求重新分類目的地並分流至對應 carrier。"""
        clean_host = str(target_host or "").strip().strip("[]")
        route = _classify_destination_route(clean_host)
        if route == "google_server_direct":
            return self._open_google_server_direct_tunnel(clean_host, target_port, timeout=timeout)
        sock, extra = self._open_windscribe_tls_tunnel(clean_host, target_port, timeout=timeout)
        with self._lock:
            self.last_route_decision = ("ws_tunnel_chain", clean_host, self.last_ok_tunnel_port)
        return sock, extra

    def _handle_client(self, client_sock):
        tls_sock = None
        try:
            client_sock.settimeout(15.0)
            hdr_b, cli_extra = self._read_http_headers(client_sock)
            lines = hdr_b.decode("latin-1", errors="replace").split("\r\n")
            parts = (lines[0] if lines else "").split()
            if len(parts) < 3:
                client_sock.sendall(b"HTTP/1.1 400 Bad Request\r\n\r\n")
                return
            method, target, proto = parts[0].upper(), parts[1], parts[2]
            if method == "CONNECT":
                t_host, t_port = (target.rsplit(":", 1)[0], int(target.rsplit(":", 1)[1])) if ":" in target else (target, 443)
                tls_sock, up_extra = self._open_routed_tunnel(t_host.strip("[]"), t_port, timeout=4.0)
                client_sock.settimeout(None)
                client_sock.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
                if cli_extra:
                    tls_sock.sendall(cli_extra)
                if up_extra:
                    client_sock.sendall(up_extra)
                self._relay_bidirectional(client_sock, tls_sock)
            elif target.startswith("http://"):
                from urllib.parse import urlsplit as _urlsplit
                sp = _urlsplit(target)
                rel = (sp.path or "/") + (f"?{sp.query}" if sp.query else "")
                tls_sock, up_extra = self._open_routed_tunnel(sp.hostname or "", sp.port or 80, timeout=4.0)
                client_sock.settimeout(None)
                rebuilt = [f"{method} {rel} {proto}"] + [
                    "Connection: close" if hl.lower().startswith("proxy-connection:") else hl
                    for hl in lines[1:] if hl
                ]
                tls_sock.sendall(("\r\n".join(rebuilt) + "\r\n\r\n").encode("latin-1") + cli_extra)
                if up_extra:
                    client_sock.sendall(up_extra)
                self._relay_bidirectional(client_sock, tls_sock)
            else:
                client_sock.sendall(b"HTTP/1.1 405 Method Not Allowed\r\n\r\n")
        except Exception:
            try:
                client_sock.sendall(b"HTTP/1.1 502 Bad Gateway\r\n\r\n")
            except Exception:
                pass
        finally:
            for sck in (tls_sock, client_sock):
                if sck is not None:
                    try:
                        sck.close()
                    except Exception:
                        pass

_SEAT_EMBEDDED_SOCKS_BRIDGES = {}
_SEAT_EXTERNAL_SOCKS_PORTS = set()
ENABLE_EMBEDDED_SOCKS_BRIDGE = True


def _is_embedded_socks_bridge_enabled():
    if not globals().get("ENABLE_EMBEDDED_SOCKS_BRIDGE", True):
        return False
    env_v = os.environ.get("WATCHER_ENABLE_EMBEDDED_SOCKS_BRIDGE", "1").strip().lower()
    return env_v not in ("0", "false", "no", "off")


def _bootstrap_ws_extension_for_socks(p, sid, profile_dir, socks_port, wait_sec=None):
    """應 60165 & 60166 Step 2：當 11080 未通時，啟動臨時 Extension Bootstrap Browser（只開本機空白/extension popup，嚴禁連目標網站），令 extension 真運行／收割並 bounded 等待 11080。"""
    if p is None or not hasattr(p, "chromium"):
        return {"ok": False, "harvest": None, "socks_ready": False, "reason": "no-playwright"}
    sp_int = int(socks_port)
    w_sec = float(wait_sec if wait_sec is not None else os.environ.get("WATCHER_EXT_BOOTSTRAP_WAIT_SEC", "1.2"))
    boot_browser = ext_page = None
    harvested = None
    socks_ready = False
    storage_js = """() => new Promise((resolve) => {
        try {
            if (typeof chrome === 'undefined' || !chrome.storage || !chrome.storage.local)
                return resolve({ __err: 'no-chrome-storage-local' });
            chrome.storage.local.get(null, (items) => {
                if (chrome.runtime && chrome.runtime.lastError)
                    resolve({ __err: String(chrome.runtime.lastError.message || 'lastError') });
                else resolve(items || {});
            });
        } catch (e) { resolve({ __err: String(e && e.message || e) }); }
    })"""
    try:
        _clear_stale_singleton_locks(profile_dir)
        log(sid, f"🚀 [VPN-CHAIN:BOOTSTRAP] 127.0.0.1:{sp_int} 未通，啟動臨時 Extension Bootstrap Browser（proxy=socks5://127.0.0.1:{sp_int}，只開 popup.html，嚴禁直連目標網站）")
        boot_browser = p.chromium.launch_persistent_context(
            str(profile_dir),
            headless=False,
            device_scale_factor=1,
            proxy={"server": f"socks5://127.0.0.1:{sp_int}"},
            args=_build_chromium_launch_args(profile_dir, load_extensions=True),
            ignore_default_args=["--enable-automation"],
            viewport={"width": 1400, "height": 900},
        )
        if boot_browser is not None:
            ext_page = boot_browser.new_page() if hasattr(boot_browser, "new_page") else (
                boot_browser.pages[0] if getattr(boot_browser, "pages", None) else None
            )
            if ext_page is not None:
                ext_page.goto(VPN_POPUP_URL, wait_until="domcontentloaded", timeout=8000)
                deadline = time.time() + max(0.3, min(w_sec, 5.0))
                while True:
                    try:
                        raw_items = ext_page.evaluate(storage_js)
                        if isinstance(raw_items, dict) and not raw_items.get("__err"):
                            parsed = _extract_ws_config_from_storage(raw_items)
                            if parsed.get("ok"):
                                harvested = parsed
                    except Exception:
                        pass
                    st_probe, _ = _probe_external_socks5_ready(sp_int, "api.ipify.org", 443, sid=sid, timeout=0.6)
                    if st_probe == "external-ready":
                        socks_ready = True
                        break
                    if time.time() >= deadline:
                        break
                    time.sleep(0.25)
    except Exception as e:
        log(sid, f"⚠️ [VPN-CHAIN:BOOTSTRAP] Extension Bootstrap Browser 結束 ({type(e).__name__})")
    finally:
        for obj in (ext_page, boot_browser):
            if obj is not None:
                try:
                    obj.close()
                except Exception:
                    pass
        try:
            _clear_stale_singleton_locks(profile_dir)
        except Exception:
            pass
    return {"ok": bool(harvested or socks_ready), "harvest": harvested, "socks_ready": socks_ready}


def _sanitize_vpn_err(err_msg, username=None, password=None, auth_b64=None, *extra_secrets):
    s = str(err_msg or "")
    auto_b64 = None
    if username and password and not auth_b64:
        try:
            auto_b64 = _base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
        except Exception:
            auto_b64 = None
    all_secrets = [username, password, auth_b64, auto_b64, *extra_secrets]
    for secret in sorted([str(x).strip() for x in all_secrets if x and str(x).strip()], key=len, reverse=True):
        if len(secret) >= 2:
            s = s.replace(secret, "[REDACTED]")
        else:
            s = re.sub(rf"(?<![A-Za-z0-9]){re.escape(secret)}(?![A-Za-z0-9])", "[REDACTED]", s)
    s = re.sub(r"(?i)(Proxy-Authorization:\s*Basic\s+)[A-Za-z0-9+/=]+", r"\1[REDACTED]", s)
    s = re.sub(r"(https?://|socks5h?://)([^/@\s:]+):([^/@\s]+)@", r"\1[REDACTED]:[REDACTED]@", s)
    return s[:240]


def _partition_two_hop_ws_hosts(ordered_hosts):
    seen = set()
    uniq = []
    for h in (ordered_hosts or []):
        hs = str(h or "").strip()
        if hs and hs.lower() not in seen:
            seen.add(hs.lower())
            uniq.append(hs)
    if len(uniq) < 2:
        return [], [], "no-distinct-host"
    bridge_primary = uniq[0]
    chain_hosts = [h for h in uniq[1:] if h.lower() != bridge_primary.lower()]
    if not chain_hosts:
        return [], [], "no-distinct-host"
    # Give bridge_hosts fallback candidates from the tail that do not collide with chain_hosts[0]
    bridge_fallbacks = [h for h in reversed(uniq[1:]) if h.lower() != chain_hosts[0].lower() and h.lower() != bridge_primary.lower()]
    bridge_hosts = [bridge_primary] + bridge_fallbacks[:3]
    return bridge_hosts, chain_hosts, None


_DEFAULT_SERVER_TUNNEL_PORTS = (11080, 11081, 11082, 11083, 11084, 11085, 11086)


def _is_port_owned_by_watcher_runtime(port):
    p_int = _coerce_bounded_tcp_port(port)
    if p_int is None:
        return False
    with _SEAT_CHAIN_LOCK:
        for br in _SEAT_EMBEDDED_SOCKS_BRIDGES.values():
            if br is not None and p_int in (getattr(br, "socks_port", None), getattr(br, "listen_port", None)):
                return True
        for ch in _SEAT_CHAIN_PROXIES.values():
            if ch is not None and getattr(ch, "listen_port", None) == p_int:
                return True
    return False


_EMBEDDED_BRIDGE_BASE_PORT = 17080
_TUNNEL_FORWARD_FATAL_HINT = "VM→server tunnel forward 未通，呢個係 R13 頭號死因，先起返 tunnel 再試"


def _has_loopback_tcp_listener(port, timeout=0.25):
    """Owner 60495：只探測硬編碼 loopback tunnel-forward port，絕不探測外部或嘗試 VM-direct fallback。"""
    p_int = _coerce_bounded_tcp_port(port)
    if p_int not in _DEFAULT_SERVER_TUNNEL_PORTS:
        return False
    sock = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
    try:
        sock.settimeout(min(max(float(timeout), 0.05), 0.5))
        return sock.connect_ex(("127.0.0.1", p_int)) == 0
    except OSError:
        return False
    finally:
        try:
            sock.close()
        except Exception:
            pass


def _has_server_direct_loopback_listener(port, timeout=0.25):
    """Owner 60533/60538：只探測標準化 Google server-direct loopback carrier 11090；與 7-port tunnel helper 嚴格分離。"""
    p_int = _coerce_bounded_tcp_port(port)
    if p_int != _DEFAULT_SERVER_DIRECT_SOCKS_PORT:
        return False
    sock = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
    try:
        sock.settimeout(min(max(float(timeout), 0.05), 0.5))
        return sock.connect_ex(("127.0.0.1", p_int)) == 0
    except OSError:
        return False
    finally:
        try:
            sock.close()
        except Exception:
            pass


def _check_server_tunnel_forward_listeners(sid, phase="cycle"):
    """Owner 60495：啟動及每輪 cycle 檢查全 7 個 forward；全數無 listener 就明示頭號死因並 fail-closed。"""
    ready = tuple(p for p in _DEFAULT_SERVER_TUNNEL_PORTS if _has_loopback_tcp_listener(p))
    missing = tuple(p for p in _DEFAULT_SERVER_TUNNEL_PORTS if p not in ready)
    if not ready:
        log(sid, f"🛑 [R13:TUNNEL-FORWARD-DOWN:{str(phase).upper()}] {_TUNNEL_FORWARD_FATAL_HINT}")
        return False, {"ready": ready, "missing": missing, "reason": "SERVER_TUNNEL_FORWARD_UNAVAILABLE"}
    if missing:
        log(sid, f"⚠️ [R13:TUNNEL-FORWARD-DEGRADED:{str(phase).upper()}] ready={ready} missing={missing}；只准使用仍在生嘅 approved server tunnel，絕不 VM 直出")
    return True, {"ready": ready, "missing": missing, "reason": None}


def _preflight_check_server_tunnel_forwards(sid):
    ok, detail = _check_server_tunnel_forward_listeners(sid, phase="startup")
    if not ok:
        return False, _TUNNEL_FORWARD_FATAL_HINT
    return True, f"ready={detail.get('ready')} missing={detail.get('missing')}"


def _preflight_check_server_direct_carrier(sid, port=None, expected_ip=_EXPECTED_SERVER_DIRECT_EXIT_IP):
    """應 60533 #2/#3 + A87 60536/60539：啟動時強制檢查 Google server-direct carrier (11090)：
    1) 無 listener 即明確 FAIL 並印出三要素指引（絕不喺 watcher 內偷起 ssh 或靜默 fallback）；
    2) 必須經 127.0.0.1:11090 SOCKS5 探測出口 IP，並斷言出口 IP == 149.118.48.126 先准推。"""
    direct_ports = _resolve_server_direct_socks_ports()
    if port is None and not direct_ports:
        log(sid, f"🛑 {_SERVER_DIRECT_DOWN_HINT}")
        return False, _SERVER_DIRECT_DOWN_HINT
    target_port = int(port if port is not None else direct_ports[0])
    if not _has_server_direct_loopback_listener(target_port):
        log(sid, f"🛑 {_SERVER_DIRECT_DOWN_HINT}")
        return False, _SERVER_DIRECT_DOWN_HINT
    exit_ip, probe_err = _probe_socks_tunnel_exit_ip(target_port, sid=sid, timeout=5.0, allow_cached=False)
    if not exit_ip:
        msg = f"[R13:SERVER-DIRECT-EXIT-UNAVAILABLE] 經 127.0.0.1:{target_port} SOCKS5 無法探測出口 IP ({probe_err or 'none'})；預期出口={expected_ip}。{_SERVER_DIRECT_DOWN_HINT}"
        log(sid, f"🛑 {msg}")
        return False, msg
    if str(exit_ip).strip() != str(expected_ip).strip():
        msg = f"[R13:SERVER-DIRECT-EXIT-MISMATCH] 經 127.0.0.1:{target_port} SOCKS5 實測出口={exit_ip} != 預期 {expected_ip}。{_SERVER_DIRECT_DOWN_HINT}"
        log(sid, f"🛑 {msg}")
        return False, msg
    log(sid, f"✅ [PREFLIGHT:SERVER-DIRECT] 127.0.0.1:{target_port} 出口驗證通過 (exit_ip={exit_ip})")
    return True, f"port={target_port} exit_ip={exit_ip}"


_preflight_check_server_direct = _preflight_check_server_direct_carrier


def _resolve_configured_server_tunnel_ports(explicit_ports=None, exclude_ports=(), sid=None, preferred_port=None):
    """應 Owner 60445/60449 + A65 V2-036 + A87 60451 + 60533 #1：只由 vpn-proxies.conf / load_vpn_ports() 列出嘅 7 條本機 loopback server-tunnel SOCKS5 端口中 bounded 選擇，硬性排除所有 server-direct 端口 (11090)、bridge 自己 listener 同 chain port，並支援按席位輪換。"""
    excl = {_coerce_bounded_tcp_port(x) for x in (exclude_ports or ()) if _coerce_bounded_tcp_port(x) is not None}
    excl.add(_DEFAULT_SERVER_DIRECT_SOCKS_PORT)
    try:
        excl.update(_resolve_server_direct_socks_ports())
    except Exception:
        pass
    raw_list = []
    if explicit_ports is not None:
        raw_list = list(explicit_ports)
    else:
        try:
            vp = load_vpn_ports()
            if isinstance(vp, dict) and vp:
                raw_list = list(vp.values())
        except Exception:
            raw_list = []
        if not raw_list:
            raw_list = list(_DEFAULT_SERVER_TUNNEL_PORTS)
    out = []
    for item in raw_list:
        p_int = _coerce_bounded_tcp_port(item)
        if p_int is None or p_int in excl or p_int in out:
            continue
        if _is_port_owned_by_watcher_runtime(p_int):
            continue
        out.append(p_int)
    out = out[:7]
    if len(out) > 1 and sid and explicit_ports is None:
        s_key = str(sid).strip().upper()
        offset = sum(ord(c) for c in s_key) % len(out)
        out = out[offset:] + out[:offset]
    pref_i = _coerce_bounded_tcp_port(preferred_port)
    if pref_i is not None and pref_i in out:
        out = [pref_i] + [p for p in out if p != pref_i]
    return tuple(out)


def _resolve_non_colliding_bridge_bind_port(socks_port, server_tunnel_ports=()):
    """應 A87 60451 [三]#1：若 socks_port 屬於 11080..11086 server tunnel 範圍，內建 Bridge 改 bind 17080..17086 專用端口，絕不霸佔 11080..11086。"""
    sp_int = int(socks_port or 11080)
    reserved = set(_DEFAULT_SERVER_TUNNEL_PORTS) | {int(p) for p in (server_tunnel_ports or ()) if _coerce_bounded_tcp_port(p) is not None}
    if sp_int in reserved:
        offset = max(0, sp_int - 11080) if 11080 <= sp_int <= 11180 else (sp_int % 100)
        return _EMBEDDED_BRIDGE_BASE_PORT + offset
    return sp_int


class _EmbeddedWsSocksBridge:
    """應 60107, 60124 & Owner 60445/60449：Hop-1 必須經 server／7 條 tunnel 出網（嚴禁經主持 VM 直出），且絕不霸佔 11080..11086。"""
    def __init__(self, sid, socks_port, ssl_context=None, server_tunnel_ports=None, bind_port=None):
        self.sid = str(sid or "UNKNOWN").upper()
        self.socks_port = int(socks_port)
        self.bind_port = int(bind_port) if bind_port is not None else self.socks_port
        self.listen_port = None
        self.ssl_context = ssl_context
        self.server_tunnel_ports = tuple(server_tunnel_ports) if server_tunnel_ports is not None else None
        self.owned_by_watcher = True
        self._lock = _threading.Lock()
        self._bridge_hosts = []
        self._allowed_ws_hosts = set()
        self._upstream_port = 443
        self._upstream_ports = _ws_secure_proxy_port_candidates(443)
        self._auth_b64 = None
        self._server_sock = None
        self._active_socks = set()
        self._running = False
        self.tunnel_ok_count = 0
        self.tunnel_err_count = 0
        self.last_ok_host = None
        self.last_ok_tunnel_port = None
        self.last_error = None

    def update_upstream(self, bridge_hosts, all_harvested_hosts, proxy_port, username, password, server_tunnel_ports=None):
        clean_bridge = [str(h).strip() for h in (bridge_hosts or []) if str(h).strip()]
        allowed = {str(h).strip().lower() for h in (all_harvested_hosts or clean_bridge) if str(h).strip()}
        if not clean_bridge or not allowed or not username or not password:
            raise ValueError("Embedded SOCKS bridge requires non-empty WS hosts and credentials")
        for bh in clean_bridge:
            if bh.lower() not in allowed:
                raise ValueError(f"Bridge host {bh} not in harvested Windscribe host set")
        token = _base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
        configured_port = _coerce_ws_secure_proxy_port(proxy_port) or _coerce_bounded_tcp_port(proxy_port)
        if configured_port is None:
            raise ValueError("invalid secure-proxy port")
        with self._lock:
            self._bridge_hosts = clean_bridge
            self._allowed_ws_hosts = allowed
            self._upstream_port = configured_port
            self._upstream_ports = _ws_secure_proxy_port_candidates(configured_port)
            self._auth_b64 = token
            if server_tunnel_ports is not None:
                self.server_tunnel_ports = tuple(server_tunnel_ports)

    def is_ready(self):
        with self._lock:
            return bool(
                self._running
                and self.listen_port is not None
                and self._bridge_hosts
                and self._auth_b64
                and self.tunnel_ok_count > 0
            )

    def start(self):
        if self._running and self._server_sock is not None and self.listen_port is not None:
            return self.listen_port
        target_bind = int(self.bind_port or self.socks_port)
        cand_binds = [target_bind]
        if target_bind >= _EMBEDDED_BRIDGE_BASE_PORT:
            cand_binds.extend([p for p in range(_EMBEDDED_BRIDGE_BASE_PORT, _EMBEDDED_BRIDGE_BASE_PORT + 60) if p != target_bind])
        last_err = None
        for bp in cand_binds:
            s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
            s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
            try:
                s.bind(("127.0.0.1", bp))
                s.listen(128)
                self._server_sock = s
                self.listen_port = s.getsockname()[1]
                self._running = True
                _threading.Thread(
                    target=self._accept_loop, name=f"ws-socks-bridge-{self.sid}", daemon=True
                ).start()
                return self.listen_port
            except OSError as e:
                try:
                    s.close()
                except Exception:
                    pass
                last_err = e
        raise RuntimeError(f"socks-bind-conflict:{last_err}")

    def stop(self):
        self._running = False
        srv, self._server_sock = self._server_sock, None
        if srv is not None:
            try:
                srv.shutdown(_socket.SHUT_RDWR)
            except Exception:
                pass
            try:
                srv.close()
            except Exception:
                pass
        with self._lock:
            active = list(self._active_socks)
            self._active_socks.clear()
            self._auth_b64 = None
        for sck in active:
            try:
                sck.close()
            except Exception:
                pass

    def _accept_loop(self):
        while self._running and self._server_sock is not None:
            try:
                cli_sock, _ = self._server_sock.accept()
                try:
                    cli_sock.setsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 1)
                except Exception:
                    pass
                with self._lock:
                    self._active_socks.add(cli_sock)
                _threading.Thread(target=self._handle_socks_client, args=(cli_sock,), daemon=True).start()
            except OSError:
                break
            except Exception:
                continue

    def _open_hop1_ws_tls_tunnel(self, dest_host, dest_port, timeout=4.5):
        with self._lock:
            bridge_hosts = list(self._bridge_hosts)
            allowed_set = set(self._allowed_ws_hosts)
            up_ports = tuple(self._upstream_ports)
            auth_b64 = self._auth_b64
        if not bridge_hosts or not auth_b64:
            raise RuntimeError("tls-auth-failed:bridge-not-configured")
        dest_low = str(dest_host or "").strip().lower()
        distinct_candidates = [
            h for h in bridge_hosts
            if h.lower() in allowed_set and h.lower() != dest_low
        ]
        if not distinct_candidates:
            with self._lock:
                self.tunnel_err_count += 1
                self.last_error = "no-distinct-host"
            raise RuntimeError("no-distinct-host:bridge-host-matches-target")
        per_host_timeout = min(max(float(timeout), 0.5), 4.5)
        with self._lock:
            explicit_tunnels = self.server_tunnel_ports
        tunnel_candidates = _resolve_configured_server_tunnel_ports(
            explicit_ports=explicit_tunnels,
            exclude_ports=(self.socks_port, self.bind_port, self.listen_port),
            sid=self.sid,
            preferred_port=self.socks_port,
        )
        if not tunnel_candidates:
            unavail = "SERVER_TUNNEL_UNAVAILABLE:no-server-tunnel-candidates"
            with self._lock:
                self.tunnel_err_count += 1
                self.last_error = unavail
            raise RuntimeError(f"tls-auth-failed:{unavail}")
        last_exc = None
        attempts = []
        carrier_failures = []
        any_tunnel_connected = False
        socks_dialer = getattr(self, "_socks5_connect", None) or _WindscribeChainProxy._socks5_connect
        for ws_host in distinct_candidates[:4]:
            for up_port in up_ports:
                raw_sock = tls_sock = None
                used_tunnel_port = None
                try:
                    # Gate 3 & Owner 60445/60449 & A65 60463: Hop-1 MUST traverse a verified loopback server-tunnel SOCKS5 carrier (11080..11086); zero VM-direct branch.
                    last_tun_exc = None
                    for tun_port in tunnel_candidates:
                        try:
                            raw_sock = socks_dialer(
                                "127.0.0.1", int(tun_port), ws_host, int(up_port), timeout=per_host_timeout,
                            )
                            raw_sock.setsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 1)
                            used_tunnel_port = int(tun_port)
                            any_tunnel_connected = True
                            break
                        except Exception as te:
                            last_tun_exc = te
                            carrier_failures.append(f"{tun_port}:{type(te).__name__}")
                            if raw_sock is not None:
                                try:
                                    raw_sock.close()
                                except Exception:
                                    pass
                                raw_sock = None
                    if raw_sock is None:
                        raise RuntimeError(f"SERVER_TUNNEL_UNAVAILABLE:{type(last_tun_exc).__name__ if last_tun_exc else 'none'}")
                    ctx = self.ssl_context
                    if ctx is None:
                        ctx = _ssl.create_default_context()
                        try:
                            ctx.set_alpn_protocols(["http/1.1"])
                        except Exception:
                            pass
                    tls_sock, raw_sock = ctx.wrap_socket(raw_sock, server_hostname=ws_host), None
                    req = (
                        f"CONNECT {dest_host}:{int(dest_port)} HTTP/1.1\r\n"
                        f"Host: {dest_host}:{int(dest_port)}\r\n"
                        f"Proxy-Authorization: Basic {auth_b64}\r\n"
                        f"Proxy-Connection: keep-alive\r\n\r\n"
                    ).encode("latin-1")
                    tls_sock.sendall(req)
                    hdr_b, extra_b = _WindscribeChainProxy._read_http_headers(tls_sock)
                    parts = hdr_b.split(b"\r\n", 1)[0].decode("latin-1", errors="replace").split()
                    code = int(parts[1]) if len(parts) >= 2 and parts[1].isdigit() else 0
                    if code != 200:
                        raise RuntimeError(f"tls-auth-failed:HTTP_{code}")
                    tls_sock.settimeout(None)
                    with self._lock:
                        self.tunnel_ok_count += 1
                        self.last_ok_host = ws_host
                        if used_tunnel_port is not None:
                            self.last_ok_tunnel_port = used_tunnel_port
                        self.last_error = None
                        self._upstream_port = up_port
                        self._upstream_ports = (up_port,) + tuple(p for p in self._upstream_ports if p != up_port)
                    return tls_sock, extra_b
                except Exception as e:
                    last_exc = e
                    attempts.append((int(up_port), type(e).__name__, bool(_ws_should_try_alternate_secure_port(e))))
                    for sck in (tls_sock, raw_sock):
                        if sck is not None:
                            try:
                                sck.close()
                            except Exception:
                                pass
                    if up_port == up_ports[0] and _ws_should_try_alternate_secure_port(e):
                        continue
                    break
            with self._lock:
                if ws_host in self._bridge_hosts and len(self._bridge_hosts) > 1:
                    self._bridge_hosts = [h for h in self._bridge_hosts if h != ws_host] + [ws_host]
        if not any_tunnel_connected:
            tun_list_s = ",".join(str(p) for p in tunnel_candidates)
            unavail = f"SERVER_TUNNEL_UNAVAILABLE:tunnels={tun_list_s}:failures={','.join(carrier_failures[:7])}"
            with self._lock:
                self.tunnel_err_count += 1
                self.last_error = unavail
            raise RuntimeError(f"tls-auth-failed:{unavail}")
        attempt_summary = ",".join(f"{p}:{cls}" for p, cls, _wrong in attempts)
        both_official_wrong = (
            {p for p, _cls, wrong in attempts if wrong} == set(_WS_SECURE_PROXY_PORTS)
            and all(wrong for _p, _cls, wrong in attempts)
        )
        diagnosis = "TLS_PATH_BLOCKED_BOTH_SECURE_PORTS" if both_official_wrong else "TLS_UPSTREAM_FAILED"
        clean_last = _sanitize_vpn_err(last_exc, auth_b64=auth_b64)
        structured = f"{diagnosis}:attempts={attempt_summary}:last={clean_last}"
        with self._lock:
            self.tunnel_err_count += 1
            self.last_error = structured
        raise RuntimeError(f"tls-auth-failed:{structured}")

    def _handle_socks_client(self, cli_sock):
        tls_sock = None
        try:
            cli_sock.settimeout(10.0)
            hdr = _WindscribeChainProxy._recv_exact(cli_sock, 2)
            ver, nmethods = hdr[0], hdr[1]
            if ver != 5:
                return
            _WindscribeChainProxy._recv_exact(cli_sock, nmethods)
            cli_sock.sendall(b"\x05\x00")
            req_hdr = _WindscribeChainProxy._recv_exact(cli_sock, 4)
            ver, cmd, _rsv, atyp = req_hdr[0], req_hdr[1], req_hdr[2], req_hdr[3]
            if ver != 5 or cmd != 1:
                cli_sock.sendall(b"\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00")
                return
            if atyp == 1:
                addr_b = _WindscribeChainProxy._recv_exact(cli_sock, 4)
                dest_host = _socket.inet_ntoa(addr_b)
            elif atyp == 3:
                alen = _WindscribeChainProxy._recv_exact(cli_sock, 1)[0]
                dest_host = _WindscribeChainProxy._recv_exact(cli_sock, alen).decode("ascii", errors="replace")
            elif atyp == 4:
                addr_b = _WindscribeChainProxy._recv_exact(cli_sock, 16)
                dest_host = _socket.inet_ntop(_socket.AF_INET6, addr_b)
            else:
                cli_sock.sendall(b"\x05\x08\x00\x01\x00\x00\x00\x00\x00\x00")
                return
            dest_port = _struct.unpack("!H", _WindscribeChainProxy._recv_exact(cli_sock, 2))[0]
            tls_sock, extra_b = self._open_hop1_ws_tls_tunnel(dest_host, dest_port, timeout=4.5)
            with self._lock:
                self._active_socks.add(tls_sock)
            cli_sock.settimeout(None)
            cli_sock.sendall(b"\x05\x00\x00\x01\x7f\x00\x00\x01\x00\x00")
            if extra_b:
                cli_sock.sendall(extra_b)
            t = _threading.Thread(
                target=_WindscribeChainProxy._pipe_stream, args=(cli_sock, tls_sock), daemon=True
            )
            t.start()
            _WindscribeChainProxy._pipe_stream(tls_sock, cli_sock)
            t.join(timeout=2.0)
        except Exception:
            try:
                cli_sock.sendall(b"\x05\x01\x00\x01\x00\x00\x00\x00\x00\x00")
            except Exception:
                pass
        finally:
            with self._lock:
                self._active_socks.discard(cli_sock)
                if tls_sock is not None:
                    self._active_socks.discard(tls_sock)
            for sck in (tls_sock, client_sock if "client_sock" in locals() else cli_sock):
                if sck is not None:
                    try:
                        sck.close()
                    except Exception:
                        pass


def _get_active_embedded_socks_bridge(sid):
    with _SEAT_CHAIN_LOCK:
        return _SEAT_EMBEDDED_SOCKS_BRIDGES.get(str(sid or "").upper())


def _stop_seat_embedded_socks_bridge(sid):
    key = str(sid or "").upper()
    with _SEAT_CHAIN_LOCK:
        bridge = _SEAT_EMBEDDED_SOCKS_BRIDGES.pop(key, None)
    if bridge is not None and getattr(bridge, "owned_by_watcher", False):
        try:
            bridge.stop()
            log(key, f"🛑 [VPN-CHAIN:BRIDGE] 已停止內建 WS-SOCKS5 Bridge (127.0.0.1:{bridge.socks_port})")
        except Exception:
            pass


def _probe_external_socks5_ready(socks_port, target_host, target_port, sid=None, timeout=3.0):
    """Gate 1: 既有 11080 只有完成真 SOCKS5 handshake + remote CONNECT 先可復用；純 TCP accept 唔算 ready。"""
    sp = int(socks_port)
    key = str(sid or "").upper()
    with _SEAT_CHAIN_LOCK:
        owned = _SEAT_EMBEDDED_SOCKS_BRIDGES.get(key)
        if owned is not None and owned.listen_port == sp and owned._running:
            return "embedded-owned", None
        for other_k, other_b in _SEAT_EMBEDDED_SOCKS_BRIDGES.items():
            if other_b is not None and other_b.listen_port == sp and other_b._running:
                return "embedded-owned-other", None
    raw = None
    try:
        raw = _socket.create_connection(("127.0.0.1", sp), timeout=min(float(timeout), 2.5))
    except ConnectionRefusedError:
        return "no-listener", None
    except OSError as e:
        if getattr(e, "errno", None) in (111, 61):
            return "no-listener", None
        return "external-handshake-failed", f"socks-tcp-err:{type(e).__name__}"
    # An external process accepted TCP on 127.0.0.1:sp; now verify full SOCKS5 greeting + remote CONNECT
    try:
        raw.setsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 1)
        raw.settimeout(min(float(timeout), 3.5))
        raw.sendall(b"\x05\x01\x00")
        ver, method = _WindscribeChainProxy._recv_exact(raw, 2)
        if ver != 5 or method != 0:
            return "external-handshake-failed", f"socks-greeting-rejected:{ver}/{method}"
        hb = str(target_host).encode("idna")
        raw.sendall(b"\x05\x01\x00\x03" + bytes([len(hb)]) + hb + _struct.pack("!H", int(target_port)))
        ver, rep, _rsv, atyp = _WindscribeChainProxy._recv_exact(raw, 4)
        if ver != 5 or rep != 0:
            return "external-handshake-failed", f"socks-connect-rejected:rep={rep}"
        _WindscribeChainProxy._recv_exact(
            raw, 6 if atyp == 1 else (_WindscribeChainProxy._recv_exact(raw, 1)[0] + 2 if atyp == 3 else 18)
        )
        _SEAT_EXTERNAL_SOCKS_PORTS.add(sp)
        return "external-ready", None
    except Exception as e:
        return "external-handshake-failed", f"socks-handshake-failed:{type(e).__name__}"
    finally:
        if raw is not None:
            try:
                raw.close()
            except Exception:
                pass


def _get_active_chain_proxy(sid):
    with _SEAT_CHAIN_LOCK:
        return _SEAT_CHAIN_PROXIES.get(str(sid or "").upper())

def _stop_seat_chain_proxy(sid):
    key = str(sid or "").upper()
    with _SEAT_CHAIN_LOCK:
        chain = _SEAT_CHAIN_PROXIES.pop(key, None)
    if chain is not None:
        try:
            chain.stop()
            log(key, f"🛑 [VPN-CHAIN] 已停止本地 Chain Proxy (127.0.0.1:{chain.listen_port})")
        except Exception:
            pass
    _stop_seat_embedded_socks_bridge(key)

def _stop_all_chain_proxies():
    with _SEAT_CHAIN_LOCK:
        keys = sorted(set(_SEAT_CHAIN_PROXIES.keys()) | set(_SEAT_EMBEDDED_SOCKS_BRIDGES.keys()))
    for k in keys:
        _stop_seat_chain_proxy(k)

_atexit.register(_stop_all_chain_proxies)

def _order_hosts_for_seat(sid, raw_hosts, rotate_upstream=False, preferred_host=None):
    """應 59419 問題二：換 URL 時輪換 Windscribe upstream host（排除上一輪用過嘅 host，唔好成日用同一粒）。"""
    key = str(sid or "").upper()
    hosts = [str(h).strip() for h in (raw_hosts or []) if str(h).strip()]
    if not hosts:
        return []
    with _SEAT_CHAIN_LOCK:
        existing_chain = _SEAT_CHAIN_PROXIES.get(key)
        prev_host = (existing_chain.last_ok_host if existing_chain else None) or _SEAT_LAST_UPSTREAM_HOST.get(key)
        cur_idx = int(_SEAT_UPSTREAM_ROTATION_IDX.get(key, 0))
        if rotate_upstream:
            cur_idx = (cur_idx + 1) % len(hosts)
            _SEAT_UPSTREAM_ROTATION_IDX[key] = cur_idx
        elif key not in _SEAT_UPSTREAM_ROTATION_IDX:
            _SEAT_UPSTREAM_ROTATION_IDX[key] = 0
    ordered = hosts[cur_idx:] + hosts[:cur_idx]
    if rotate_upstream and prev_host and len(ordered) > 1 and ordered[0] == prev_host:
        ordered = [h for h in ordered if h != prev_host] + [prev_host]
    pref = str(preferred_host or "").strip()
    if pref:
        ordered = [pref] + [h for h in ordered if h != pref]
    return ordered

_LAST_GOOD_WS_HARVEST = None
_SOCKS_TUNNEL_IP_CACHE = {}

def _parse_ip_from_probe_body(raw_body):
    body = str(raw_body or "").strip()
    if not body:
        return None
    if body.startswith("{"):
        try:
            j = json.loads(body)
            ip = str(j.get("ip") or "").strip()
            if ip and re.match(r"^[0-9a-fA-F:.]{3,45}$", ip):
                return ip
        except Exception:
            pass
    for line in body.splitlines():
        s = line.strip()
        if s.startswith("ip="):
            cand = s.split("=", 1)[1].strip()
            if re.match(r"^[0-9a-fA-F:.]{3,45}$", cand):
                return cand
    first_line = body.splitlines()[0].strip()
    if re.match(r"^(?:\d{1,3}\.){3}\d{1,3}$", first_line):
        return first_line
    return None

def _prepare_seat_vpn_runtime(p, sid, profile_dir, socks_port, rotate_upstream=False, preferred_host=None):
    """應 59406/59409/59412/59414 & 59419（問題二）& 59641 #6 & 59726：執行 Stage A 收割並啟動／更新 Stage B Chain Proxy（push browser 唔 load Windscribe extension）；若當下 ws-* 收割失敗則自動輪換下一個 ws-* 或沿用已驗證收割快取。"""
    global _LAST_GOOD_WS_HARVEST
    has_unpacked_ext = bool(_discover_unpacked_extensions(profile_dir)) or bool(_harvest_ws_config_from_leveldb(profile_dir).get("ok"))
    if not VPN_USE_CHAIN_PROXY:
        return {
            "ok": False, "mode": "chain", "proxy_server": None,
            "load_extensions": False, "chain_port": None, "hosts": [],
            "reason": "chain-disabled",
        }
    if not has_unpacked_ext:
        repaired_ws = None
        try:
            repaired_ws = _switch_ws_extension_for_seat(sid, profile_dir, _resolve_ws_profiles_dir())
        except Exception:
            repaired_ws = None
        has_unpacked_ext = bool(_discover_unpacked_extensions(profile_dir)) or bool(_harvest_ws_config_from_leveldb(profile_dir).get("ok"))
        if not repaired_ws or not has_unpacked_ext:
            return {
                "ok": False, "mode": "chain", "proxy_server": None,
                "load_extensions": False, "chain_port": None, "hosts": [],
                "reason": "no-unpacked-ext",
            }
        log(sid, f"✅ [VPN-LATCH-FIX] no-unpacked-ext 已自動套用 ws_ext={repaired_ws} 修復，繼續 Stage A/B")
    harvest = _stage_a_harvest_windscribe(p, sid, profile_dir, socks_port)
    if not harvest.get("ok"):
        try:
            switched = _switch_ws_extension_for_seat(sid, profile_dir, _resolve_ws_profiles_dir())
            if switched:
                log(sid, f"🔁 [VPN-CHAIN:STAGE-A] 初次收割未過 ({harvest.get('reason')})，已自動切換 ws_ext={switched} 重試收割")
                harvest = _stage_a_harvest_windscribe(p, sid, profile_dir, socks_port)
        except Exception:
            pass
    if not harvest.get("ok") and isinstance(_LAST_GOOD_WS_HARVEST, dict) and _LAST_GOOD_WS_HARVEST.get("ok"):
        log(sid, f"♻️ [VPN-CHAIN:STAGE-A] 本輪收割未過 ({harvest.get('reason')})，沿用進程內已驗證 WS 憑證快取啟動 Chain Proxy")
        harvest = dict(_LAST_GOOD_WS_HARVEST)
    if not harvest.get("ok"):
        return {
            "ok": False, "mode": "chain", "proxy_server": None, "load_extensions": False,
            "chain_port": None, "hosts": [], "reason": harvest.get("reason") or "stage-a-failed",
        }
    _LAST_GOOD_WS_HARVEST = dict(harvest)
    key = str(sid or "").upper()
    prev_host = _SEAT_LAST_UPSTREAM_HOST.get(key)
    ordered_hosts = _order_hosts_for_seat(key, harvest["hosts"], rotate_upstream=rotate_upstream, preferred_host=preferred_host)
    if not ordered_hosts:
        return {
            "ok": False, "mode": "chain", "proxy_server": None, "load_extensions": False,
            "chain_port": None, "hosts": [], "reason": "no-distinct-host",
        }
    sp_int = int(socks_port) if socks_port else 11080
    probe_ws_host = ordered_hosts[0]
    up_port = int(harvest.get("port") or 443)
    ws_user = harvest.get("username") or ""
    ws_pass = harvest.get("password") or ""

    # Gate 1 & Gate 2: Probe whether 127.0.0.1:<socks_port> has a verified external SOCKS5 listener or needs the embedded WS-SOCKS5 bridge
    socks_state, socks_err = _probe_external_socks5_ready(sp_int, probe_ws_host, up_port, sid=key, timeout=3.0)
    if socks_state == "external-handshake-failed":
        clean_err = _sanitize_vpn_err(socks_err, username=ws_user, password=ws_pass)
        log(sid, f"❌ [VPN-CHAIN:STAGE-B] 外部 SOCKS5 (127.0.0.1:{sp_int}) 握手失敗 ({clean_err})，絕不覆蓋外部進程，fail-closed 中止")
        return {
            "ok": False, "mode": "chain", "proxy_server": None, "load_extensions": False,
            "chain_port": None, "hosts": [], "reason": f"socks-handshake-failed:{clean_err}",
        }

    # Owner 60445/60449: the seven carrier ports are host-provisioned forwards to
    # owner-server SOCKS.  Never let a VM-side extension manufacture a listener
    # on a missing carrier port and then misclassify it as a server tunnel.
    # Stage-A LevelDB harvesting above remains independent of carrier ownership.

    # If the selected host-provisioned carrier is absent, use only other
    # configured server forwards through the embedded bridge or fail closed.
    if socks_state == "no-listener" and not _is_embedded_socks_bridge_enabled():
        log(sid, f"❌ [VPN-CHAIN:BASE_SOCKS_UNAVAILABLE] 127.0.0.1:{sp_int} 無外部 SOCKS5 listener 且內建 Bridge 已停用，fail-closed 報錯")
        return {
            "ok": False, "mode": "chain", "proxy_server": None, "load_extensions": False,
            "chain_port": None, "hosts": [], "reason": f"BASE_SOCKS_UNAVAILABLE:127.0.0.1:{sp_int}",
        }

    using_embedded = socks_state in ("no-listener", "embedded-owned", "embedded-owned-other")
    chain_hosts = list(ordered_hosts)
    bridge_hosts = []
    verified_server_tunnels = None
    effective_socks_port = sp_int
    if not using_embedded:
        other_tunnels = _resolve_configured_server_tunnel_ports(exclude_ports=(sp_int,), sid=key, preferred_port=sp_int)
        ready_tunnels = [sp_int]
        for tp in other_tunnels:
            t_state, _ = _probe_external_socks5_ready(tp, probe_ws_host, up_port, sid=key, timeout=1.5)
            if t_state == "external-ready" and tp not in ready_tunnels:
                ready_tunnels.append(tp)
        verified_server_tunnels = tuple(ready_tunnels[:7])
    if using_embedded:
        bridge_hosts, chain_hosts, part_err = _partition_two_hop_ws_hosts(ordered_hosts)
        if part_err or not bridge_hosts or not chain_hosts:
            _stop_seat_embedded_socks_bridge(key)
            log(sid, f"❌ [VPN-CHAIN:STAGE-B] 內建雙跳 WS-SOCKS5 Bridge 需要至少 2 粒不重複 WS 節點 (現有 {len(ordered_hosts)} 粒)，fail-closed 中止")
            return {
                "ok": False, "mode": "chain", "proxy_server": None, "load_extensions": False,
                "chain_port": None, "hosts": [], "reason": "no-distinct-host",
            }
        cand_tunnels = _resolve_configured_server_tunnel_ports(exclude_ports=(sp_int,), sid=key, preferred_port=sp_int)
        verified_list = []
        for tp in cand_tunnels:
            t_state, _t_err = _probe_external_socks5_ready(tp, bridge_hosts[0], up_port, sid=key, timeout=2.5)
            if t_state == "external-ready":
                verified_list.append(tp)
        if not verified_list:
            _stop_seat_embedded_socks_bridge(key)
            log(sid, f"❌ [VPN-CHAIN:SERVER_TUNNEL_UNAVAILABLE] 127.0.0.1:{sp_int} 無外部 listener 且其餘 server tunnels ({cand_tunnels}) 均未就緒（應 60445/60449 嚴禁經主持 VM 直出），fail-closed 中止")
            return {
                "ok": False, "mode": "chain", "proxy_server": None, "load_extensions": False,
                "chain_port": None, "hosts": [], "reason": f"SERVER_TUNNEL_UNAVAILABLE:127.0.0.1:{sp_int}:tunnels={cand_tunnels}",
            }
        verified_server_tunnels = tuple(verified_list)
        target_bridge_bind = _resolve_non_colliding_bridge_bind_port(sp_int, server_tunnel_ports=cand_tunnels)
        try:
            with _SEAT_CHAIN_LOCK:
                bridge = _SEAT_EMBEDDED_SOCKS_BRIDGES.get(key)
                if bridge is not None and (bridge.socks_port != sp_int or bridge.bind_port != target_bridge_bind):
                    try:
                        bridge.stop()
                    except Exception:
                        pass
                    bridge = None
                if bridge is None:
                    bridge = _EmbeddedWsSocksBridge(
                        key, socks_port=sp_int, server_tunnel_ports=verified_server_tunnels, bind_port=target_bridge_bind
                    )
                    _SEAT_EMBEDDED_SOCKS_BRIDGES[key] = bridge
                bridge.update_upstream(
                    bridge_hosts=bridge_hosts,
                    all_harvested_hosts=ordered_hosts,
                    proxy_port=up_port,
                    username=ws_user,
                    password=ws_pass,
                    server_tunnel_ports=verified_server_tunnels,
                )
                effective_socks_port = bridge.start()
            log(sid, f"🌉 [VPN-CHAIN:BRIDGE] 本機 127.0.0.1:{sp_int} 無外部 listener，已於非衝突端口 127.0.0.1:{effective_socks_port} 啟動內建 WS-SOCKS5 Bridge (ServerTunnels={verified_server_tunnels}, Hop-1={bridge_hosts[0]}:{up_port})")
        except Exception as be:
            _stop_seat_embedded_socks_bridge(key)
            clean_be = _sanitize_vpn_err(be, username=ws_user, password=ws_pass)
            reason_code = clean_be if clean_be.startswith("socks-bind-conflict") else f"socks-bind-conflict:{clean_be}"
            log(sid, f"❌ [VPN-CHAIN:BRIDGE] 啟動內建 127.0.0.1:{target_bridge_bind} Bridge 失敗 ({reason_code})，fail-closed 中止")
            return {
                "ok": False, "mode": "chain", "proxy_server": None, "load_extensions": False,
                "chain_port": None, "hosts": [], "reason": reason_code,
            }

    try:
        with _SEAT_CHAIN_LOCK:
            chain = _SEAT_CHAIN_PROXIES.get(key)
            if chain is None:
                chain = _WindscribeChainProxy(key, preferred_port=_seat_chain_preferred_port(key, socks_port=sp_int))
                _SEAT_CHAIN_PROXIES[key] = chain
            elif prev_host is None and chain.last_ok_host:
                prev_host = chain.last_ok_host
            if using_embedded and bridge is not None and getattr(bridge, "ssl_context", None) is not None and chain.ssl_context is None:
                chain.ssl_context = bridge.ssl_context
            chain.update_upstream(
                socks_port=effective_socks_port,
                hosts=chain_hosts,
                proxy_port=up_port,
                username=ws_user,
                password=ws_pass,
                server_tunnel_ports=(None if using_embedded else verified_server_tunnels),
            )
            listen_port = chain.start()

        # Gate 5: Verify real base SOCKS5 handshake + at least one outer WS TLS CONNECT path before reporting Stage-B ready
        if using_embedded:
            s_probe = None
            try:
                s_probe = _WindscribeChainProxy._socks5_connect("127.0.0.1", effective_socks_port, chain_hosts[0], up_port, timeout=4.5)
            except Exception as se:
                b_last = getattr(bridge, "last_error", None) if bridge is not None else None
                clean_se = _sanitize_vpn_err(b_last or se, username=ws_user, password=ws_pass)
                _stop_seat_chain_proxy(key)
                if clean_se.startswith(("SERVER_TUNNEL_UNAVAILABLE", "no-distinct-host", "tls-auth-failed", "socks-handshake-failed")):
                    reason_out = clean_se
                else:
                    reason_tag = "SERVER_TUNNEL_UNAVAILABLE" if "SERVER_TUNNEL_UNAVAILABLE" in clean_se else (
                        "no-distinct-host" if "no-distinct-host" in clean_se else (
                            "tls-auth-failed" if "tls-auth-failed" in clean_se else "socks-handshake-failed"
                        )
                    )
                    reason_out = f"{reason_tag}:{clean_se}"
                return {
                    "ok": False, "mode": "chain", "proxy_server": None, "load_extensions": False,
                    "chain_port": None, "hosts": [], "reason": reason_out,
                }
            finally:
                if s_probe is not None:
                    try:
                        s_probe.close()
                    except Exception:
                        pass

        # Gate 6: Obtain baseline public IP via effective_socks_port, verify outer 18080 TLS CONNECT + post_ip != baseline_ip with bounded host rotation
        _SOCKS_TUNNEL_IP_CACHE.pop(effective_socks_port, None)
        base_ip, base_err = _probe_socks_tunnel_exit_ip(effective_socks_port, sid=key, timeout=4.0, allow_cached=False)
        if not base_ip or not _is_valid_public_exit_ip(base_ip):
            _stop_seat_chain_proxy(key)
            clean_berr = _sanitize_vpn_err(base_err, username=ws_user, password=ws_pass)
            return {
                "ok": False, "mode": "chain", "proxy_server": None, "load_extensions": False,
                "chain_port": None, "hosts": [], "reason": f"baseline-ip-invalid:{base_ip or clean_berr}",
            }

        max_rot = min(len(chain_hosts), 4)
        verified_post_ip = None
        last_fail_reason = "tls-auth-failed"
        for _attempt in range(max_rot):
            test_tls = None
            try:
                test_tls, _ = chain._open_windscribe_tls_tunnel("api.ipify.org", 443, timeout=4.5)
            except Exception as te:
                clean_te = _sanitize_vpn_err(te, username=ws_user, password=ws_pass)
                last_fail_reason = f"tls-auth-failed:{clean_te}"
                _demote_chain_upstream_host(chain)
                continue
            finally:
                if test_tls is not None:
                    try:
                        test_tls.close()
                    except Exception:
                        pass

            cand_post_ip = _probe_chain_proxy_exit_ip_host_side(listen_port, timeout=4.5)
            if not cand_post_ip or not _is_valid_public_exit_ip(cand_post_ip):
                last_fail_reason = f"post-ip-invalid:{cand_post_ip or 'empty'}"
                _demote_chain_upstream_host(chain)
                continue
            if _is_ip_blacklisted(cand_post_ip):
                last_fail_reason = f"ip-blacklisted-403:{cand_post_ip}"
                _demote_chain_upstream_host(chain)
                continue
            if cand_post_ip == base_ip:
                last_fail_reason = f"same-exit-ip:{cand_post_ip}"
                _demote_chain_upstream_host(chain)
                continue
            verified_post_ip = cand_post_ip
            _SEAT_LAST_EXIT_IP[key] = verified_post_ip
            break

        if not verified_post_ip:
            _stop_seat_chain_proxy(key)
            log(sid, f"❌ [VPN-CHAIN:STAGE-B] 外層 WS TLS 或出口差異驗證未過 ({last_fail_reason})，fail-closed 中止")
            return {
                "ok": False, "mode": "chain", "proxy_server": None, "load_extensions": False,
                "chain_port": None, "hosts": [], "reason": last_fail_reason,
            }

        chosen_h = chain.last_ok_host or (chain_hosts[0] if chain_hosts else None)
        if chosen_h:
            _SEAT_LAST_UPSTREAM_HOST[key] = chosen_h
        if rotate_upstream:
            log(sid, f"🔁 [VPN-CHAIN:ROTATE] 換 URL 同步切換 Windscribe upstream：{prev_host or 'NONE'} -> 首選 {chosen_h} (候選池共 {len(chain_hosts)} 粒)")
        log(
            sid,
            f"🔗 [VPN-CHAIN:STAGE-B] 本地 Chain Proxy 握手及出口驗證就緒：127.0.0.1:{listen_port} -> "
            f"socks5://127.0.0.1:{sp_int} ({'embedded' if using_embedded else 'external'}, base={_mask_ip_for_log(base_ip)}) -> "
            f"TLS {chosen_h}:{up_port} (post={_mask_ip_for_log(verified_post_ip)})",
        )
        return {
            "ok": True, "mode": "chain", "proxy_server": f"http://127.0.0.1:{listen_port}",
            "load_extensions": False, "chain_port": listen_port, "hosts": chain_hosts,
            "prev_host": prev_host, "chosen_host": chosen_h,
            "socks_mode": "embedded" if using_embedded else "external",
            "baseline_ip": base_ip, "post_ip": verified_post_ip, "reason": None,
        }
    except Exception as e:
        _stop_seat_chain_proxy(key)
        clean_e = _sanitize_vpn_err(e, username=ws_user, password=ws_pass)
        log(sid, f"❌ [VPN-CHAIN:STAGE-B] 啟動或更新 Chain Proxy 失敗：{clean_e}")
        return {
            "ok": False, "mode": "chain", "proxy_server": None, "load_extensions": False,
            "chain_port": None, "hosts": [], "reason": f"chain-start-exc:{type(e).__name__}:{clean_e}",
        }

def _read_vpn_toggle_state(ext_page):
    """讀 VPN 掣狀態：'on' / 'off' / 'unknown'（Fix 1.3：狀態元素層→掣字→aria→相鄰→父，整行錨定＋歧義守衛）。"""
    def _scan(text):
        got = set()
        for raw in str(text or "").replace("\r", "\n").split("\n"):
            s2 = raw.strip().strip("：:·•|-— ")
            if re.fullmatch(r"ON|OFF", s2):
                got.add(s2)
        return got

    def _decide(layers, cls):
        for src, texts in layers:
            seen = set()
            for t in texts:
                seen |= _scan(t)
            if len(seen) == 1:
                w = next(iter(seen))
                return {"state": "on" if w == "ON" else "off", "cls": cls, "text": w, "reason": None, "src": src}
            if len(seen) > 1:
                return {"state": "unknown", "cls": cls, "text": "ambiguous:" + "/".join(sorted(seen)), "reason": "ambiguous", "src": src}
        return {"state": "unknown", "cls": cls, "text": None, "reason": "no-on-off-text", "src": None}

    try:
        if hasattr(ext_page, "evaluate"):
            res = ext_page.evaluate(
                """({sel, sels}) => {
                    const lineSeen = (text) => {
                        const seen = new Set();
                        for (const raw of String(text || '').split(/[\\r\\n]+/)) {
                            const s = raw.trim().replace(/^[\\s:：·•|—-]+|[\\s:：·•|—-]+$/g, '');
                            if (/^(ON|OFF)$/.test(s)) seen.add(s);
                        }
                        return seen;
                    };
                    const btn = document.querySelector(sel);
                    const cls = btn ? String(btn.className || '') : null;
                    const layers = [];
                    const statusSeen = new Set();
                    for (const q of sels) {
                        try {
                            document.querySelectorAll(q).forEach((el) => {
                                for (const v of lineSeen(el.textContent)) statusSeen.add(v);
                            });
                        } catch (e) {}
                    }
                    layers.push(['status-element', statusSeen]);
                    if (btn) {
                        layers.push(['button-text', lineSeen(btn.textContent)]);
                        layers.push(['aria-label', lineSeen(btn.getAttribute('aria-label'))]);
                        layers.push(['next-sibling', btn.nextElementSibling ? lineSeen(btn.nextElementSibling.textContent) : new Set()]);
                        layers.push(['parent-text', btn.parentElement ? lineSeen(btn.parentElement.textContent) : new Set()]);
                    }
                    for (const [src, seen] of layers) {
                        if (seen.size === 1) {
                            const w = [...seen][0];
                            return { state: w === 'ON' ? 'on' : 'off', cls, text: w, reason: null, src };
                        }
                        if (seen.size > 1) {
                            return { state: 'unknown', cls, text: 'ambiguous:' + [...seen].sort().join('/'), reason: 'ambiguous', src };
                        }
                    }
                    return { state: 'unknown', cls, text: null, reason: btn ? 'no-on-off-text' : 'no-button', src: null };
                }""",
                {"sel": VPN_TOGGLE_SELECTOR, "sels": list(VPN_STATUS_SELECTORS)},
            )
            if isinstance(res, dict) and res.get("state") in ("on", "off", "unknown"):
                return res
    except Exception:
        pass
    try:
        loc = ext_page.locator(VPN_TOGGLE_SELECTOR)
        if loc.count() > 0:
            el = loc.first
            cls = str(el.get_attribute("class") or "") if hasattr(el, "get_attribute") else ""
            status_texts = []
            for q in VPN_STATUS_SELECTORS:
                try:
                    ql = ext_page.locator(q)
                    for i in range(min(ql.count(), 8)):
                        status_texts.append(ql.nth(i).inner_text())
                except Exception:
                    pass
            btn_texts = [el.inner_text() or ""] if hasattr(el, "inner_text") else []
            attr_texts = [el.get_attribute(a) or "" for a in ("aria-label", "title")] if hasattr(el, "get_attribute") else []
            return _decide([("status-element", status_texts), ("button-text", btn_texts), ("aria-label", attr_texts)], cls)
    except Exception:
        pass
    return {"state": "unknown", "cls": None, "text": None, "reason": "no-button", "src": None}

def _wait_vpn_toggle_state(ext_page, want_states, timeout_ms=15000):
    """對齊 bm.js waitForVpnToggleState：輪詢等待 VPN 掣進入指定狀態 ('on' / 'off')。"""
    wants = (want_states,) if isinstance(want_states, str) else tuple(want_states)
    deadline = time.time() + max(0.05, float(timeout_ms) / 1000.0)
    last = {"state": "unknown", "cls": None}
    while time.time() < deadline:
        last = _read_vpn_toggle_state(ext_page)
        if last.get("state") in wants:
            return {"ok": True, **last}
        time.sleep(0.05)
    last = _read_vpn_toggle_state(ext_page)
    return {"ok": last.get("state") in wants, **last}

def _resolve_seat_socks_port(sid):
    chain = _get_active_chain_proxy(sid)
    if chain is not None and getattr(chain, "socks_port", None):
        return int(chain.socks_port)
    try:
        seats = load_seats()
        vpn_ports = load_vpn_ports()
        cfg = seats.get(str(sid or "").upper()) or {}
        vpn_name = cfg.get("vpn")
        if vpn_name and vpn_name in vpn_ports:
            return int(vpn_ports[vpn_name])
    except Exception:
        pass
    return None

def _probe_socks_tunnel_exit_ip(socks_port, sid=None, timeout=4.0, allow_cached=True):
    """Probe SOCKS exit IP. Cache is checked first when allow_cached=True for fast baseline lookup."""
    if not socks_port:
        return None, "no-socks-port"
    sp = int(socks_port)
    cached = _SOCKS_TUNNEL_IP_CACHE.get(sp)
    if allow_cached and cached and (time.time() - cached[1]) < 600.0 and cached[0]:
        return cached[0], None
    errs = []
    chain = _get_active_chain_proxy(sid) if sid else None
    has_custom_ssl = chain is not None and getattr(chain, "ssl_context", None) is not None
    probe_urls = (
        "https://api.ipify.org?format=json",
        "https://icanhazip.com",
        "https://checkip.amazonaws.com",
        "https://www.cloudflare.com/cdn-cgi/trace",
        "https://ipinfo.io/json",
    )
    if not has_custom_ssl:
        for url in probe_urls:
            try:
                r = subprocess.run(
                    ["curl", "-sS", "--max-time", str(int(max(2, timeout))), "-x", f"socks5h://127.0.0.1:{sp}", url],
                    capture_output=True, text=True, timeout=timeout + 2,
                )
                if r.returncode == 0 and r.stdout.strip():
                    ip = _parse_ip_from_probe_body(r.stdout)
                    if ip:
                        _SOCKS_TUNNEL_IP_CACHE[sp] = (ip, time.time())
                        return ip, None
                elif r.stderr.strip():
                    errs.append(f"curl({url}):{r.stderr.strip()[:80]}")
            except Exception as e:
                errs.append(f"curl({url}):{type(e).__name__}")
    ctx = chain.ssl_context if has_custom_ssl else _ssl.create_default_context()
    for host, path in (
        ("api.ipify.org", "/?format=json"),
        ("icanhazip.com", "/"),
        ("checkip.amazonaws.com", "/"),
        ("www.cloudflare.com", "/cdn-cgi/trace"),
        ("ipinfo.io", "/json"),
    ):
        raw_s = tls_s = None
        try:
            raw_s = _WindscribeChainProxy._socks5_connect("127.0.0.1", sp, host, 443, timeout=timeout)
            tls_s = ctx.wrap_socket(raw_s, server_hostname=host)
            raw_s = None
            tls_s.settimeout(timeout)
            req = (
                f"GET {path} HTTP/1.1\r\n"
                f"Host: {host}\r\n"
                f"User-Agent: curl/8.0\r\n"
                f"Accept: application/json, text/plain, */*\r\n"
                f"Connection: close\r\n\r\n"
            ).encode("ascii")
            tls_s.sendall(req)
            buf = bytearray()
            while len(buf) < 65536:
                chunk = tls_s.recv(4096)
                if not chunk:
                    break
                buf.extend(chunk)
            raw_resp = bytes(buf)
            sep = b"\r\n\r\n" if b"\r\n\r\n" in raw_resp else b"\n\n"
            if sep in raw_resp:
                body = raw_resp.split(sep, 1)[1].decode("utf-8", errors="replace").strip()
                ip = _parse_ip_from_probe_body(body)
                if ip:
                    _SOCKS_TUNNEL_IP_CACHE[sp] = (ip, time.time())
                    return ip, None
        except Exception as e:
            errs.append(f"py({host}):{type(e).__name__}:{e}")
        finally:
            for sck in (tls_s, raw_s):
                if sck is not None:
                    try:
                        sck.close()
                    except Exception:
                        pass
    if allow_cached and cached and cached[0]:
        return cached[0], None
    return None, "; ".join(errs)[:200] or "socks-probe-empty"

_LOCAL_DIRECT_IP_CACHE = {"ip": None, "ts": 0.0}


def _clean_proxy_env(force_direct=False):
    env = dict(os.environ)
    for key in (
        "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
        "http_proxy", "https_proxy", "all_proxy", "no_proxy",
    ):
        env.pop(key, None)
    if force_direct:
        env["NO_PROXY"] = "*"
        env["no_proxy"] = "*"
    return env


def _clean_no_proxy_env():
    """Defense in depth for forced-direct curl probes."""
    return _clean_proxy_env(force_direct=True)


def _probe_local_direct_exit_ip(timeout=4.0, allow_cached=True):
    """應 60024/60025 #1a & A65 60030 & A87 60032：當 SOCKS 隧道基準探測不可用時，經外部公網回顯服務探測本機直連出口 IP 作 pre-VPN 基準（絕不讀取本機網卡私網位址）。"""
    now = time.time()
    if allow_cached and _LOCAL_DIRECT_IP_CACHE.get("ip") and (now - float(_LOCAL_DIRECT_IP_CACHE.get("ts") or 0.0)) < 600.0:
        return _LOCAL_DIRECT_IP_CACHE["ip"], None
    errs = []
    for url in (
        "https://api.ipify.org?format=json",
        "https://icanhazip.com",
        "https://checkip.amazonaws.com",
        "https://www.cloudflare.com/cdn-cgi/trace",
        "https://ipinfo.io/json",
    ):
        try:
            r = subprocess.run(
                ["curl", "-sS", "--noproxy", "*", "--max-time", str(int(max(2, timeout))), url],
                capture_output=True, text=True, timeout=timeout + 2, env=_clean_no_proxy_env(),
            )
            if r.returncode == 0 and r.stdout.strip():
                ip = _parse_ip_from_probe_body(r.stdout)
                if ip:
                    _LOCAL_DIRECT_IP_CACHE["ip"] = ip
                    _LOCAL_DIRECT_IP_CACHE["ts"] = time.time()
                    return ip, None
            elif r.stderr.strip():
                errs.append(f"curl({url}):{r.stderr.strip()[:60]}")
        except Exception as e:
            errs.append(f"curl({url}):{type(e).__name__}")
    return None, "; ".join(errs)[:200] or "local-probe-empty"

def _resolve_pre_vpn_baseline_ip(socks_port=None, sid=None, baseline_ip=None):
    """應 60024/60025 #1a & A87 60032 §二/§三：
    解析連 Extension／WS Chain 前之基準出口 IP（優先 explicit -> SOCKS tunnel -> 本機直連公網出口），
    並強制通過 _is_valid_public_exit_ip 拒絕私網/loopback/link-local/reserved 位址。
    回傳 (ip_or_none, reason_code, err_detail)。"""
    if baseline_ip is not None and str(baseline_ip).strip():
        cand = str(baseline_ip).strip()
        if not _is_valid_public_exit_ip(cand):
            return None, "baseline-private-ip", f"explicit({cand})"
        return cand, "explicit", None
    tunnel_err = None
    if socks_port is not None:
        t_ip, tunnel_err = _probe_socks_tunnel_exit_ip(socks_port, sid=sid)
        if t_ip:
            if not _is_valid_public_exit_ip(t_ip):
                return None, "baseline-private-ip", f"tunnel({t_ip})"
            return t_ip, "tunnel", None
        l_ip, local_err = _probe_local_direct_exit_ip()
        if l_ip:
            if not _is_valid_public_exit_ip(l_ip):
                return None, "baseline-private-ip", f"tunnel_err={tunnel_err or '-'}; local({l_ip})"
            return l_ip, "local-fallback", f"tunnel-baseline-failed:{tunnel_err or '-'}"
        return None, "no-baseline-available", f"tunnel-baseline-failed:{tunnel_err or '-'}; local-baseline-failed:{local_err or '-'}"
    l_ip, local_err = _probe_local_direct_exit_ip()
    if l_ip:
        if not _is_valid_public_exit_ip(l_ip):
            return None, "baseline-private-ip", f"local({l_ip})"
        return l_ip, "local", None
    return None, "local-baseline-failed", local_err or "local-probe-empty"

def _probe_chain_proxy_exit_ip_host_side(chain_port, timeout=6.0):
    """應 59726：當 browser 處於 about:blank 執行 fetch 被攔或超時時，由 host 端直接經 127.0.0.1:<chain_port> 探測出口 IP 作後備驗證（內建純 Python CONNECT + curl 雙路）。"""
    if not chain_port:
        return None
    cp = int(chain_port)
    ctx = _ssl.create_default_context()
    for host, path in (
        ("api.ipify.org", "/?format=json"),
        ("icanhazip.com", "/"),
        ("checkip.amazonaws.com", "/"),
        ("www.cloudflare.com", "/cdn-cgi/trace"),
    ):
        raw_s = tls_s = None
        try:
            raw_s = _socket.create_connection(("127.0.0.1", cp), timeout=timeout)
            raw_s.settimeout(timeout)
            raw_s.sendall(f"CONNECT {host}:443 HTTP/1.1\r\nHost: {host}:443\r\n\r\n".encode("ascii"))
            hdr_b, _ = _WindscribeChainProxy._read_http_headers(raw_s)
            if b" 200 " not in hdr_b.split(b"\r\n", 1)[0]:
                raise RuntimeError("chain CONNECT non-200")
            tls_s = ctx.wrap_socket(raw_s, server_hostname=host)
            raw_s = None
            tls_s.settimeout(timeout)
            tls_s.sendall(
                f"GET {path} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: curl/8.0\r\nAccept: */*\r\nConnection: close\r\n\r\n".encode("ascii")
            )
            buf = bytearray()
            while len(buf) < 65536:
                chunk = tls_s.recv(4096)
                if not chunk:
                    break
                buf.extend(chunk)
            raw_resp = bytes(buf)
            sep = b"\r\n\r\n" if b"\r\n\r\n" in raw_resp else b"\n\n"
            if sep in raw_resp:
                body = raw_resp.split(sep, 1)[1].decode("utf-8", errors="replace").strip()
                ip = _parse_ip_from_probe_body(body)
                if ip:
                    return ip
        except Exception:
            pass
        finally:
            for sck in (tls_s, raw_s):
                if sck is not None:
                    try:
                        sck.close()
                    except Exception:
                        pass
    for url in (
        "https://api.ipify.org?format=json",
        "https://icanhazip.com",
        "https://checkip.amazonaws.com",
        "https://www.cloudflare.com/cdn-cgi/trace",
        "https://ipinfo.io/json",
    ):
        try:
            r = subprocess.run(
                ["curl", "-sS", "--max-time", str(int(max(3, timeout))), "-x", f"http://127.0.0.1:{cp}", url],
                capture_output=True, text=True, timeout=timeout + 2, env=_clean_proxy_env(),
            )
            if r.returncode == 0 and r.stdout.strip():
                ip = _parse_ip_from_probe_body(r.stdout)
                if ip:
                    return ip
        except Exception:
            pass
    return None

def _probe_browser_page_exit_ip(page):
    """由 browser page 執行多端點公網出口 IP 探測，回傳 dict(ip, org, hostname, err)。"""
    if page is None or not hasattr(page, "evaluate"):
        return {"ip": None, "org": None, "hostname": None, "err": "page-unavailable"}
    js = """async () => {
        const ctl = (ms) => { const c = new AbortController(); setTimeout(() => c.abort(), ms); return c.signal; };
        const out = { ip: null, org: null, hostname: null, err: null };
        const bump = (s) => { out.err = out.err ? out.err + '; ' + s : s; };
        try {
            const r = await fetch('https://ipinfo.io/json', { cache: 'no-store', signal: ctl(8000) });
            if (!r.ok) throw new Error('HTTP ' + r.status);
            const j = await r.json();
            out.ip = j.ip || null; out.org = j.org || null; out.hostname = j.hostname || null;
        } catch (e) { bump('ipinfo.io/json: ' + (e && e.message || e)); }
        if (!out.ip) {
            try {
                const r = await fetch('https://api.ipify.org?format=json', { cache: 'no-store', signal: ctl(8000) });
                if (!r.ok) throw new Error('HTTP ' + r.status);
                out.ip = (await r.json()).ip || null;
            } catch (e) { bump('ipify: ' + (e && e.message || e)); }
        }
        if (!out.ip) {
            try {
                const r = await fetch('https://icanhazip.com', { cache: 'no-store', signal: ctl(6000) });
                if (!r.ok) throw new Error('HTTP ' + r.status);
                const t = (await r.text()).trim();
                if (/^(?:\\d{1,3}\\.){3}\\d{1,3}$/.test(t)) out.ip = t;
            } catch (e) { bump('icanhazip: ' + (e && e.message || e)); }
        }
        if (!out.ip) {
            try {
                const r = await fetch('https://www.cloudflare.com/cdn-cgi/trace', { cache: 'no-store', signal: ctl(6000) });
                if (!r.ok) throw new Error('HTTP ' + r.status);
                const m = (await r.text()).match(/^ip=([^\\r\\n]+)/m);
                if (m && m[1]) out.ip = m[1].trim();
            } catch (e) { bump('cf-trace: ' + (e && e.message || e)); }
        }
        return out;
    }"""
    try:
        res = page.evaluate(js)
    except Exception as e:
        return {"ip": None, "org": None, "hostname": None, "err": "evaluate-failed:" + type(e).__name__, "_eval_exc": True}
    if not isinstance(res, dict):
        return {"ip": None, "org": None, "hostname": None, "err": "bad-response:" + repr(res)[:120], "_bad_resp": True}
    return res

def _verify_windscribe_exit(page, sid, socks_port=None, baseline_ip=None):
    """應 59426 & 60010/60011 & 60024/60025 #1 & A87 60032：
    1. 先記低連 Extension／WS Chain 前嘅基準公網 IP（tunnel IP 或本機直連公網 IP；拒絕 RFC1918/loopback 私網位址）
    2. 連完後再攞出口 IP（支援 browser page.evaluate ＋ host-side chain proxy 後備探測）
    3. 純 IP 差分驗證（唔查特定 hostname / org 關鍵字）：
       - 出口 IP 存在、屬合法公網 IP、唔喺黑名單、且 ip != baseline_ip → 成功 (reason=diff-from-tunnel-ip)
       - ip == baseline_ip → 失敗 (reason=same-as-tunnel-ip)。"""
    if page is None or not hasattr(page, "evaluate"):
        return False, "page-unavailable"
    sp = socks_port if socks_port is not None else _resolve_seat_socks_port(sid)
    tunnel_ip, base_status, base_err = _resolve_pre_vpn_baseline_ip(socks_port=sp, sid=sid, baseline_ip=baseline_ip)
    if not tunnel_ip:
        return False, f"ip=- tunnel_ip=- socks_port={sp} reason={base_status} err={base_err or '-'}"
    page_url = str(getattr(page, "url", "") or "").strip().lower()
    if page_url.startswith("about:blank"):
        res = {"ip": None, "org": None, "hostname": None, "err": "about-blank-host-probe"}
    else:
        res = _probe_browser_page_exit_ip(page)
    ip = str(res.get("ip") or "").strip()
    if not ip:
        chain = _get_active_chain_proxy(sid) if sid else None
        if chain is not None and getattr(chain, "listen_port", None):
            host_ip = _probe_chain_proxy_exit_ip_host_side(chain.listen_port, timeout=6.0)
            if host_ip:
                ip = host_ip
    if not ip and res.get("_eval_exc"):
        return False, str(res.get("err") or "evaluate-failed")
    if not ip and res.get("_bad_resp"):
        return False, str(res.get("err") or "bad-response")
    detail = (
        f"ip={ip or '-'} tunnel_ip={tunnel_ip or '-'} baseline_src={base_status} "
        f"err={str(res.get('err') or '-')[:200]}"
    )
    if not ip:
        return False, detail + " reason=empty-exit-ip"
    if not _is_valid_public_exit_ip(ip):
        return False, detail + " reason=exit-private-ip"
    if sid:
        _SEAT_LAST_EXIT_IP[str(sid).upper()] = ip
    if _is_ip_blacklisted(ip):
        chain = _get_active_chain_proxy(sid) if sid else None
        _demote_chain_upstream_host(chain)
        if sid:
            log(sid, f"🚫 [IP-BLACKLIST:SKIP] 出口 ({_mask_ip_for_log(ip)}) 已在本地黑名單內，拒絕採用並自動切換下一個節點")
        return False, detail + " reason=ip-blacklisted-403"
    if os.environ.get("ARENA_PROBE_403_ON_EXIT_CHECK", "0") == "1":
        chain = _get_active_chain_proxy(sid) if sid else None
        proxy_u = f"http://127.0.0.1:{chain.listen_port}" if (chain and getattr(chain, "listen_port", None)) else None
        p_blk, p_reason = _probe_arena_ip_blocked(
            proxy_u, exit_ip=ip, sid=sid, port=sp,
            upstream_host=(chain.last_ok_host if chain else None),
        )
        if p_blk:
            _demote_chain_upstream_host(chain)
            return False, detail + f" reason=ip-blacklisted-403({p_reason})"
    if tunnel_ip:
        if _is_ip_blacklisted(tunnel_ip) and sid:
            log(sid, f"⚠️ [IP-BLACKLIST:TUNNEL] 本席基礎 SOCKS 隧道 (port={sp}) 出口 ({_mask_ip_for_log(tunnel_ip)}) 在黑名單內，強制要求經 Windscribe 非黑名單出口 ({_mask_ip_for_log(ip)})")
        if ip == tunnel_ip:
            return False, detail + " reason=same-as-tunnel-ip"
        return True, detail + " reason=diff-from-tunnel-ip"
    if ip in VPN_JP1_TUNNEL_IPS:
        return False, detail + " reason=same-as-tunnel-ip"
    return True, detail + " reason=diff-from-tunnel-ip"

def _resolve_current_seat_exit_ip(page, sid, socks_port=None):
    key = str(sid or "").upper()
    if key and _SEAT_LAST_EXIT_IP.get(key):
        return _SEAT_LAST_EXIT_IP[key]
    chain = _get_active_chain_proxy(sid) if sid else None
    if chain is not None and getattr(chain, "listen_port", None):
        hip = _probe_chain_proxy_exit_ip_host_side(chain.listen_port, timeout=5.0)
        if hip:
            if key:
                _SEAT_LAST_EXIT_IP[key] = hip
            return hip
    sp = socks_port if socks_port is not None else _resolve_seat_socks_port(sid)
    if sp is not None:
        tip, _ = _probe_socks_tunnel_exit_ip(sp, sid=sid, allow_cached=True)
        if tip:
            return tip
    return None

def _check_page_arena_ip_blocked(page, nav_response=None, sid=None, port=None):
    """應 59822 #1/#2 & 59823 §2(b)：於 page.goto + ca_checkbox_gate 後檢查頁面是否因出口 IP 被 arena.ai 403 封鎖；若是則自動寫入 ip-blacklist.json。"""
    if page is None:
        return False, None, None
    status_code = None
    headers = None
    if nav_response is not None:
        try:
            st_attr = getattr(nav_response, "status", None)
            status_code = st_attr() if callable(st_attr) else int(st_attr) if st_attr is not None else None
        except Exception:
            status_code = None
        try:
            h_attr = getattr(nav_response, "headers", None)
            headers = h_attr() if callable(h_attr) else (dict(h_attr) if isinstance(h_attr, dict) else None)
        except Exception:
            headers = None
    body_text = ""
    try:
        if hasattr(page, "evaluate"):
            eval_txt = page.evaluate("() => ((document && document.title) ? document.title : '') + '\n' + ((document && document.body && document.body.innerText) ? document.body.innerText.slice(0, 4096) : '')")
            if isinstance(eval_txt, str):
                body_text = eval_txt
    except Exception:
        pass
    low = body_text.lower()
    if "continue session" in low or "open sidebar" in low:
        return False, None, None
    if not _is_arena_403_ip_block_response(status_code, body_text, headers):
        return False, None, None
    exit_ip = _resolve_current_seat_exit_ip(page, sid, socks_port=port)
    key = str(sid or "").upper()
    upstream_host = _SEAT_LAST_UPSTREAM_HOST.get(key)
    cur_url = getattr(page, "url", "") if hasattr(page, "url") else ""
    if exit_ip:
        _record_blacklisted_ip(
            exit_ip, reason="browser_arena_403", sid=sid, port=port,
            upstream_host=upstream_host, url=cur_url,
        )
    return True, exit_ip, f"arena_403(status={status_code})"

def _select_non_blacklisted_socks_port(sid, preferred_port, vpn_ports=None):
    """應 59821/59822 & 59823 §3：若席位所配基礎 SOCKS port 出口 IP 已在黑名單內（如 11082 -> 158.101.145.210），自動告警並優先揀選非黑名單隧道 port。"""
    if not preferred_port:
        return preferred_port
    pref = int(preferred_port)
    bl = _load_ip_blacklist().get("blocked_ips", {})
    pref_blocked_ip = None
    for bip, bmeta in bl.items():
        if isinstance(bmeta, dict) and bmeta.get("port") and int(bmeta["port"]) == pref:
            pref_blocked_ip = bip
            break
    if not pref_blocked_ip:
        cached = _SOCKS_TUNNEL_IP_CACHE.get(pref)
        if cached and _is_ip_blacklisted(cached[0]):
            pref_blocked_ip = cached[0]
    if not pref_blocked_ip:
        return pref
    if os.environ.get("ARENA_AUTO_SWITCH_BLACKLISTED_SOCKS_PORT", "1") == "0":
        log(sid, f"⚠️ [IP-BLACKLIST:TUNNEL-PORT] 席位基礎隧道 port={pref} 對應黑名單出口 ({_mask_ip_for_log(pref_blocked_ip)})（已由 Windscribe Chain 覆蓋出口）")
        return pref
    ports_map = vpn_ports if isinstance(vpn_ports, dict) else {}
    blocked_ports = {
        int(m["port"]) for m in bl.values()
        if isinstance(m, dict) and m.get("port") is not None
    }
    direct_excl = {_DEFAULT_SERVER_DIRECT_SOCKS_PORT}
    try:
        direct_excl.update(_resolve_server_direct_socks_ports())
    except Exception:
        pass
    for vname, cand_p in sorted(ports_map.items(), key=lambda kv: int(kv[1])):
        if str(vname).strip().upper() in _SERVER_DIRECT_CONF_KEYS:
            continue
        cp = int(cand_p)
        if cp == pref or cp in blocked_ports or cp in direct_excl:
            continue
        c_ip = _SOCKS_TUNNEL_IP_CACHE.get(cp)
        if c_ip and _is_ip_blacklisted(c_ip[0]):
            continue
        log(sid, f"🔁 [IP-BLACKLIST:TUNNEL-SWITCH] 原隧道 port={pref} ({_mask_ip_for_log(pref_blocked_ip)}) 在黑名單內，自動切換基礎隧道至 {vname}:{cp}")
        return cp
    log(sid, f"⚠️ [IP-BLACKLIST:TUNNEL-PORT] 原隧道 port={pref} ({_mask_ip_for_log(pref_blocked_ip)}) 在黑名單內，將由 Windscribe Chain 強制替換出口")
    return pref

def _activate_vpn_extension_once(browser, page, sid, profile_dir, require_on=False):
    """Chain ready 時必須驗證 WS 出口；否則才試 extension popup。任何未驗證狀態都回 False，VPN_FAIL_OPEN 不再短路。"""
    key = str(sid or "").upper()
    chain = _get_active_chain_proxy(sid)
    if chain is not None and chain.is_ready():
        exit_ok, exit_detail = _verify_windscribe_exit(page, sid, socks_port=chain.socks_port)
        if not exit_ok:
            log(sid, f"❌ [VPN-CHAIN] 出口 IP 驗證未過 → activated 改 False ({exit_detail}) chain=127.0.0.1:{chain.listen_port}")
            return False
        active_host = chain.last_ok_host or (chain.upstream_hosts[0] if chain.upstream_hosts else None)
        if active_host:
            _SEAT_LAST_UPSTREAM_HOST[key] = active_host
        m_ip = re.search(r"ip=([^\s]+)", str(exit_detail or ""))
        if m_ip and m_ip.group(1) != "-":
            _SEAT_LAST_EXIT_IP[key] = m_ip.group(1)
        log(sid, f"✅ [VPN-CHAIN] 出口 IP 驗證通過 ({exit_detail}) chain=127.0.0.1:{chain.listen_port} upstream={active_host or chain.upstream_hosts}")
        return True
    ext_paths = _discover_unpacked_extensions(profile_dir)
    if not ext_paths:
        if require_on:
            log(sid, "❌ [VPN-EXT] 目標 profile 無可用 Extension VPN（fail-closed）")
        return False
    sp_ext = _resolve_seat_socks_port(sid)
    pre_ext_ip, _pre_src, _pre_err = _resolve_pre_vpn_baseline_ip(socks_port=sp_ext, sid=sid)
    activated = False
    for ep in ext_paths:
        mf_path = Path(ep) / "manifest.json"
        ext_id = Path(ep).parent.name
        popup_rel = None
        try:
            mf = json.loads(mf_path.read_text(encoding="utf-8"))
            action = mf.get("action") or mf.get("browser_action") or {}
            if isinstance(action, dict):
                popup_rel = action.get("default_popup")
        except Exception:
            popup_rel = None
        if not popup_rel:
            for cand_html in ("popup.html", "index.html", "panel.html"):
                if (Path(ep) / cand_html).is_file():
                    popup_rel = cand_html
                    break
        if popup_rel and hasattr(browser, "new_page"):
            ext_page = None
            try:
                ext_page = browser.new_page()
                popup_url = VPN_POPUP_URL if ext_id == VPN_EXTENSION_ID else f"chrome-extension://{ext_id}/{popup_rel.lstrip('/')}"
                ext_page.goto(popup_url, wait_until="domcontentloaded", timeout=15000)
                time.sleep(0.2)
                joy_loc = ext_page.locator(VPN_TOGGLE_SELECTOR)
                if joy_loc.count() > 0:
                    kn = _wait_vpn_toggle_state(ext_page, ("on", "off"), timeout_ms=5000)
                    st0 = kn.get("state")
                    if st0 == "on":
                        log(sid, f"[VPN-EXT] 初始狀態已係 ON (cls={kn.get('cls')!r} text={kn.get('text')!r}) → 先直接驗證 IP 變化，若未變再重連")
                        activated = True
                    elif st0 == "off":
                        if not pre_ext_ip and page is not None:
                            _pre_res = _probe_browser_page_exit_ip(page)
                            _cand_pre = str(_pre_res.get("ip") or "").strip()
                            if _is_valid_public_exit_ip(_cand_pre):
                                pre_ext_ip = _cand_pre
                        log(sid, f"[VPN-EXT] 初始狀態係 OFF (cls={kn.get('cls')!r} text={kn.get('text')!r}, pre_ip={_mask_ip_for_log(pre_ext_ip) if pre_ext_ip else '-'}) → 撳 1 次轉 ON")
                        joy_loc.first.click(timeout=5000)
                        on_r = _wait_vpn_toggle_state(ext_page, ("on",), timeout_ms=15000)
                        activated = bool(on_r.get("ok"))
                    else:
                        # Fix1.3（應59359 A87）：unknown 唔再盲撳，只記錄、fail-closed
                        log(sid, f"⚠️ [VPN-EXT] 初始狀態 unknown → 唔撳，fail-closed (cls={kn.get('cls')!r} text={kn.get('text')!r} reason={kn.get('reason')!r} src={kn.get('src')!r})")
                        activated = False
                else:
                    for sel in (
                        '[data-testid*="connect" i]',
                        'button[class*="connect" i]',
                        'button[id*="connect" i]',
                        '.connect-button',
                        '.power-button',
                        '[aria-label*="connect" i]',
                        '[aria-label*="turn on" i]',
                        'button',
                    ):
                        loc = ext_page.locator(sel)
                        if loc.count() > 0:
                            loc.first.click(timeout=3000)
                            activated = True
                            break
                time.sleep(0.2)
            except Exception as e:
                log(sid, f"[VPN-EXT] popup 啟用嘗試完畢 ({ext_id}): {e}")
            finally:
                if ext_page is not None:
                    try:
                        ext_page.close()
                    except Exception:
                        pass
    click_x = os.environ.get("VPN_EXT_CLICK_X")
    click_y = os.environ.get("VPN_EXT_CLICK_Y")
    if click_x and click_y and not activated:
        wid = _seat_window_id(sid, page=page)
        if wid:
            _xdotool_click(wid, int(click_x), int(click_y))
            activated = True
    # 應 60024/60025 #1：記低連 Extension 前嘅 IP -> 連完再攞 IP -> 有變＝成功，冇變＝失敗
    if activated:
        exit_ok, exit_detail = _verify_windscribe_exit(page, sid, socks_port=sp_ext, baseline_ip=pre_ext_ip)
        if not exit_ok:
            log(sid, f"❌ [VPN-EXT] 出口 IP 驗證未過 → activated 改 False ({exit_detail})")
            activated = False
        else:
            log(sid, f"[VPN-EXT] 出口 IP 驗證通過 ({exit_detail})")
    if not activated:
        log(sid, f"❌ [VPN-LATCH-FIX] VPN 啟用／出口驗證未確認 (activated=False, require_on={require_on})，拒絕上 latch；由外層輪換 ws-*／upstream")
        return False
    log(sid, f"✅ [VPN-EXT] 啟動時行一次啟用完成 (activated={activated})，進入正常流程")
    return True

def _clear_stale_singleton_locks(profile_dir):
    """清理目標 profile 目錄殘留嘅 SingletonLock/SingletonCookie/SingletonSocket，防重開卡死。"""
    pdir = Path(profile_dir)
    for lname in ("SingletonLock", "SingletonCookie", "SingletonSocket"):
        lp = pdir / lname
        try:
            if lp.is_symlink() or lp.exists():
                lp.unlink()
        except OSError:
            pass

def _reopen_chrome_for_profile_switch(p, browser, sid, cfg, port, target_entry, profiles_dir=None, cur_page=None):
    """應主持 58489 & A2/58491 #6 & A93/58517 & A2/58518：先驗後關——目標無效時保留現行已驗證 browser/page 並跳過今次輪換；驗過有效先至結束 Chrome -> 用對應 profile 重開 -> 起 VPN -> 去指定 URL。"""
    pdir = Path(profiles_dir if profiles_dir is not None else PROFILES_DIR)
    next_url = str((target_entry or {}).get("url") or "").strip()
    if isinstance(target_entry, dict) and "profile" in target_entry and target_entry.get("profile") is not None:
        raw_tp = str(target_entry.get("profile") or "").strip()
        next_profile = raw_tp if raw_tp else _seats_fallback_profile(sid)
    else:
        next_profile = _seats_fallback_profile(sid)
    # 先驗後關 (A93/58517 ① + A2/58518 【二】)：目標無效就唔好郁而家個 browser
    if not next_url or not _is_valid_profile_name(next_profile):
        log(sid, f"❌ [PROFILE-SWITCH-FAIL:VALIDATE] 目標 profile={next_profile!r} 或 url={next_url!r} 無效（先驗後關：保留現行 browser，跳過今次輪換）")
        _keep_page = cur_page if cur_page is not None else (browser.pages[0] if (browser is not None and getattr(browser, "pages", None)) else None)
        return {"ok": False, "phase": "validate", "browser": browser, "page": _keep_page, "profile_dir": None, "ws_ext": None}
    if browser is not None:
        try:
            browser.close()
        except Exception:
            pass
    _stop_seat_chain_proxy(sid)

    # Step 1（應 59641 #3/#4）：先清走 ramdisk 舊 profile，再由 persistent workshop 種 CP 下一個 profile 去 ramdisk（全程只放 1 個 profile）
    new_profile_dir = None
    try:
        new_profile_dir = _stage_seed_profile_to_ramdisk(sid, next_profile, seed_root=pdir)
        ws_chosen = _switch_ws_extension_for_seat(sid, new_profile_dir, _resolve_ws_profiles_dir(pdir))
    except Exception as e:
        log(sid, f"❌ [PROFILE-SWITCH-FAIL:STEP1] 準備目標 ramdisk profile={next_profile} 失敗 ({e})，fail-closed 中止")
        return {"ok": False, "phase": "prepare_profile", "browser": None, "page": None, "profile_dir": new_profile_dir, "ws_ext": None}

    cfg["profile"] = next_profile
    cfg["url"] = next_url
    log(sid, f"🔄 [PROFILE-SWITCH:STEP1] 已關閉舊 Chrome 並切換 profile={next_profile} ({new_profile_dir}), ws_ext={ws_chosen}")

    # Step 2: 執行 Fix 2 Stage A/B 準備 Chain Proxy（應 59419 問題二：換 URL 同步輪換 Windscribe upstream 攞新 IP）＋ 用新 profile 重開 Watch Chrome 並驗證出口 IP
    has_unpacked_ext = bool(_discover_unpacked_extensions(new_profile_dir))
    pref_host = (target_entry or {}).get("vpn_host") or (target_entry or {}).get("upstream") if isinstance(target_entry, dict) else None
    vpn_rt = _prepare_seat_vpn_runtime(p, sid, new_profile_dir, port, rotate_upstream=True, preferred_host=pref_host)
    if not vpn_rt.get("ok"):
        log(sid, f"❌ [PROFILE-SWITCH-FAIL:STEP2-VPN] profile={next_profile} Stage A/B Chain Proxy 準備失敗 ({vpn_rt.get('reason')})，fail-closed 中止")
        return {"ok": False, "phase": "open_vpn", "browser": None, "page": None, "profile_dir": new_profile_dir, "ws_ext": ws_chosen}
    new_browser = None
    try:
        new_browser = p.chromium.launch_persistent_context(
            str(new_profile_dir),
            headless=False,
            device_scale_factor=1,
            proxy={"server": vpn_rt["proxy_server"]},
            args=_build_chromium_launch_args(new_profile_dir, load_extensions=vpn_rt["load_extensions"]),
            ignore_default_args=["--enable-automation"],
            viewport={"width": 1400, "height": 900},
        )
        if new_browser is None:
            raise RuntimeError("launch_persistent_context returned None")
        new_page = new_browser.new_page() if not getattr(new_browser, "pages", None) else new_browser.pages[0]
        enforce_window_geometry(sid, stage="REOPEN", page=new_page)
    except Exception as e:
        log(sid, f"❌ [PROFILE-SWITCH-FAIL:STEP2-CHROME] 用 profile={next_profile} 重開 Chrome 失敗 ({e})，fail-closed 中止")
        if new_browser is not None:
            try:
                new_browser.close()
            except Exception:
                pass
        return {"ok": False, "phase": "reopen_chrome", "browser": None, "page": None, "profile_dir": new_profile_dir, "ws_ext": ws_chosen}

    has_unpacked_ext = bool(_discover_unpacked_extensions(new_profile_dir))
    vpn_ok = _activate_vpn_extension_once(new_browser, new_page, sid, new_profile_dir, require_on=has_unpacked_ext)
    if not vpn_ok:
        log(sid, f"❌ [PROFILE-SWITCH-FAIL:STEP2-VPN] profile={next_profile} WS Chain／Extension 出口驗證失敗；禁止 direct-SOCKS fallback，fail-closed 中止並由外層輪換")
        try:
            new_browser.close()
        except Exception:
            pass
        _stop_seat_chain_proxy(sid)
        return {"ok": False, "phase": "open_vpn", "browser": None, "page": None, "profile_dir": new_profile_dir, "ws_ext": ws_chosen}
    log(sid, f"✅ [PROFILE-SWITCH:STEP2] 已用 profile={next_profile} 重開 Chrome 並開啟 VPN (ws_ext={ws_chosen})")

    # Step 3: 導航去指定 URL 並通過 Seam 4 ensure_rotation_url 校驗
    try:
        _sw_nav_resp = new_page.goto(next_url, wait_until="domcontentloaded", timeout=60000)
        _dismiss_cookie_consent(new_page, sid)
        if not ensure_rotation_url(new_page, sid):
            raise RuntimeError(f"ensure_rotation_url failed for {getattr(new_page, 'url', '')!r}")
        enforce_window_geometry(sid, stage="TARGET-URL", page=new_page)
        ensure_zoom_100(new_page, sid, "TARGET-URL", new_profile_dir)
        ca_checkbox_gate(new_page, sid, "URL-CHANGE")
        _dismiss_cookie_consent(new_page, sid)
        _sw_blk, _sw_blk_ip, _sw_blk_reason = _check_page_arena_ip_blocked(new_page, _sw_nav_resp, sid=sid, port=port)
        if _sw_blk:
            raise RuntimeError(f"arena_ip_blocked_403 ip={_sw_blk_ip} reason={_sw_blk_reason}")
    except Exception as e:
        log(sid, f"❌ [PROFILE-SWITCH-FAIL:STEP3-URL] 導航至指定 URL ({next_url}) 失敗 ({e})，fail-closed 中止")
        try:
            new_browser.close()
        except Exception:
            pass
        return {"ok": False, "phase": "goto_url", "browser": None, "page": None, "profile_dir": new_profile_dir, "ws_ext": ws_chosen}

    log(sid, f"✅ [PROFILE-SWITCH:STEP3] 三步切換完成：profile={next_profile} ＋ VPN={ws_chosen} ＋ URL={next_url}")
    return {
        "ok": True,
        "phase": "done",
        "browser": new_browser,
        "page": new_page,
        "profile_dir": new_profile_dir,
        "ws_ext": ws_chosen,
        "profile": next_profile,
        "url": next_url,
    }

_SEAT_ACTIVE_PROFILE_DIR = {}
_LAST_PID_WIDS_CACHE = (0.0, None, None, [])

def _extract_cmdline_user_data_dir(cmdline_bytes):
    """由 /proc/<pid>/cmdline NUL 分隔參數精確提取 --user-data-dir 路徑並 resolve（應 A98/59477 防 A2/A20 前綴誤判）。"""
    if not cmdline_bytes:
        return None
    parts = [p.decode("utf-8", errors="ignore") for p in cmdline_bytes.split(b"\x00") if p]
    for idx, arg in enumerate(parts):
        if arg.startswith("--user-data-dir="):
            val = arg.split("=", 1)[1].strip()
            if val:
                try:
                    return Path(val).resolve()
                except Exception:
                    return Path(val)
        elif arg == "--user-data-dir" and idx + 1 < len(parts):
            val = parts[idx + 1].strip()
            if val:
                try:
                    return Path(val).resolve()
                except Exception:
                    return Path(val)
    return None

def _x_display():
    """解析實際 X display（主持 59484／59486：嚴禁寫死；A89／59491 設計經 A70 合併）。
    次序：環境變數 DISPLAY（其 socket 真存在先用）→ /tmp/.X11-unix 現存 socket（X98 優先）→ ':98'。
    last-resort 依主持 59484 字面用 display 98（A89 原版 last-resort 為 display 99）。"""
    socks = []
    try:
        for p in Path("/tmp/.X11-unix").iterdir():
            nm = p.name
            if nm.startswith("X") and nm[1:].isdigit():
                socks.append(int(nm[1:]))
    except Exception:
        socks = []
    socks.sort()
    envd = os.environ.get("DISPLAY") or ""
    if envd.startswith(":") and envd[1:].isdigit() and int(envd[1:]) in socks:
        return envd
    if 98 in socks:
        return ":98"
    if socks:
        return f":{socks[0]}"
    return envd or ":98"


def _x_env():
    """X 工具（xdotool／import）用嘅 subprocess env：DISPLAY 一律經 _x_display() 解析，唔准寫死。"""
    return {**os.environ, "DISPLAY": _x_display()}


def _get_descendant_chrome_pids(root_pid=None):
    """由本席 watcher PID 向下遍歷進程樹（並結合本席 profile_dir 之 SingletonLock / 精確 --user-data-dir 匹配防 reparent 失配），搵出所有本席 Chrome PID。"""
    root_pid = int(root_pid if root_pid is not None else os.getpid())
    children_map = {}
    comm_map = {}
    proc_root = Path("/proc")
    if proc_root.exists():
        for entry in proc_root.iterdir():
            if not entry.name.isdigit():
                continue
            pid_i = int(entry.name)
            try:
                stat_txt = (entry / "stat").read_text(encoding="utf-8", errors="ignore")
                rp = stat_txt.rfind(")")
                if rp != -1:
                    comm = stat_txt[stat_txt.find("(") + 1:rp].lower()
                    rest = stat_txt[rp + 2:].split()
                    ppid_i = int(rest[1])
                    children_map.setdefault(ppid_i, []).append(pid_i)
                    comm_map[pid_i] = comm
            except Exception:
                pass
    try:
        out = subprocess.run(["pgrep", "-P", str(root_pid)], capture_output=True, text=True, timeout=2)
        for line in out.stdout.splitlines():
            if line.strip().isdigit():
                cp = int(line.strip())
                if cp not in children_map.get(root_pid, []):
                    children_map.setdefault(root_pid, []).append(cp)
    except Exception:
        pass
    seed_roots = [root_pid]
    if root_pid == os.getpid() and _SEAT_ACTIVE_PROFILE_DIR:
        active_pdirs = [str(v) for v in _SEAT_ACTIVE_PROFILE_DIR.values() if v]
        resolved_pdirs = set()
        for pdir_s in active_pdirs:
            try:
                resolved_pdirs.add(Path(pdir_s).resolve())
            except Exception:
                resolved_pdirs.add(Path(pdir_s))
            try:
                slock = Path(pdir_s) / "SingletonLock"
                if slock.is_symlink():
                    target = os.readlink(str(slock))
                    m_sl = re.search(r"-(\d+)$", target)
                    if m_sl:
                        spid = int(m_sl.group(1))
                        if spid in comm_map and spid not in seed_roots:
                            seed_roots.append(spid)
            except Exception:
                pass
        if proc_root.exists() and resolved_pdirs:
            for pid_i, comm in list(comm_map.items()):
                if "chrom" not in comm or pid_i in seed_roots:
                    continue
                try:
                    udd = _extract_cmdline_user_data_dir((proc_root / str(pid_i) / "cmdline").read_bytes())
                    if udd is not None and udd in resolved_pdirs:
                        seed_roots.append(pid_i)
                except Exception:
                    pass
    visited = []
    queue = []
    seen = set(seed_roots)
    for sr in seed_roots:
        if sr != root_pid:
            visited.append(sr)
        queue.extend(children_map.get(sr, []))
    while queue:
        cur = queue.pop(0)
        if cur in seen:
            continue
        seen.add(cur)
        visited.append(cur)
        queue.extend(children_map.get(cur, []))
    chrome_pids = [p for p in visited if "chrom" in comm_map.get(p, "")]
    other_pids = [p for p in visited if "chrom" not in comm_map.get(p, "")]
    return chrome_pids + other_pids + [root_pid]

def _parse_window_geom(geom_text):
    """解析 xdotool getwindowgeometry 輸出，回傳 (x, y, w, h) 或 None。"""
    if not geom_text:
        return None
    x = y = w = h = None
    m_pos = re.search(r"Position:\s*(-?\d+),(-?\d+)", geom_text)
    if m_pos:
        x, y = int(m_pos.group(1)), int(m_pos.group(2))
    m_geo = re.search(r"Geometry:\s*(\d+)\s*x\s*(\d+)", geom_text)
    if m_geo:
        w, h = int(m_geo.group(1)), int(m_geo.group(2))
    if x is None:
        mx = re.search(r"^X=(-?\d+)", geom_text, re.M)
        my = re.search(r"^Y=(-?\d+)", geom_text, re.M)
        if mx and my:
            x, y = int(mx.group(1)), int(my.group(1))
    if w is None:
        mw = re.search(r"^WIDTH=(\d+)", geom_text, re.M)
        mh = re.search(r"^HEIGHT=(\d+)", geom_text, re.M)
        if mw and mh:
            w, h = int(mw.group(1)), int(mh.group(1))
    if x is not None and y is not None and w is not None and h is not None:
        return (x, y, w, h)
    return None

def _descendant_x11_wids(root_pid=None):
    """按本席 PID 樹調用 xdotool search --onlyvisible --pid <cpid> 認返自己個 Chrome window（嚴禁全屏見 Arena 就郁）。"""
    global _LAST_PID_WIDS_CACHE
    env = _x_env()
    cand_pids = _get_descendant_chrome_pids(root_pid)
    found_wids = []
    for cpid in cand_pids:
        try:
            res = subprocess.run(
                ["xdotool", "search", "--onlyvisible", "--pid", str(cpid)],
                capture_output=True, text=True, timeout=3, env=env
            )
            for w in res.stdout.strip().splitlines():
                w = w.strip()
                if w and w not in found_wids:
                    found_wids.append(w)
        except Exception:
            pass
    try:
        _LAST_PID_WIDS_CACHE = (time.monotonic(), id(subprocess.run), root_pid, list(found_wids))
    except Exception:
        pass
    return found_wids

def _seat_window_id(sid=None, page=None, root_pid=None):
    """統一本席視窗解析器（主持 47526 + A4 47528【2】+ 59453 + A98/59477）：只准由本席 PID 樹 (--pid) 或本席 page 唯一 ZOOMLOCK 臨時標題即時挑戰認窗（無未驗證 XID 快取，徹底廢除面積啟發式）。"""
    ts_c, run_id_c, rpid_c, wids_c = _LAST_PID_WIDS_CACHE
    try:
        now_m = time.monotonic()
    except Exception:
        now_m = 0.0
    if run_id_c == id(subprocess.run) and rpid_c == root_pid and now_m > 0 and (now_m - ts_c) < 0.35:
        wids = list(wids_c)
    else:
        wids = _descendant_x11_wids(root_pid=root_pid)
    if wids:
        return wids[-1]
    if page is not None and sid:
        env = _x_env()
        tag = f"ZOOMLOCK_{sid}_{int(time.time()*1000)%100000}"
        old_t = None
        title_set = False
        try:
            if hasattr(page, "bring_to_front"):
                try:
                    page.bring_to_front()
                except Exception:
                    pass
            old_t = page.evaluate(f"() => {{ const t = document.title; document.title = '{tag}'; return t; }}")
            title_set = True
            twids = []
            for wait_s in (0.08, 0.12, 0.15):
                time.sleep(wait_s)
                out = subprocess.run(["xdotool", "search", "--onlyvisible", "--name", tag], env=env, timeout=3, capture_output=True, text=True)
                twids = [w.strip() for w in out.stdout.splitlines() if w.strip()]
                if not twids:
                    out2 = subprocess.run(["xdotool", "search", "--name", tag], env=env, timeout=3, capture_output=True, text=True)
                    twids = [w.strip() for w in out2.stdout.splitlines() if w.strip()]
                if twids:
                    break
            if twids:
                return twids[-1]
        except Exception:
            pass
        finally:
            if title_set:
                try:
                    page.evaluate("(t) => { document.title = t; }", old_t if old_t is not None else "")
                except Exception:
                    pass
    return None


def _get_seat_dpr_baseline(sid):
    '''讀取 operator 簽認或 seats.conf 宣告之 DPR 基準（永不自動學習未驗證讀數）；回傳 float 或 None。'''
    try:
        sconf = SYSTEM_DIR / "seats.conf"
        if sconf.exists():
            for line in sconf.read_text(encoding="utf-8", errors="ignore").splitlines():
                s = line.strip()
                m = re.match(r"^#\s*zoom_baseline\s*:\s*(A\d+)\s*=\s*([0-9.]+)", s)
                if m and m.group(1) == sid:
                    val = float(m.group(2))
                    if val > 0:
                        _SEAT_DPR_BASELINE[sid] = val
                        if sid not in _BASELINE_LOGGED:
                            _BASELINE_LOGGED.add(sid)
                            ts_utc = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
                            log(sid, f"[ZOOM-BASELINE:{sid}={val}@{ts_utc}]")
                        return val
    except Exception:
        pass
    val = _SEAT_DPR_BASELINE.get(sid, 1.0)
    try:
        val = float(val)
        return val if val > 0 else None
    except Exception:
        return None

def _sanitize_profile_zoom_prefs(profile_dir, sid):
    if not profile_dir:
        return False
    prefs_path = Path(profile_dir) / "Default" / "Preferences"
    if not prefs_path.exists():
        return False
    try:
        data = json.loads(prefs_path.read_text(encoding="utf-8", errors="ignore"))
        if not isinstance(data, dict):
            return False
        changed = False
        part = data.get("partition")
        if isinstance(part, dict):
            for k in ("per_host_zoom_levels", "partition_default_zoom_levels"):
                if part.get(k):
                    log(sid, f"🔍 [ZOOM-PREFS] 捉到 Preferences partition.{k}={part[k]}，即刻清零")
                    part[k] = {}
                    changed = True
            if "default_zoom_level" in part and part.get("default_zoom_level") not in (None, 0, 0.0, {}):
                log(sid, f"🔍 [ZOOM-PREFS] 捉到 Preferences partition.default_zoom_level={part.get('default_zoom_level')}，即刻移除")
                part.pop("default_zoom_level", None)
                changed = True
        for k in ("per_host_zoom_levels", "partition_default_zoom_levels"):
            if data.get(k):
                log(sid, f"🔍 [ZOOM-PREFS] 捉到 Preferences {k}={data[k]}，即刻清零")
                data[k] = {}
                changed = True
        if "default_zoom_level" in data and data.get("default_zoom_level") not in (None, 0, 0.0, {}):
            log(sid, f"🔍 [ZOOM-PREFS] 捉到 Preferences default_zoom_level={data.get('default_zoom_level')}，即刻移除")
            data.pop("default_zoom_level", None)
            changed = True
        if changed:
            tmp_p = prefs_path.with_suffix(".tmp")
            tmp_p.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
            tmp_p.replace(prefs_path)
            _PREFS_CLEANED_AT_BOOT.add(sid)
        return changed
    except Exception as e:
        log(sid, f"⚠️ [ZOOM-PREFS] 清理 Preferences 異常 ({type(e).__name__}: {e})")
        return False

def _apply_css_zoom_reset(page, sid):
    '''冪等 CSS zoom reset（A4 47581【2】）：若 documentElement.style.zoom 已為空/'100%'/'1' 則零動作；否則重設為 '100%'。'''
    try:
        cur_z = page.evaluate("document.documentElement && document.documentElement.style ? document.documentElement.style.zoom : ''")
        if isinstance(cur_z, str) and cur_z.strip() not in ("", "100%", "1"):
            page.evaluate("if (document.documentElement && document.documentElement.style) { document.documentElement.style.zoom = '100%'; }")
            return True
        return False
    except Exception as e:
        log(sid, f"⚠️ [ZOOM-CSS] CSS zoom reset 異常 ({type(e).__name__}: {e})")
        return False

def _send_windowactivate_ctrl0(page, sid):
    try:
        if hasattr(page, "keyboard") and hasattr(page.keyboard, "press"):
            page.keyboard.press("Control+0")
    except Exception as e:
        log(sid, f"⚠️ [ZOOM-KEY] Playwright Control+0 異常 ({type(e).__name__}: {e})")
    if os.environ.get("DISPLAY") or Path("/tmp/.X11-unix/X" + _x_display().lstrip(":")).exists():
        try:
            env = _x_env()
            wid = _seat_window_id(sid, page=page)
            if wid:
                subprocess.run(["xdotool", "windowraise", str(wid)], env=env, timeout=3, capture_output=True)
                time.sleep(0.12)
                subprocess.run(["xdotool", "windowactivate", "--sync", str(wid)], env=env, timeout=3, capture_output=True)
                time.sleep(0.12)
                subprocess.run(["xdotool", "key", "ctrl+0"], env=env, timeout=3, capture_output=True)
        except Exception as e:
            log(sid, f"⚠️ [ZOOM-X11] xdotool ctrl+0 異常 ({type(e).__name__}: {e})")

def ensure_zoom_100(page, sid, stage="CYCLE", profile_dir=None):
    '''Seam 3 (Z1-Z6)：四源讀回驗證（含 operator 基準比值 dpr/baseline）+ 3步遞進校正 -> 失敗 HOLD 禁座標點擊。'''
    base_dpr = _get_seat_dpr_baseline(sid)

    def _probe():
        if base_dpr is None or base_dpr <= 0:
            return {"dpr": 0.0, "dprRatio": 0.0, "innerW": 0, "innerH": 0, "vvScale": 0.0, "unconfirmed": True}
        try:
            raw_dpr = page.evaluate("window.devicePixelRatio")
            raw_w = page.evaluate("window.innerWidth")
            raw_h = page.evaluate("window.innerHeight")
            vv_raw = page.evaluate("JSON.stringify({scale: (window.visualViewport && window.visualViewport.scale) || 1.0})")
            dpr = float(raw_dpr if raw_dpr is not None else 1.0)
            w = int(raw_w if raw_w is not None else TARGET_VIEWPORT_W)
            h = int(raw_h if raw_h is not None else TARGET_VIEWPORT_H)
            if isinstance(vv_raw, str):
                vv_scale = float(json.loads(vv_raw).get("scale", 1.0))
            elif isinstance(vv_raw, (int, float)):
                vv_scale = float(vv_raw)
            else:
                vv_scale = 1.0
            ratio = round(dpr / base_dpr, 4)
            return {"dpr": dpr, "dprRatio": ratio, "innerW": w, "innerH": h, "vvScale": vv_scale, "unconfirmed": False}
        except Exception as e:
            log(sid, f"⚠️ [ZOOM-PROBE] 縮放探針讀取失敗 ({type(e).__name__}: {e}) -> UNCONFIRMED")
            return {"dpr": 0.0, "dprRatio": 0.0, "innerW": 0, "innerH": 0, "vvScale": 0.0, "unconfirmed": True}

    def _ok(m):
        return (
            not m.get("unconfirmed", False)
            and abs(float(m.get("dprRatio", m.get("dpr", 0))) - 1.0) < 0.01
            and int(m.get("innerW", 0)) == TARGET_VIEWPORT_W
            and int(m.get("innerH", 0)) == TARGET_VIEWPORT_H
            and abs(float(m.get("vvScale", 1.0)) - 1.0) < 0.01
        )

    def _z5(m, att, meth, res):
        w = int(m.get("innerW", 0))
        pz = round(TARGET_VIEWPORT_W / w, 4) if w > 0 else 0.0
        return f"zoom dpr={m.get('dpr')} ratio={m.get('dprRatio', m.get('dpr'))} innerW={w} innerH={m.get('innerH')} vvScale={m.get('vvScale', 1.0)} pageZoom={pz} attempt={att} method={meth} result={res}"

    m0 = _probe()
    if _ok(m0):
        _PREFS_CLEANED_AT_BOOT.discard(sid)
        if stage != "CYCLE":
            log(sid, _z5(m0, 0, "noop", "OK"))
        return True, m0

    ts_drift_utc = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    log(sid, f"🚨 ERROR [ZOOM-LOCK] [ZOOM-DRIFT-ALERT:{sid}@{ts_drift_utc}] 偵測到 Zoom/Scale 偏離 100% (stage={stage} baseline={base_dpr} dpr={m0.get('dpr')} ratio={m0.get('dprRatio')} innerW={m0.get('innerW')} innerH={m0.get('innerH')} vvScale={m0.get('vvScale')} unconfirmed={m0.get('unconfirmed')})，拒絕靜默修復，立即報錯並啟動三步強制校正")
    if sid in _PREFS_CLEANED_AT_BOOT or stage == "TARGET-URL":
        log(sid, f"⚠️ [CAUSAL-NOTE:PREFS-NOT-PERSISTED] {sid} 啟動清 Preferences 後首輪仍測得非 100% ({m0})，進入三步強制校正")
        _PREFS_CLEANED_AT_BOOT.discard(sid)

    # Attempt 1: 鎖定本席 PID 視窗 (_seat_window_id) + windowactivate --sync + ctrl+0
    _send_windowactivate_ctrl0(page, sid)
    m1 = _probe()
    if _ok(m1):
        log(sid, _z5(m1, 1, "windowactivate+ctrl+0", "OK"))
        return True, m1
    log(sid, _z5(m1, 1, "windowactivate+ctrl+0", "FAIL"))

    # Attempt 2: 清 Preferences + windowactivate --sync + ctrl+0
    _sanitize_profile_zoom_prefs(profile_dir, sid)
    _send_windowactivate_ctrl0(page, sid)
    m2 = _probe()
    if _ok(m2):
        log(sid, _z5(m2, 2, "clean_prefs+windowactivate+ctrl+0", "OK"))
        return True, m2
    log(sid, _z5(m2, 2, "clean_prefs+windowactivate+ctrl+0", "FAIL"))

    # Attempt 3: 冪等 CSS zoom reset + windowactivate + ctrl+0, then reread（依主持 47596 真機三席實測，刪去 runtime 視口重設與 CDP 覆寫）
    _apply_css_zoom_reset(page, sid)
    _send_windowactivate_ctrl0(page, sid)
    m3 = _probe()
    if _ok(m3):
        log(sid, _z5(m3, 3, "css_zoom_reset+windowactivate+ctrl+0", "OK"))
        return True, m3

    log(sid, f"🚨 [CAUSAL-NOTE:Z2-HOLD:{stage}] {_z5(m3, 3, 'escalate_skip_click_and_reopen', 'FAIL')} -> HOLD（因 Zoom 未達 100%，本輪嚴禁座標點擊並觸發收 Browser 清 Preferences 重開）")
    return False, m3

def load_vpn_ports():
    """應 60533 #1 + A87 60536/60539：讀取席位/WireGuard 隧道端口（嚴格排除 SERVER_DIRECT 及 11090，絕不混入 7-port tunnel 池或席位 SOCKS 輪換池）。"""
    ports = {}
    v_path = (Path(SYSTEM_DIR) / "vpn-proxies.conf") if ("_DEFAULT_SYSTEM_DIR" in globals() and SYSTEM_DIR != _DEFAULT_SYSTEM_DIR and (Path(SYSTEM_DIR) / "vpn-proxies.conf").exists()) else VPN_CONF
    with open(v_path) as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            parts = [p.strip() for p in line.split("|")] if "|" in line else line.split()
            if len(parts) >= 2:
                k = parts[0].strip()
                if k.upper() in _SERVER_DIRECT_CONF_KEYS:
                    continue
                p_val = int(parts[1])
                if p_val == _DEFAULT_SERVER_DIRECT_SOCKS_PORT:
                    continue
                ports[k] = p_val
    return ports

def log(sid, msg):
    ts = time.strftime("%Y-%m-%d %H:%M:%S")
    line = f"[{ts}] [{sid}] {msg}"
    print(line, flush=True)
    try:
        LOGS_DIR.mkdir(parents=True, exist_ok=True)
        logfile = LOGS_DIR / f"watcher-{sid}.log"
        with open(logfile, "a") as f:
            f.write(line + "\n")
        # trim to 5000 lines（errors=ignore 防亂碼 crash，2026-10-05 修）
        with open(logfile, errors="ignore") as f:
            lines = f.readlines()
        if len(lines) > 5000:
            with open(logfile, "w") as f:
                f.writelines(lines[-5000:])
    except Exception:
        pass


# 席位→Y 座標映射（Browser 排位鐵律，2026-10-05 19:44 HKT owner 下令必須）
# 三個一組：第一席 y=0，第二席 y=900，第三席 y=1800
SLOT_Y_POS = {
    'A2': 0, 'A3': 0, 'A4': 0,
    'A5': 0, 'A6': 0, 'A7': 0,
    'A8': 0, 'A9': 0, 'A10': 0,
}

def enforce_window_geometry(sid, stage="CYCLE", root_pid=None, page=None):
    '''強制本席 browser window 位置與尺寸（主持 47526 + A4 47528 W1-W8 + 59453 page fallback + 59484/59486/59487 修復 + A89/59499-59500 護欄）
    1) W2：優先由本席 PID 樹 (`_descendant_x11_wids`) 認窗；Playwright/Chrome reparent 令 PID 樹失配時，
       只准用本席 page 嘅唯一 ZOOMLOCK 臨時標題認窗（沿用 `_seat_window_id` 安全 fallback，嚴禁全屏面積啟發式）。
    2) W1/W3：檢查及校正位置 (0, _slot_target_y(sid)) ＋ 尺寸 1408x900，重讀雙重驗；每個 wid 最多 3 次，
       第 2 次失敗後重解一次本席 window（stale wid 防護）先用最後結果判 FAIL。
    3) DISPLAY 一律經 _x_display() 解析（env（socket 真存在先用）→ X11 socket X98 優先 → :98）——舊行為寫死 display 99，已移除。
    4) 全部 xdotool 呼叫經 _xdo() 護欄：任何例外（含 --sync TimeoutExpired）只記錄 [GEOM-XDO] 並繼續下一格／下一次，
       唔會射穿中止（A89/59499-59500：現行裸 call 一卡就 return False，令重試／raw 幾何診斷全部冇機會行）；整體仍 fail-closed。
    '''
    target_x = 0
    target_y = _slot_target_y(sid)
    try:
        env = _x_env()
    except NameError:
        # 只出現喺「單函數 exec」核對器（ForbesAbide 類）嘅 ns；正常模組內 _x_env 一定存在。
        env = {**os.environ, "DISPLAY": os.environ.get("DISPLAY") or ":98"}

    def _xdo(argv):
        """單一 xdotool 呼叫：任何例外都唔准射穿；返 (rc, stdout, stderr)，rc=None＝例外。"""
        try:
            r = subprocess.run(argv, capture_output=True, text=True, timeout=5, env=env)
            return getattr(r, 'returncode', 0), (getattr(r, 'stdout', '') or ''), (getattr(r, 'stderr', '') or '')
        except Exception as e:
            words = ' '.join(str(a) for a in argv[1:] if not str(a).isdigit())
            log(sid, f"⚠️ [GEOM-XDO] {words} 例外 ({type(e).__name__}) DISPLAY={env.get('DISPLAY')}")
            return None, '', ''

    try:
        wids = _descendant_x11_wids(root_pid=root_pid)
        if not wids and page is not None:
            title_wid = _seat_window_id(sid=sid, page=page, root_pid=root_pid)
            if title_wid:
                wids = [str(title_wid)]
                if stage != "CYCLE":
                    log(sid, f"⚠️ [GEOM-W2-FALLBACK] PID 樹認窗失配；已用本席 page ZOOMLOCK 臨時標題安全認窗 wid={title_wid}")
        if not wids:
            log(sid, f"⚠️ [GEOM-W2] 按本席 PID 樹／page ZOOMLOCK 都搵唔到 Chrome window (pid={root_pid or os.getpid()}, DISPLAY={env.get('DISPLAY')})，跳過呢個 cycle")
            return False
        all_ok = True
        for wid in wids:
            rc0, raw, err0 = _xdo(['xdotool', 'getwindowgeometry', str(wid)])
            parsed = _parse_window_geom(raw)
            if parsed is None:
                rc1, raw1, err1 = _xdo(['xdotool', 'getwindowgeometry', '--shell', str(wid)])
                parsed = _parse_window_geom(raw1)
                log(sid, f"⚠️ [GEOM-PARSE] wid={wid} 主讀解析唔到 (rc={rc0}) DISPLAY={env.get('DISPLAY')} out={raw[:160]!r} err={err0[:200]!r}；--shell rc={rc1} out={raw1[:160]!r}")
            pos_ok = parsed is not None and parsed[0] == target_x and parsed[1] == target_y
            size_ok = parsed is not None and parsed[2] == EXPECTED_WIN_W and parsed[3] == EXPECTED_WIN_H
            if pos_ok and size_ok:
                if stage != "CYCLE":
                    log(sid, f"geom wid={wid} x={parsed[0]} y={parsed[1]} w={parsed[2]} h={parsed[3]} attempt=0 result=OK")
                continue
            fixed = False
            parsed2 = parsed
            for attempt in range(1, 4):
                _xdo(['xdotool', 'windowmove', str(wid), str(target_x), str(target_y)])
                rc_sync, _, _ = _xdo(['xdotool', 'windowsize', '--sync', str(wid), str(EXPECTED_WIN_W), str(EXPECTED_WIN_H)])
                if rc_sync is None or rc_sync != 0:
                    # --sync 卡住／失敗：即刻改試唔 sync（A89/59499 §2 護欄；避免射穿中止）
                    _xdo(['xdotool', 'windowsize', str(wid), str(EXPECTED_WIN_W), str(EXPECTED_WIN_H)])
                time.sleep(0.35)
                _, raw2, _ = _xdo(['xdotool', 'getwindowgeometry', str(wid)])
                parsed2 = _parse_window_geom(raw2)
                if parsed2 is not None and parsed2[0] == target_x and parsed2[1] == target_y and parsed2[2] == EXPECTED_WIN_W and parsed2[3] == EXPECTED_WIN_H:
                    log(sid, f"⚠️ [GEOM-W1] window {wid} 已校正至位置 ({target_x},{target_y}) 及尺寸 {EXPECTED_WIN_W}x{EXPECTED_WIN_H}（實測={parsed2}） attempt={attempt} result=OK")
                    fixed = True
                    break
                if attempt == 2 and page is not None:
                    alt_wid = _seat_window_id(sid=sid, page=page, root_pid=root_pid)
                    if alt_wid and str(alt_wid) != str(wid):
                        log(sid, f"⚠️ [GEOM-W2-RESOLVE] wid={wid} 連續校正唔到；重解本席 window → wid={alt_wid}，再試")
                        wid = str(alt_wid)
            if not fixed:
                _, raw_fail, _ = _xdo(['xdotool', 'getwindowgeometry', str(wid)])
                log(sid, f"🚨 [GEOM-W1] window {wid} 較唔返 ({target_x},{target_y}) {EXPECTED_WIN_W}x{EXPECTED_WIN_H}（實測={parsed2}） DISPLAY={env.get('DISPLAY')} attempt=3 result=FAIL，呢個 cycle 唔運行；raw={(raw_fail or '')[:200]!r}")
                all_ok = False
        return all_ok
    except Exception as e:
        log(sid, f"enforce_window_geometry 出錯 ({type(e).__name__}: {e})，唔准運行")
        return False


def is_generating(page):
    """檢查係咪生成緊（跟 ca.js：唔係搵 ■ 字，係搵 Stop 掣）
    selector: button[aria-label="Stop generating"], button[aria-label="Stop generation"]
    用 .last()，check is_visible()。有 = 生成緊。
    """
    try:
        stop_btn = page.locator('button[aria-label="Stop generating"], button[aria-label="Stop generation"]').last
        if stop_btn.count() > 0:
            try:
                if stop_btn.is_visible(timeout=300):
                    return True
            except Exception:
                pass
        return False
    except Exception:
        return False

def get_arena_logged_in_email(page):
    """跟 ca.js getArenaLoggedInEmail：用 JS evaluate 喺 sidebar DOM 搵電郵。
    搵：ul[data-sidebar="menu"] button → ul[data-sidebar="menu"] → button → 成個 body
    用 email regex 抽。搵到 = 已登入（ca.js：唯一登入證據＝真實電郵）。
    """
    try:
        email = page.evaluate("""() => {
            const emailRe = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/i;
            const roots = Array.from(document.querySelectorAll('ul[data-sidebar="menu"] button, ul[data-sidebar="menu"], button'));
            for (const el of roots) {
                const text = (el.innerText || el.textContent || '').trim();
                const m = text.match(emailRe);
                if (m) return m[0];
            }
            const bodyText = (document.body && document.body.innerText || '').trim();
            const m = bodyText.match(emailRe);
            return m ? m[0] : null;
        }""")
        return email
    except Exception:
        return None

def find_exact_text_login_button(page):
    """跟 ca.js findExactTextLoginButton（已修正：唔分大小寫，因頁面有時係 "Log in"）：
    先 get_by_role('button', name='Log In', exact=True)，唔得就逐個 button 睇 innerText（case-insensitive）
    """
    import re
    try:
        rb = page.get_by_role("button", name="Log In", exact=True).first
        if rb.count() > 0:
            try:
                if rb.is_visible(timeout=700):
                    return rb
            except Exception:
                pass
    except Exception:
        pass
    try:
        # 唔分大小寫：Log In / Log in 都得
        rb2 = page.get_by_role("button", name=re.compile(r"^log in$", re.IGNORECASE)).first
        if rb2.count() > 0:
            try:
                if rb2.is_visible(timeout=700):
                    return rb2
            except Exception:
                pass
    except Exception:
        pass
    try:
        buttons = page.locator('button[type="button"], button')
        count = buttons.count()
        for i in range(count):
            try:
                b = buttons.nth(i)
                if not b.is_visible(timeout=300):
                    continue
                t = b.inner_text(timeout=1000).replace("\n", " ").strip()
                t = re.sub(r"\s+", " ", t)
                if t.lower() == "log in":
                    return b
            except Exception:
                continue
    except Exception:
        pass
    return None

def wait_for_sidebar_button(page, sid, timeout_ms=120000):
    """120s 內一直搵左面 slide menu 個制，搵到 = loaded。
    用 expand_sidebar 嗰兩組 selector（group/toggle-btn + ca.js aria-label），淨係搵唔撳。
    """
    import time as _time
    deadline = _time.time() * 1000 + timeout_ms
    sels = [
        'button[class*="group/toggle-btn"]',
        'button[aria-label*="sidebar" i], button[aria-label*="menu" i], button[aria-label*="open" i]',
    ]
    while _time.time() * 1000 < deadline:
        for sel in sels:
            try:
                btn = page.locator(sel).first
                if btn.count() > 0 and btn.is_visible(timeout=1000):
                    log(sid, f"搵到 slide menu 制（{sel}）= loaded")
                    return True
            except Exception:
                pass
        try:
            page.wait_for_timeout(1000)
        except Exception:
            break
    log(sid, "120s 都搵唔到 slide menu 制")
    return False

def expand_sidebar(page, sid):
    """撳 sidebar toggle，等 sidebar 內容 load 出嚟。
    跟 ca.js + 用戶俾嘅正確 DOM：
    1. agent page：button[class*="group/toggle-btn"]（無 aria-label，用戶俾嘅）
    2. Landing/homepage：button[aria-label*="sidebar" i], button[aria-label*="menu" i], button[aria-label*="open" i]（ca.js）
    撳之前先 check 開咗未（見到 Log In 掣或電郵 = 已開），開咗就唔撳，避免開閂打架。
    撳一下，delay 3s。
    """
    # 先 check：sidebar 已開（見到 Log In 掣或電郵）就唔使撳
    try:
        if find_exact_text_login_button(page) is not None:
            return True
    except Exception:
        pass
    try:
        if get_arena_logged_in_email(page):
            return True
    except Exception:
        pass
    # 方法 1：agent page 版（用戶俾嘅正確 DOM）
    try:
        btn = page.locator('button[class*="group/toggle-btn"]').first
        if btn.count() > 0 and btn.is_visible(timeout=3000):
            btn.click(timeout=8000)
            page.wait_for_timeout(5000)
            log(sid, "已撳 sidebar toggle（group/toggle-btn）")
            return True
    except Exception as e:
        log(sid, f"撳 group/toggle-btn 出錯: {e}")
    # 方法 2：ca.js 版（三個 aria-label pattern）
    try:
        tg = page.locator('button[aria-label*="sidebar" i], button[aria-label*="menu" i], button[aria-label*="open" i]').first
        if tg.count() > 0 and tg.is_visible(timeout=3000):
            tg.click(timeout=8000)
            page.wait_for_timeout(5000)
            log(sid, "已撳 sidebar toggle（ca.js aria-label 版）")
            return True
    except Exception as e:
        log(sid, f"撳 ca.js sidebar toggle 出錯/冇掣: {e}")
    return False

def ca_page_logged_in(page, sid):
    """跟 ca.js caPageLoggedIn：5 次輪詢搵電郵，奇數次開 sidebar。搵到電郵 = 已登入。"""
    for i in range(5):
        try:
            email = get_arena_logged_in_email(page)
            if email:
                log(sid, f"搵到電郵：{email}（第 {i+1} 次）→ 已登入")
                return True
            if i % 2 == 1:
                expand_sidebar(page, sid)
                email2 = get_arena_logged_in_email(page)
                if email2:
                    log(sid, f"開 sidebar 後搵到電郵：{email2} → 已登入")
                    return True
        except Exception as e:
            log(sid, f"登入輪詢第 {i+1} 次出錯: {e}")
        page.wait_for_timeout(900)
    return False

def find_keep_working(page, sid):
    """用 CSS :has-text() selector，逐個試，is_visible 先回傳。
    順序跟 ca.js fallback，包埋「有进展/有進展/Some progress」變體。
    """
    candidates = [
        'button:has-text("Keep working")',
        'button:has-text("有进展")',
        'button:has-text("有進展")',
        'button:has-text("Some progress")',
        'span:has-text("Keep working")',
        'span:has-text("有进展")',
        'span:has-text("有進展")',
        'button:has-text("继续工作")',
        'button:has-text("繼續工作")',
        'span:has-text("继续工作")',
        'span:has-text("繼續工作")',
    ]
    for sel in candidates:
        try:
            loc = page.locator(sel).first
            if loc.count() > 0 and loc.is_visible(timeout=600):
                log(sid, f"找到 Keep working：{sel}")
                return loc
        except Exception:
            continue
    return None

def wait_for_login_indicators(page, sid, timeout_ms=120000):
    """等登入指標出現：電郵（已登入）或 Log In 掣（未登入），唔用死時間。
    用 ca_page_logged_in 同 find_exact_text_login_button 輪詢。
    返 True = 見到其中一個，False = 超時。
    """
    import time as _time
    deadline = _time.time() * 1000 + timeout_ms
    while _time.time() * 1000 < deadline:
        try:
            if ca_page_logged_in(page, sid):
                log(sid, "等到登入指標：已登入（見到電郵）")
                return True
        except Exception:
            pass
        try:
            if find_exact_text_login_button(page) is not None:
                log(sid, "等到登入指標：未登入（見到 Log In 掣）")
                return True
        except Exception:
            pass
        try:
            page.wait_for_timeout(1000)
        except Exception:
            break
    log(sid, "等登入指標超時（未見電郵亦未見 Log In 掣）")
    return False

def wait_for_dom_stable(page, sid, timeout_ms=30000, stable_rounds=3, poll_ms=1000):
    """等 DOM 穩定（唔用死時間）：每 poll_ms 計一次 body hash，
    連續 stable_rounds 次無變化即當穩定。超時照返。
    """
    last_h = None
    stable = 0
    waited = 0
    while waited < timeout_ms:
        try:
            body = page.content()
            h = hash(body) & 0xFFFFFFFF
        except Exception:
            h = None
        if h is not None and h == last_h:
            stable += 1
            if stable >= stable_rounds:
                log(sid, f"DOM 已穩定（hash={h:08x}，{waited}ms）")
                return True
        else:
            stable = 0
        last_h = h
        page.wait_for_timeout(poll_ms)
        waited += poll_ms
    log(sid, f"等 DOM 穩定超時（{timeout_ms}ms），繼續")
    return False

def wait_for_page_generated(page, sid, timeout_ms=15000):
    """等頁面生成（有實際內容）後先返。唔係齋等 reload 完。
    用 body innerText 長度 > 100 做指標，代表頁面內容 render 咗。
    """
    try:
        page.wait_for_function(
            "document.body && document.body.innerText && document.body.innerText.length > 100",
            timeout=timeout_ms
        )
        return True
    except Exception as e:
        log(sid, f"等頁面生成超時: {e}")
        return False

def find_input_box(page, sid):
    """
    搵輸入框，三個方法逐個試（跟 8080：textarea 用 .last，contenteditable 用 .first，textbox 用 .last）
    避開 password field（Chrome autofill 會填密碼，唔可以掂）。
    返 locator 或 None
    """
    def is_password_field(loc):
        """檢查係咪 password field"""
        try:
            tag = loc.evaluate("el => el.tagName.toLowerCase()").lower()
            typ = loc.evaluate("el => (el.getAttribute('type') || '').toLowerCase()")
            if tag == "input" and typ == "password":
                return True
            # 檢查附近有冇密碼相關（name/id 含 password/passwd/pwd）
            name_id = loc.evaluate("el => (el.getAttribute('name') || '') + ' ' + (el.getAttribute('id') || '') + ' ' + (el.getAttribute('autocomplete') || '')").lower()
            if any(k in name_id for k in ["password", "passwd", "current-password", "new-password"]):
                return True
        except Exception:
            pass
        return False

    cands = [
        ("textarea-last", lambda: page.locator("textarea").last),
        ("contenteditable-first", lambda: page.locator('[contenteditable="true"]').first),
        ("role-textbox-last", lambda: page.get_by_role("textbox").last),
    ]
    for name, fn in cands:
        try:
            loc = fn()
            if loc.count() > 0 and loc.is_visible(timeout=3000):
                if is_password_field(loc):
                    log(sid, f"⚠️ 跳過 password field（{name}），唔掂密碼")
                    continue
                log(sid, f"找到輸入框: {name}")
                return loc
        except Exception:
            pass
    return None

def get_page_heartbeat(page, sid):
    """
    心跳：記錄 page 狀態，防假成功。
    記錄：hash、Stop 掣、Keep working、輸入框、body 字數
    """
    try:
        body = page.inner_text("body")
        h = hash(body) & 0xFFFFFFFF
        has_gen = _is_generating_with_heartbeat(page, sid)
        has_kw = find_keep_working(page, sid) is not None
        inp = find_input_box(page, sid)
        inp_state = "無"
        if inp:
            try:
                inp_state = "有(可見)" if inp.is_visible(timeout=1000) else "有(隱藏)"
            except:
                inp_state = "有(未知)"
        hb = f"hash={h:08x} stop={'有' if has_gen else '無'} kw={'有' if has_kw else '無'} 輸入框={inp_state} body={len(body)}字"
        return hb
    except Exception as e:
        return f"心跳出錯: {e}"

def verify_email_via_sidebar(page, sid):
    """明確用 slide menu 開閂去確認有無 email：
    開 sidebar → 睇有無 email → 有＝已登入，冇＝要 login。
    返 email 字串或 None。
    """
    try:
        # 確保 sidebar 開咗
        expand_sidebar(page, sid)
        page.wait_for_timeout(2000)
        email = get_arena_logged_in_email(page)
        if email:
            log(sid, f"sidebar 確認有 email：{email}")
            return email
        else:
            log(sid, "sidebar 開咗但搵唔到 email → 要 login")
            return None
    except Exception as e:
        log(sid, f"verify_email_via_sidebar 出錯: {e}")
        return None

def check_login_state(page, sid, account_email, browser_ctx=None):
    """
    登入狀態檢查（跟 ca.js ＋ 59651 #8 Google 登入自動補密碼）：
    0. 若頁面已處於 Google 登入／密碼頁（input[type="password"] 可見或 accounts.google.com）→ 直接行 handle_arena_login_flow 自動補密碼
    1. ca_page_logged_in：5 次輪詢搵電郵 → 搵到＝已登入
    2. 搵唔到 → 睇有冇 Log In 掣 → 有＝未登入 → 自動行 login flow（含 .google-pw 自動補密碼）
    3. 兩個都冇＝異常
    返：'logged_in' / 'logged_out' / 'unknown' / 'login_failed' / 'session_cleared_retry'
    """
    try:
        cur_u = str(getattr(page, "url", "") or "")
        if "accounts.google.com" in cur_u or _is_google_password_prompt_visible(page):
            log(sid, "偵測到 Google 登入／密碼頁（Google session 已失效）→ 啟動自動補密碼登入流程")
            login_result = handle_arena_login_flow(page, sid, browser_ctx)
            if login_result == "SESSION_CLEARED":
                return 'session_cleared_retry'
            if login_result:
                page.wait_for_timeout(2000)
                if "arena.ai" in str(getattr(page, "url", "") or "") and ca_page_logged_in(page, sid):
                    return 'logged_in'
                return 'logged_in' if "arena.ai" in str(getattr(page, "url", "") or "") else 'login_failed'
            return 'login_failed'

        # 1. 用 ca.js 方法搵電郵
        if ca_page_logged_in(page, sid):
            return 'logged_in'

        # 2. 冇電郵 → 睇下係咪有 Log In 掣
        login_btn = find_exact_text_login_button(page)
        if login_btn is not None:
            log(sid, "見到 Log In 掣 → 嘗試自動登入")
            try:
                login_btn.click(timeout=8000)
                page.wait_for_timeout(3000)
            except Exception as e:
                log(sid, f"撳 Log In 出錯: {e}")
            # 行自動登入流程
            login_result = handle_arena_login_flow(page, sid, browser_ctx)
            if login_result == "SESSION_CLEARED":
                log(sid, "Arena session missing，已清 arena，要重跑 watcher")
                return 'session_cleared_retry'
            if login_result:
                log(sid, "自動登入成功，再驗證一次")
                page.wait_for_timeout(3000)
                if ca_page_logged_in(page, sid):
                    return 'logged_in'
                else:
                    log(sid, "自動登入後都搵唔到電郵")
                    return 'login_failed'
            else:
                log(sid, "自動登入失敗（密碼錯／彈驗證碼／超時）")
                return 'login_failed'

        # 3. 兩個都冇＝異常
        log(sid, "⚠️ 電郵同 Log In 都搵唔到＝頁面異常，截圖留證")
        try:
            page.screenshot(path=f"/tmp/{sid.lower()}-login-unknown-{int(time.time())}.png")
        except:
            pass
        return 'unknown'

    except Exception as e:
        log(sid, f"登入檢查出錯: {e}")
        return 'unknown'

def wait_for_login_signal(page, predicate, timeout_ms=2000, poll_ms=200):
    """跟 ca.js waitForLoginSignal：poll predicate，成功即返，唔使等足 timeout"""
    import time as _time
    deadline = _time.time() * 1000 + timeout_ms
    while _time.time() * 1000 < deadline:
        try:
            if predicate():
                return True
        except Exception:
            pass
        page.wait_for_timeout(poll_ms)
    return False

def is_login_flow_stuck_on_session_missing(page, sid):
    """檢測 login flow 卡住（Google missing Arena session）：
    在 Arena 按 Log In 後、Google login 期間，DOM 出現 "session missing" 文字。
    返 True = 卡住，要清 Arena 後重行 first-run login flow。
    """
    try:
        body_text = page.locator("body").inner_text(timeout=3000).lower()
        if "session missing" in body_text:
            log(sid, f"⚠️ 檢測到 login flow 卡住（DOM 有 'session missing'，URL: {page.url[:80]}）")
            return True
    except Exception:
        pass
    return False

def _has_active_error_banner_line(body_text, target_phrase):
    """應 F9：只匹配當前活動錯誤提示行，拒絕歷史對話引用。"""
    if not body_text or target_phrase not in body_text:
        return False
    lines = [ln.strip() for ln in str(body_text).splitlines() if ln.strip()]
    for ln in reversed(lines[-8:]):
        if target_phrase not in ln:
            continue
        low = ln.lower()
        if any(m in low for m in _QUOTE_OR_HISTORY_MARKERS):
            continue
        if ln.startswith((">", "`", '"', "'", "「", "『", "[")):
            continue
        return True
    return False

def _has_active_swr_try_again_line(body_text):
    """應 59418 第2項：匹配當前活動錯誤提示行同時包含 'Something went wrong' 及 'try again'（拒絕歷史對話引用）。"""
    if not body_text:
        return False
    low_all = str(body_text).lower()
    if "something went wrong" not in low_all or "try again" not in low_all:
        return False
    lines = [ln.strip() for ln in str(body_text).splitlines() if ln.strip()]
    for ln in reversed(lines[-8:]):
        low = ln.lower()
        if "something went wrong" not in low or "try again" not in low:
            continue
        if any(m in low for m in _QUOTE_OR_HISTORY_MARKERS):
            continue
        if ln.startswith((">", "`", '"', "'", "「", "『", "[")):
            continue
        return True
    return False

_DAILY_LIMIT_PENDING = {}
_RESPONSE_ENDED_STATE = {}
_SESSION_PUSH_STATE = {}
# Explicit per-cycle evidence for Owner 60007; kept separate from session totals.
_CYCLE_SEND_ATTEMPTED = {}
_CYCLE_PRE_SEND_SWR_COUNT = {}

def _reset_session_push_state(sid, url=None):
    """應 60007：每次進入新 session 或切換 URL 時重置 pushed_count=0，確保第一次入頁面見到殘留 DAILY_LIMIT 舊訊息唔會誤判。"""
    key = str(sid or "").upper()
    _SESSION_PUSH_STATE[key] = {
        "url": str(url or "").strip(),
        "pushed_count": 0,
        "pre_push_swr_count": 0,
        "last_push_ts": 0.0,
    }
    _DAILY_LIMIT_PENDING.pop(key, None)
    _CYCLE_SEND_ATTEMPTED[key] = False
    _CYCLE_PRE_SEND_SWR_COUNT[key] = 0

def _count_swr_banners_in_text(body_text):
    if not body_text:
        return 0
    low = str(body_text).lower()
    return low.count("something went wrong")

def _record_session_push_before_send(page, sid):
    """應 60007：於實際發送召回句前，記錄當前頁面已存在之舊錯誤橫幅數量作基準。"""
    key = str(sid or "").upper()
    cur_url = str(getattr(page, "url", "") or "").strip() if page is not None else ""
    st = _SESSION_PUSH_STATE.setdefault(key, {"url": cur_url, "pushed_count": 0, "pre_push_swr_count": 0, "last_push_ts": 0.0})
    if cur_url and st.get("url") and st["url"] != cur_url:
        st["url"] = cur_url
        st["pushed_count"] = 0
        st["pre_push_swr_count"] = 0
    elif cur_url and not st.get("url"):
        st["url"] = cur_url
    if page is not None and hasattr(page, "locator"):
        try:
            body_text = page.locator("body").inner_text(timeout=2000)
            st["pre_push_swr_count"] = _count_swr_banners_in_text(body_text)
            _CYCLE_PRE_SEND_SWR_COUNT[key] = st["pre_push_swr_count"]
        except Exception:
            pass
    return st

def _mark_session_pushed(sid, page=None):
    """應 60007：當今次 session 於該 URL 實際發送過至少一次召回句後，標記 pushed_count += 1。"""
    key = str(sid or "").upper()
    cur_url = str(getattr(page, "url", "") or "").strip() if page is not None else ""
    st = _SESSION_PUSH_STATE.setdefault(key, {"url": cur_url, "pushed_count": 0, "pre_push_swr_count": 0, "last_push_ts": 0.0})
    if cur_url:
        st["url"] = cur_url
    st["pushed_count"] = int(st.get("pushed_count", 0)) + 1
    st["last_push_ts"] = time.time()
    _CYCLE_SEND_ATTEMPTED[key] = True
    return st["pushed_count"]

def _has_pushed_in_current_session(sid, page=None):
    """應 60007：檢查今次 session 於當前 URL 是否已實際推過（send 過嘢）。"""
    key = str(sid or "").upper()
    st = _SESSION_PUSH_STATE.get(key)
    if not isinstance(st, dict):
        return False
    cur_url = str(getattr(page, "url", "") or "").strip() if page is not None else ""
    if cur_url and st.get("url") and st["url"] != cur_url:
        return False
    return int(st.get("pushed_count", 0)) >= 1

def _mark_daily_limit_hit(sid, reason):
    """記錄第1項／第3項觸發嘅 daily limit 原因，交由主循環執行三步換 URL（唔報 Muse）。"""
    key = str(sid or "").upper()
    _DAILY_LIMIT_PENDING[key] = str(reason or "daily_limit")
    log(sid, f"🚨 [DAILY-LIMIT-MARK] {sid} 觸發 daily limit ({reason}) → 將執行換 URL（唔報 Muse）")

def _peek_daily_limit_hit(sid):
    return _DAILY_LIMIT_PENDING.get(str(sid or "").upper())

def _consume_daily_limit_hit(sid):
    return _DAILY_LIMIT_PENDING.pop(str(sid or "").upper(), None)

def get_latest_response_ended_timestamp(page, sid=None):
    """應 59418 第3項：提取頁面最底嗰個 <div class="mt-3 flex flex-col gap-3"> 內 <span aria-label*="Response ended"> <time datetime="..."> 時間戳。"""
    if page is None:
        return None
    # Tier 1: DOM query via page.evaluate
    if hasattr(page, "evaluate"):
        try:
            ts = page.evaluate(
                """() => {
                    const sels = [
                        'div.mt-3.flex.flex-col.gap-3 span[aria-label*="Response ended" i] time[datetime]',
                        'span[aria-label*="Response ended" i] time[datetime]'
                    ];
                    for (const sel of sels) {
                        const nodes = document.querySelectorAll(sel);
                        if (nodes && nodes.length > 0) {
                            const last = nodes[nodes.length - 1];
                            const dt = last.getAttribute('datetime');
                            if (dt && dt.trim()) return dt.trim();
                        }
                    }
                    return null;
                }"""
            )
            if isinstance(ts, str) and ts.strip():
                return ts.strip()
        except Exception:
            pass
    # Tier 2: Playwright locator fallback
    if hasattr(page, "locator"):
        for sel in (
            'div.mt-3.flex.flex-col.gap-3 span[aria-label*="Response ended"] time[datetime]',
            'span[aria-label*="Response ended"] time[datetime]',
        ):
            try:
                loc = page.locator(sel)
                cnt = loc.count()
                if cnt > 0:
                    dt = loc.nth(cnt - 1).get_attribute("datetime")
                    if isinstance(dt, str) and dt.strip():
                        return dt.strip()
            except Exception:
                pass
    # Tier 3: HTML regex fallback
    if hasattr(page, "content"):
        try:
            html = page.content() or ""
            matches = re.findall(
                r'<span[^>]*aria-label="[^"]*Response ended[^"]*"[^>]*>[\s\S]*?<time[^>]*datetime="([^"]+)"',
                html,
                flags=re.IGNORECASE,
            )
            if matches:
                return matches[-1].strip()
        except Exception:
            pass
    return None

def _reset_response_ended_tracker(sid):
    key = str(sid or "").upper()
    _RESPONSE_ENDED_STATE[key] = {"baseline_ts": None, "unchanged_count": 0}

def _record_response_ended_before_push(page, sid):
    """應 59418 第3項：喺推之前記低最底 Response ended 時間戳；若推之前已出現新時間戳則更新基線並重置計數。"""
    key = str(sid or "").upper()
    st = _RESPONSE_ENDED_STATE.setdefault(key, {"baseline_ts": None, "unchanged_count": 0})
    cur_ts = get_latest_response_ended_timestamp(page, sid)
    if cur_ts:
        if st.get("baseline_ts") is None:
            st["baseline_ts"] = cur_ts
            st["unchanged_count"] = 0
            log(sid, f"[RESPONSE-ENDED] 記低第一次推之前最底 Response ended 時間戳：{cur_ts}")
        elif cur_ts != st.get("baseline_ts"):
            log(sid, f"[RESPONSE-ENDED] 推之前偵測到新 Response ended 時間戳（{st.get('baseline_ts')} -> {cur_ts}），重置計數 0/3")
            st["baseline_ts"] = cur_ts
            st["unchanged_count"] = 0
    return cur_ts

def _check_response_ended_after_push_success(page, sid):
    """應 59418 第3項：每輪推送顯示成功後檢查最底 Response ended 時間戳；連續 3 輪唔變即判定 daily limit。"""
    key = str(sid or "").upper()
    st = _RESPONSE_ENDED_STATE.setdefault(key, {"baseline_ts": None, "unchanged_count": 0})
    after_ts = get_latest_response_ended_timestamp(page, sid)
    base_ts = st.get("baseline_ts")
    if base_ts is None:
        if after_ts is not None:
            st["baseline_ts"] = after_ts
        return False
    if after_ts is not None and after_ts != base_ts:
        log(sid, f"[RESPONSE-ENDED] 推完後偵測到新 Response ended 時間戳（{base_ts} -> {after_ts}），重置計數 0/3")
        st["baseline_ts"] = after_ts
        st["unchanged_count"] = 0
        return False
    if after_ts == base_ts:
        st["unchanged_count"] = int(st.get("unchanged_count", 0)) + 1
        cnt = st["unchanged_count"]
        log(sid, f"⚠️ [RESPONSE-ENDED] 第 {cnt}/3 輪推送顯示成功，但最底 Response ended 時間戳未變（datetime={base_ts}）")
        if cnt >= 3:
            log(sid, f"🚨 [DAILY-LIMIT:ITEM3] 連續 {cnt} 輪推送都顯示成功，但最底 Response ended 時間戳一直唔變（datetime={base_ts}）→ 判定 daily limit，立即換 URL（唔報 Muse）")
            _reset_response_ended_tracker(sid)
            _mark_daily_limit_hit(sid, f"item3_response_ended_unchanged_3_rounds:{base_ts}")
            return True
    return False

def _is_purple_loading_active(page, sid=None, wid=None):
    """應 59418 第1項：檢測撳完藍色掣後嘅紫色 loading 是否仲轉緊。"""
    if wid is not None:
        try:
            cp = _read_window_pixel(wid, PURPLE_CHECK_X, PURPLE_CHECK_Y)
            if cp and _color_match(cp, PURPLE_CHECK_COLOR):
                return True
        except Exception:
            pass
    if page is not None and hasattr(page, "evaluate"):
        try:
            spinning = page.evaluate(
                """() => {
                    const sels = [
                        '[aria-busy="true"]',
                        '[data-loading="true"]',
                        'svg.animate-spin',
                        '[class*="animate-spin" i]',
                        '[class*="spinner" i]'
                    ];
                    for (const sel of sels) {
                        const el = document.querySelector(sel);
                        if (el) return true;
                    }
                    return false;
                }"""
            )
            if spinning:
                return True
        except Exception:
            pass
    return False

def _wait_for_purple_loading_finished(page, sid, wid=None, max_wait_ms=15000, poll_ms=500):
    """應 59418 第1項：等待紫色 loading 轉完（最多等 max_wait_ms）。"""
    steps = max(1, int(max_wait_ms // max(100, poll_ms)))
    saw_loading = False
    for _ in range(steps):
        if not _is_purple_loading_active(page, sid=sid, wid=wid):
            if saw_loading:
                log(sid, "[PURPLE-LOADING] 紫色 loading 已轉完")
            return True
        saw_loading = True
        try:
            if page is not None and hasattr(page, "wait_for_timeout"):
                page.wait_for_timeout(poll_ms)
            else:
                time.sleep(poll_ms / 1000.0)
        except Exception:
            time.sleep(poll_ms / 1000.0)
    return False

DAILY_LIMIT_BUTTON_ARIA_LABEL = "You have reached your usage limit for today"
DAILY_LIMIT_BUTTON_SEVERITY = "blocked"


def _inspect_profile_daily_limit_dom(page):
    """Owner 60429: Inspect DOM for <button aria-label="You have reached your usage limit for today" data-severity="blocked">."""
    target_aria = DAILY_LIMIT_BUTTON_ARIA_LABEL.strip().lower()
    if page is None:
        return {"matched": False, "severity": None, "source": "none"}
    # Path 1: synthetic/mocked html content or _dom_buttons attribute for hermetic testing
    raw_html = getattr(page, "_html", None)
    if raw_html is None and hasattr(page, "content") and callable(getattr(page, "content", None)):
        try:
            cand_html = page.content()
            if isinstance(cand_html, str) and "<" in cand_html:
                raw_html = cand_html
        except Exception:
            raw_html = None
    if isinstance(raw_html, str) and raw_html:
        from html.parser import HTMLParser
        class _BtnParser(HTMLParser):
            def __init__(self):
                super().__init__()
                self.hits = []
            def handle_starttag(self, tag, attrs):
                if str(tag or "").strip().lower() != "button":
                    return
                ad = {str(k or "").strip().lower(): (v if v is not None else "") for k, v in attrs}
                aria_v = str(ad.get("aria-label") or "").strip()
                if aria_v.lower() == target_aria:
                    sev_v = str(ad.get("data-severity") or "").strip().lower()
                    self.hits.append(sev_v)
        p = _BtnParser()
        try:
            p.feed(raw_html)
            if p.hits:
                sev = "blocked" if "blocked" in p.hits else p.hits[0]
                return {"matched": True, "severity": sev, "source": "html"}
        except Exception:
            pass
    # Path 2: Playwright locator('button[aria-label]')
    if hasattr(page, "locator") and callable(getattr(page, "locator", None)):
        try:
            loc = page.locator("button[aria-label]")
            cnt = loc.count() if hasattr(loc, "count") else 0
            if isinstance(cnt, int) and cnt > 0:
                for idx in range(min(cnt, 64)):
                    item = loc.nth(idx)
                    tag_ok = True
                    if hasattr(item, "evaluate"):
                        try:
                            tname = item.evaluate("el => (el && el.tagName ? el.tagName.toLowerCase() : 'button')")
                            if isinstance(tname, str) and tname != "button":
                                tag_ok = False
                        except Exception:
                            pass
                    if not tag_ok:
                        continue
                    aria_v = str(item.get_attribute("aria-label") or "").strip()
                    if aria_v.lower() == target_aria:
                        sev_v = str(item.get_attribute("data-severity") or "").strip().lower()
                        return {"matched": True, "severity": sev_v, "source": "locator"}
        except Exception:
            pass
    # Path 3: Playwright page.evaluate over button[aria-label]
    if hasattr(page, "evaluate") and callable(getattr(page, "evaluate", None)):
        try:
            res = page.evaluate(
                """(expectedAria) => {
                    const btns = Array.from(document.querySelectorAll('button[aria-label]'));
                    for (const b of btns) {
                        if (!b || !b.tagName || b.tagName.toLowerCase() !== 'button') continue;
                        const aria = String(b.getAttribute('aria-label') || '').trim().toLowerCase();
                        if (aria === expectedAria) {
                            const sev = String(b.getAttribute('data-severity') || '').trim().toLowerCase();
                            return {matched: true, severity: sev};
                        }
                    }
                    return {matched: false, severity: ''};
                }""",
                target_aria,
            )
            if isinstance(res, dict) and res.get("matched") is True:
                return {"matched": True, "severity": str(res.get("severity") or "").strip().lower(), "source": "evaluate"}
        except Exception:
            pass
    return {"matched": False, "severity": None, "source": "none"}


def has_profile_daily_limit_dom(page, sid=None):
    """應 Owner 60429：見到 button[aria-label="You have reached your usage limit for today"]（data-severity="blocked"）
    任何情況見到呢個 aria-label，即判定為 Profile Daily Limit，唔使再估。"""
    info = _inspect_profile_daily_limit_dom(page)
    if not info.get("matched"):
        return False
    sev = str(info.get("severity") or "").strip().lower()
    if sev == DAILY_LIMIT_BUTTON_SEVERITY:
        reason = "profile_daily_limit_dom_button_blocked"
        if sid:
            log(sid, '🚨 [DAILY-LIMIT:DOM-60429] 見到 button[aria-label="You have reached your usage limit for today"][data-severity="blocked"] → 即時判定為 Profile Daily Limit')
    else:
        reason = "profile_daily_limit_dom_button_aria"
        if sid:
            log(sid, f'⚠️ [DAILY-LIMIT:DOM-60429] 見到 button[aria-label="You have reached your usage limit for today"] (data-severity={sev or "missing"} != blocked) → 應 60429 任何情況見到呢個 aria-label 即判定為 Profile Daily Limit')
    if sid:
        _mark_daily_limit_hit(sid, reason)
    return True


def is_daily_limit_error(page, sid):
    """應主持 58489 & 59418（第1、2、3項）& 60007 & 60429（Owner 精準 DOM 規則）：
    1. 任何情況見到 button[aria-label="You have reached your usage limit for today"] 即判定為 Profile Daily Limit。
    2. 舊文字橫幅則須喺今次 session 實際推過一次後新增先算。"""
    if has_profile_daily_limit_dom(page, sid):
        return True
    key = str(sid or "").upper()
    attempted = _CYCLE_SEND_ATTEMPTED.get(key)
    if attempted is None:
        attempted = _has_pushed_in_current_session(sid, page=page)
    if not attempted:
        stale_pending = _consume_daily_limit_hit(sid)
        if stale_pending:
            log(sid, f"ℹ️ [DAILY-LIMIT:IGNORE-STALE] 今次 session 尚未實際推過（pushed_count=0），忽略推前殘留標記 ({stale_pending})")
        return False
    pending_reason = _peek_daily_limit_hit(sid)
    if pending_reason:
        log(sid, f"⚠️ [DAILY-LIMIT] 偵測到已觸發每日限制（{pending_reason}）→ 觸發三步重開（換 profile ＋ 開 VPN ＋ 去指定 URL，唔報 Muse）")
        return True
    phrase = "Something went wrong with this response, please try again"
    try:
        body_text = page.locator("body").inner_text(timeout=3000)
        if _has_active_error_banner_line(body_text, phrase) or _has_active_swr_try_again_line(body_text):
            st = _SESSION_PUSH_STATE.get(key) or {}
            pre_cnt = int(_CYCLE_PRE_SEND_SWR_COUNT.get(key, st.get("pre_push_swr_count", 0)))
            cur_cnt = _count_swr_banners_in_text(body_text)
            if pre_cnt > 0 and cur_cnt <= pre_cnt:
                log(sid, f"ℹ️ [DAILY-LIMIT:IGNORE-STALE] 紅字數量未多過推前基線 ({cur_cnt}<={pre_cnt})，忽略舊殘留訊息")
                return False
            log(sid, "⚠️ [DAILY-LIMIT:ITEM2] 今次 session 推完後檢測到每日限制紅字（Something went wrong + try again）→ 觸發三步重開（換 profile ＋ 開 VPN ＋ 去指定 URL，唔報 Muse）")
            return True
    except Exception:
        pass
    return False

def _report_conversation_too_long_to_muse(sid, dead_url, dead_profile=None):
    """應 59419 第4項更正：對話耗盡（The conversation is too long for the model）時寫 urgent bus 訊息報 Muse，通知呢個 SLOT 死咗要招新人、呢條 URL 永久退役。"""
    try:
        import json as _json, time as _t, subprocess as _sp
        ts = int(_t.time())
        msg = {
            "from": f"watcher-{sid.lower()}",
            "to": "host",
            "timestamp": ts,
            "priority": "urgent",
            "type": "conversation_too_long",
            "seat": sid,
            "url": dead_url,
            "profile": dead_profile,
            "body": f"{sid} 對話超長（The conversation is too long for the model），AI 已完結，URL 永久退役：{dead_url}（profile={dead_profile}）"
        }
        _sp.run([
            "/home/hatch/workspace/ssh-newserver.sh",
            f"cat > /root/muse-mesh/inbox/host/{ts}-watcher-{sid.lower()}.json && chmod 600 /root/muse-mesh/inbox/host/{ts}-watcher-{sid.lower()}.json"
        ], input=_json.dumps(msg).encode(), timeout=30, capture_output=True)
        log(sid, f"📨 [MUSE-REPORT] 已寫 bus 訊息去 server：conversation_too_long（{sid} 舊 URL 永久退役：{dead_url}）")
        return True
    except Exception as e:
        log(sid, f"寫 bus 訊息出錯: {e}")
        return False

def is_conversation_too_long(page, sid):
    """檢測對話超長：頁面出現紅字 "The conversation is too long for the model. Please start a new chat."
    應 59419 第4項更正：呢個代表對話耗盡（唔係 daily limit），既要換 URL 繼續跑，亦要報 Muse 通知舊 SLOT 死咗。
    返 True = 對話超長。
    """
    try:
        body_text = page.locator("body").inner_text(timeout=3000)
        if "The conversation is too long for the model" in body_text:
            log(sid, "⚠️ 檢測到對話超長（The conversation is too long for the model）→ 對話耗盡，需報 Muse 並換 URL")
            return True
    except Exception:
        pass
    return False

def is_arena_session_missing(page, sid):
    """檢查 Arena（經 Google login）有冇出現 session missing。
    Google 本身 login 冇問題，係 Arena 個 session 唔見咗。
    成日出現但難捉 DOM，用多種 pattern 鬆匹配。
    """
    try:
        body_text = page.locator("body").inner_text(timeout=3000).lower()
        # session missing 相關字眼（中英文）
        has_session = "session" in body_text or "工作階段" in body_text or "會話" in body_text
        has_missing = "missing" in body_text or "expired" in body_text or "遺失" in body_text or "過期" in body_text or "不存在" in body_text
        if has_session and has_missing:
            log(sid, f"偵測到 Arena session missing（URL: {page.url[:80]}）")
            return True
        return False
    except Exception:
        return False

def clear_arena_site_data(browser_ctx, page, sid):
    """清 arena.ai site data（經 CDP），保留 Google cookies。
    用 Storage.clearDataForOrigin 只清 arena.ai 個 origin。
    """
    try:
        cdp = browser_ctx.new_cdp_session(page)
        cdp.send("Storage.clearDataForOrigin", {
            "origin": "https://arena.ai",
            "storageTypes": "all"
        })
        log(sid, "已清 arena.ai site data（保留 Google cookies）")
        return True
    except Exception as e:
        log(sid, f"清 arena site data 出錯: {e}")
        return False

_LAST_GOOGLE_PW_FATAL = {}

def _is_google_password_prompt_visible(page):
    """應 59651 #8.3：檢測頁面是否出現可見之 Google 密碼格（input[type="password"]）且當前 Google session 已失效。"""
    try:
        if page is None or not hasattr(page, "locator"):
            return False
        url = str(getattr(page, "url", "") or "")
        if "arena.ai" in url and "accounts.google.com" not in url and "/challenge/" not in url and "/signin/" not in url:
            return False
        pwd = page.locator('input[type="password"]').first
        return bool(pwd.count() > 0 and pwd.is_visible(timeout=500))
    except Exception:
        return False

def _detect_google_password_error_or_challenge(page):
    """應 59651 #8.5：檢測填密碼後是否出現密碼錯誤、驗證碼、2FA 或其他異常（嚴禁無限 retry）。"""
    try:
        url = str(getattr(page, "url", "") or "")
        if "accounts.google.com" in url and "/challenge/" in url:
            if not any(p in url for p in ("/challenge/pwd", "/signin/v3/challenge/pwd", "/challenge/selection")):
                return True, f"google_2fa_challenge:{url[:80]}"
        if hasattr(page, "locator"):
            for sel in ('iframe[src*="recaptcha" i]', 'input[type="tel"]', '#idvPin', 'input[name="Pin"]'):
                try:
                    loc = page.locator(sel).first
                    if loc.count() > 0 and loc.is_visible(timeout=200):
                        return True, f"google_verification_prompt:{sel}"
                except Exception:
                    pass
            try:
                body_txt = (page.locator("body").inner_text(timeout=1500) or "").lower()
                for err_kw in (
                    "wrong password", "密碼不正確", "密碼錯誤", "incorrect password",
                    "verify it's you", "verify it’s you", "驗證您的身分", "too many failed attempts",
                    "try again later", "請稍後再試",
                ):
                    if err_kw in body_txt:
                        return True, f"google_auth_error:{err_kw}"
            except Exception:
                pass
    except Exception:
        pass
    return False, None

def _report_google_login_failure_to_muse(sid, profile_name, reason):
    """應 59651 #8.5 & 59654 修訂：密碼錯／彈驗證碼／其他異常時上報（記低邊個 profile＋咩原因＋時間），絕不含密碼，然後由呼叫方直接 pass 去下一個 profile 繼續推。"""
    import json as _json, time as _t, subprocess as _sp
    ts = int(_t.time())
    time_str = _t.strftime("%Y-%m-%d %H:%M:%S", _t.localtime(ts))
    prof_str = str(profile_name or Path(_SEAT_ACTIVE_PROFILE_DIR.get(str(sid or "").strip().upper(), "")).name or "unknown")
    reason_str = str(reason or "google_login_failed")
    log(sid, f"🚨 [GOOGLE-PW:REPORT] profile={prof_str} | reason={reason_str} | time={time_str} ({ts}) — Google 登入自動補密碼失敗，已上報並準備直接 pass 去下一個 profile 繼續推")
    try:
        msg = {
            "from": f"watcher-{str(sid or '').lower()}",
            "to": "host",
            "timestamp": ts,
            "time": time_str,
            "priority": "urgent",
            "type": "google_login_failed",
            "seat": sid,
            "profile": prof_str,
            "reason": reason_str,
            "body": f"{sid} Google 登入自動補密碼失敗（profile={prof_str}, reason={reason_str}, time={time_str}），已直接 pass 去下一個 profile 繼續推",
        }
        _sp.run([
            "/home/hatch/workspace/ssh-newserver.sh",
            f"cat > /root/muse-mesh/inbox/host/{ts}-watcher-{str(sid or '').lower()}-login.json && chmod 600 /root/muse-mesh/inbox/host/{ts}-watcher-{str(sid or '').lower()}-login.json",
        ], input=_json.dumps(msg).encode(), timeout=15, capture_output=True)
        return True
    except Exception as e:
        log(sid, f"⚠️ [GOOGLE-PW:REPORT] 遠端 bus 寫入異常 ({type(e).__name__})，本地已記錄 profile={prof_str} reason={reason_str} time={time_str}")
        return False

def _fill_google_password_once(page, sid, seed_root=None):
    """應 59651 #8.1-#8.5：讀 `.google-pw`（0600）→ 填密碼 → 撳 Next → 等狀態轉換。
    密碼絕不寫入 log（最多記一句「已自動填密碼」）；失敗即返 (False, reason)，嚴禁無限 retry。"""
    pw = _read_google_password(sid, seed_root=seed_root)
    if not pw:
        return False, "google_pw_file_missing_or_invalid_mode"
    try:
        pwd_input = page.locator('input[type="password"]').first
        pwd_input.wait_for(state="visible", timeout=15000)
        url_before = str(getattr(page, "url", "") or "")
        pwd_input.fill(pw)
        log(sid, "已自動填密碼")
    except Exception as e:
        log(sid, f"自動填密碼失敗: {type(e).__name__}，停手")
        return False, f"fill_exception:{type(e).__name__}"
    finally:
        pw = None

    clicked_next = False
    for btn_sel in ('#passwordNext', 'button:has-text("Next")', 'button:has-text("繼續")', 'button[type="submit"]'):
        try:
            btn = page.locator(btn_sel).first
            if btn.count() > 0 and btn.is_visible(timeout=3000):
                try:
                    btn.click(timeout=10000)
                except Exception:
                    btn.evaluate("e => e.click()")
                log(sid, "已撳密碼 Next")
                clicked_next = True
                break
        except Exception:
            continue
    if not clicked_next:
        try:
            page.keyboard.press("Enter")
            log(sid, "已撳密碼 Next")
            clicked_next = True
        except Exception as e:
            return False, f"next_click_failed:{type(e).__name__}"

    wait_for_login_signal(
        page,
        lambda: (
            str(getattr(page, "url", "") or "") != url_before
            or ("arena.ai" in str(getattr(page, "url", "") or "") and "accounts.google.com" not in str(getattr(page, "url", "") or ""))
            or _detect_google_password_error_or_challenge(page)[0]
        ),
        timeout_ms=10000,
    )
    has_err, err_reason = _detect_google_password_error_or_challenge(page)
    if has_err:
        log(sid, f"🛑 [GOOGLE-PW:FAIL] 自動填密碼後偵測到密碼錯誤或驗證碼挑戰 ({err_reason})，即刻停手（唔重試）")
        return False, err_reason
    if _is_google_password_prompt_visible(page):
        log(sid, "🛑 [GOOGLE-PW:FAIL] 自動填密碼並撳 Next 後仍停留喺密碼框（疑似密碼錯誤），即刻停手（唔重試）")
        return False, "password_input_still_visible_after_submit"
    return True, "ok"

def _dismiss_cookie_consent(page, sid, timeout_ms=8000):
    """應 59724/59725/59729（Owner 實測 timing 要求）：
    撳走 arena.ai Cookie Consent popup（"This website uses cookies..." + [Accept Cookies] 黑色掣）。
    內建 timing retry loop（預設等 8 秒，每 500ms check 一次），一旦見到即撳並返回 True；
    除 navigation 後呼叫外，每次 send 之前及讀 body 確認 ACK 前均會再 check，防 popup 遮擋導致 UNCONFIRMED。"""
    if page is None:
        return False
    import time as _t
    deadline = _t.time() * 1000 + max(500, int(timeout_ms or 0))
    selectors = (
        'button:has-text("Accept Cookies")',
        'button:has-text("Accept all cookies")',
        'button:has-text("Accept All")',
        '[role="dialog"] button:has-text("Accept")',
        'div:has-text("This website uses cookies") button:has-text("Accept")',
    )
    while True:
        try:
            for sel in selectors:
                try:
                    btn = page.locator(sel).first
                    if btn.count() > 0 and btn.is_visible(timeout=400):
                        try:
                            btn.click(timeout=3000)
                        except Exception:
                            btn.evaluate("e => e.click()")
                        log(sid, "已撳走 Cookie Consent")
                        try:
                            page.wait_for_timeout(800)
                        except Exception:
                            _t.sleep(0.8)
                        return True
                except Exception:
                    pass
        except Exception:
            pass
        if _t.time() * 1000 >= deadline:
            break
        try:
            page.wait_for_timeout(500)
        except Exception:
            _t.sleep(0.5)
    return False

def handle_arena_login_flow(page, sid, browser_ctx=None, seed_root=None):
    """應 59651 #8：Google session 過期撞到 Google 登入密碼頁時，自動由 `.google-pw`（0600）補密碼行完登入流程繼續推。
    步驟：Cookie Consent / Terms of Use → Continue with Google → 帳號選擇 → 密碼頁（讀 `.google-pw` 自動補密碼＋撳 Next，最多試 1 次）→ 返 arena.ai。
    密碼錯／彈驗證碼／其他異常：一律按自停／上報機制處理，嚴禁無限 retry。
    """
    import time as _time
    s_key = str(sid or "").strip().upper()
    _LAST_GOOGLE_PW_FATAL.pop(s_key, None)
    MAX_LOGIN_WAIT = 60000
    login_start = _time.time() * 1000
    pwd_attempted = False
    log(sid, "開始自動登入流程（支援 .google-pw 自動補密碼，最多 1 次）…")

    def _try_password_step_or_abort():
        nonlocal pwd_attempted
        if pwd_attempted:
            reason = "password_retry_blocked"
            _LAST_GOOGLE_PW_FATAL[s_key] = reason
            log(sid, "🛑 [GOOGLE-PW:NO-RETRY] 本輪已自動填過一次密碼但仍要求密碼，嚴禁無限 retry，即刻停手")
            _report_google_login_failure_to_muse(sid, Path(_SEAT_ACTIVE_PROFILE_DIR.get(s_key, "")).name, reason)
            return False
        pwd_attempted = True
        ok_pw, pw_reason = _fill_google_password_once(page, sid, seed_root=seed_root)
        if not ok_pw:
            _LAST_GOOGLE_PW_FATAL[s_key] = pw_reason
            _report_google_login_failure_to_muse(sid, Path(_SEAT_ACTIVE_PROFILE_DIR.get(s_key, "")).name, pw_reason)
            return False
        return True

    # 0. 應 59724/59725/59729：喺 Terms of Use 處理隔離，先處理 Cookie Consent popup（5秒 retry loop）
    _dismiss_cookie_consent(page, sid, timeout_ms=5000)

    # 1. 處理 Terms of Use dialog 及 Cookie Consent（15 秒）
    terms_deadline = _time.time() * 1000 + 15000
    while _time.time() * 1000 < terms_deadline:
        try:
            if "accounts.google.com" in str(getattr(page, "url", "") or "") or _is_google_password_prompt_visible(page):
                break
            _dismiss_cookie_consent(page, sid, timeout_ms=500)
            dlg = page.locator('[role="dialog"]').filter(has=page.locator('h2:has-text("Terms of Use")')).first
            if dlg.count() > 0 and dlg.is_visible(timeout=1000):
                agree = page.locator('[role="dialog"] button[type="submit"]:has-text("Agree")').first
                if agree.count() > 0 and agree.is_visible(timeout=3000):
                    agree.click(timeout=5000)
                else:
                    page.keyboard.press("Enter")
                log(sid, "已處理 Terms of Use")
                wait_for_login_signal(page,
                    lambda: not (dlg.count() > 0 and dlg.is_visible(timeout=250)),
                    2000)
                break
        except Exception:
            pass
        if _time.time() * 1000 - login_start > MAX_LOGIN_WAIT:
            break
        page.wait_for_timeout(200)

    # 2. 撳 Continue with Google（20 秒）
    _dismiss_cookie_consent(page, sid)
    google_deadline = _time.time() * 1000 + 20000
    while _time.time() * 1000 < google_deadline:
        try:
            if "accounts.google.com" in str(getattr(page, "url", "") or "") or _is_google_password_prompt_visible(page):
                break
            gbtn = page.locator('button:has-text("Continue with Google")').first
            if gbtn.count() > 0 and gbtn.is_visible(timeout=1000):
                url_before = page.url
                gbtn.click(timeout=5000)
                log(sid, "已撳 Continue with Google")
                wait_for_login_signal(page,
                    lambda: page.url != url_before or "accounts.google.com" in page.url or
                            page.locator('input[type="password"]').first.is_visible(timeout=200),
                    3000)
                break
        except Exception:
            pass
        if _time.time() * 1000 - login_start > MAX_LOGIN_WAIT * 2:
            break
        page.wait_for_timeout(200)

    # 3. Google 帳號與密碼頁處理（25 秒）
    account_handled = False
    account_deadline = _time.time() * 1000 + 25000
    while _time.time() * 1000 < account_deadline:
        try:
            url = str(getattr(page, "url", "") or "")
            # 3a0. Arena session missing（經 Google login）→ 即刻清 arena 再重跑
            if is_login_flow_stuck_on_session_missing(page, sid) or is_arena_session_missing(page, sid):
                log(sid, "Arena session missing → 清 arena.ai 重跑 watcher")
                if browser_ctx is not None:
                    clear_arena_site_data(browser_ctx, page, sid)
                return "SESSION_CLEARED"
            # 3b. Challenge（2FA／驗證碼）頁
            if "accounts.google.com" in url and "/challenge/" in url:
                if "/challenge/pwd" not in url and "/signin/v3/challenge/pwd" not in url and "/challenge/selection" not in url:
                    log(sid, "遇到二次驗證／驗證碼挑戰，等 10 秒睇下會唔會自動過…")
                    if wait_for_login_signal(page, lambda: "arena.ai" in str(getattr(page, "url", "") or "") and "accounts.google.com" not in str(getattr(page, "url", "") or ""), 10000):
                        log(sid, "二次驗證後返到 arena.ai，視為通過")
                        account_handled = True
                        break
                    reason = f"google_2fa_challenge_blocked:{url[:80]}"
                    _LAST_GOOGLE_PW_FATAL[s_key] = reason
                    log(sid, f"🛑 [GOOGLE-PW:2FA] 彈驗證碼／二次驗證未能自動通過，即刻停手並上報（唔重試）")
                    _report_google_login_failure_to_muse(sid, Path(_SEAT_ACTIVE_PROFILE_DIR.get(s_key, "")).name, reason)
                    return False
                if "/challenge/selection" in url:
                    pwd_opt = page.locator('div[data-challengeentrytype="1"]').first
                    if pwd_opt.count() > 0 and pwd_opt.is_visible(timeout=1000):
                        url_before = page.url
                        pwd_opt.click(timeout=5000)
                        wait_for_login_signal(page,
                            lambda: page.url != url_before or
                                    page.locator('input[type="password"]').first.is_visible(timeout=200),
                            2000)
                        continue
                    else:
                        reason = "challenge_selection_no_pwd_option"
                        _LAST_GOOGLE_PW_FATAL[s_key] = reason
                        log(sid, "挑戰選擇頁搵唔到密碼選項，終止登入")
                        _report_google_login_failure_to_muse(sid, Path(_SEAT_ACTIVE_PROFILE_DIR.get(s_key, "")).name, reason)
                        return False
            # 3c. 應 59651 #8：頁面出現 Google 密碼格（input[type="password"]）→ 讀 `.google-pw` 自動填密碼＋撳 Next
            if "/challenge/pwd" in url or "/signin/v3/challenge/pwd" in url or _is_google_password_prompt_visible(page):
                if not _try_password_step_or_abort():
                    return False
            # 3d. 帳號選擇
            for sel in ['[data-identifier]', 'div[role="link"][data-authuser]', '.VV3oRb[role="link"]']:
                acc = page.locator(sel).first
                if acc.count() > 0 and acc.is_visible(timeout=3000):
                    url_before = page.url
                    acc.click(timeout=5000)
                    log(sid, f"已揀帳號（{sel}）")
                    wait_for_login_signal(page,
                        lambda: page.url != url_before or
                                page.locator('input[type="password"]').first.is_visible(timeout=200),
                        2000)
                    if _is_google_password_prompt_visible(page) or "/challenge/pwd" in str(getattr(page, "url", "") or ""):
                        if not _try_password_step_or_abort():
                            return False
                    break
            # 3e. 返 arena.ai 確認
            return_deadline = _time.time() * 1000 + 20000
            while _time.time() * 1000 < return_deadline:
                url = str(getattr(page, "url", "") or "")
                if "arena.ai" in url and "accounts.google.com" not in url:
                    page.wait_for_load_state("domcontentloaded", timeout=10000)
                    page.wait_for_timeout(500)
                    account_handled = True
                    break
                if "accounts.google.com" in url or _is_google_password_prompt_visible(page):
                    has_err, err_r = _detect_google_password_error_or_challenge(page)
                    if has_err:
                        _LAST_GOOGLE_PW_FATAL[s_key] = err_r
                        log(sid, f"🛑 [GOOGLE-PW:FAIL] 偵測到 Google 登入錯誤／挑戰 ({err_r})，即刻停手")
                        _report_google_login_failure_to_muse(sid, Path(_SEAT_ACTIVE_PROFILE_DIR.get(s_key, "")).name, err_r)
                        return False
                    if _is_google_password_prompt_visible(page):
                        if not _try_password_step_or_abort():
                            return False
                for sel in ['[jsname="uRHG6"] button', 'button:has-text("繼續")', 'button:has-text("Continue")', 'button:has-text("Allow")', '.tyoyWc button']:
                    cb = page.locator(sel).first
                    if cb.count() > 0 and cb.is_visible(timeout=1000):
                        url_before = page.url
                        cb.click(timeout=5000)
                        log(sid, f"已撳繼續/Allow（{sel}）")
                        wait_for_login_signal(page,
                            lambda: page.url != url_before or
                                    ("arena.ai" in page.url and "accounts.google.com" not in page.url),
                            3000)
                        break
                page.wait_for_timeout(200)
            if account_handled:
                break
        except Exception as e:
            log(sid, f"登入流程出錯: {e}")
        if _time.time() * 1000 - login_start > MAX_LOGIN_WAIT * 3:
            break
        page.wait_for_timeout(200)

    if account_handled:
        log(sid, "自動登入成功，已返 arena.ai")
    else:
        log(sid, "自動登入失敗（超時或中斷）")
    return account_handled

def _do_send_once(page, sid):
    """搵輸入框 → click → 打字 → Enter → POST-SEND 關 → ACK（三態）；ACK 確認才扣召回號。

    HOLD 期間唔自動重試。自解**要有憑據**（A4/8948：唔可以純子串就算——輸入框係 contenteditable 時，
    草稿會計入 body.inner_text，純子串會誤自解、燒號）：輸入框讀得到、入面冇 pending 句、
    而且 body 出現次數 **多過設 HOLD 嗰刻嘅基線**（冇基線可比時，最起碼 body 要有 pending 句＋輸入框乾淨）。
    讀唔到任何一項＝證據不足＝HOLD 持續（fail-closed，等人手確認）。"""
    global _recall_unconfirmed_hold, _recall_hold_baseline
    if _recall_unconfirmed_hold:
        try:
            _body_now = page.locator("body").inner_text(timeout=3000)
        except Exception:
            _body_now = None
        _inp_now = find_input_box(page, sid)
        _box_now = _box_text(_inp_now) if _inp_now else None
        _cnt_now = _needle_count(_body_now, _pending_num)
        if _box_now is None or _cnt_now is None:
            log(sid, f"UNCONFIRMED HOLD 持續（輸入框或 body 讀唔到；pending {_pending_num}）——證據不足，唔自解、唔重試")
            return "UNCONFIRMED"
        if _needle_in(_box_now, _pending_num):
            log(sid, f"UNCONFIRMED HOLD 持續（輸入框仍有 pending 'Continue SESSION {_pending_num}'＝草稿）——唔自解、唔重試")
            return "UNCONFIRMED"
        if _recall_hold_baseline is not None and _cnt_now > _recall_hold_baseline:
            _base_shown = _recall_hold_baseline
            commit_recall_sent()
            _recall_unconfirmed_hold = False
            _recall_hold_baseline = None
            _recall_state_clear()
            _mark_session_pushed(sid, page=page)
            log(sid, f"UNCONFIRMED 自解：body 出現次數 {_cnt_now} > 基線 {_base_shown}——pending 'Continue SESSION {_last_sent_num}' 其實已送出 → 扣號並解除 HOLD；本 cycle 唔再發送")
            return "HOLD_RESOLVED"
        if _recall_hold_baseline is None:
            log(sid, "UNCONFIRMED HOLD 持續（冇基線可比）——fail-closed，唔自解：唔可以用『body 有句』單憑；要**人手憑證據核實**後處理（**重啟唔係解法**：會丟失 pending／baseline）")
            return "UNCONFIRMED"
        log(sid, f"UNCONFIRMED HOLD 持續（pending 出現次數 {_cnt_now} 未多過基線）——唔自解、唔重試")
        return "UNCONFIRMED"
    if _recall_counter <= 0:
        log(sid, "召回號已用完（0）→ HOLD，上報（本 cycle 唔發送）")
        return False
    if not ensure_rotation_url(page, sid):
        log(sid, "[URL-GUARD] send 中止（URL 唔喺 JSON）")
        return False
    # 應 59729：每次 send 之前再 check 一次 Cookie Consent popup（含 5 秒 retry loop，每 500ms check 一次）
    _dismiss_cookie_consent(page, sid, timeout_ms=5000)
    inp = find_input_box(page, sid)
    if not inp:
        log(sid, "ERROR: 搵唔到輸入框 → 截圖＋dump DOM")
        try:
            page.screenshot(path=f"/tmp/{sid.lower()}-no-input.png")
        except:
            pass
        try:
            dom = page.content()
            with open(f"/tmp/{sid.lower()}-no-input-dom.html", "w") as f:
                f.write(dom)
        except:
            pass
        return False
    try:
        # 議會 patch 2026-10-16（跟進）：輸入框 focus click 同樣 Playwright 8000ms 超時，改用 JS click
        inp.evaluate("e => e.click()")
        page.wait_for_timeout(800)
        inp.fill("")
        msg = get_recall_msg()  # peek：唔扣號（扣號喺 ACK 確認之後）
        try:
            # 打字前讀 body（此時輸入框已 fill("") ⇒ 基線乾淨）；讀唔到＝None（唔可以當 0）
            _body_before = page.locator("body").inner_text(timeout=3000)
        except Exception:
            _body_before = None
        page.keyboard.type(msg, delay=25)
        page.wait_for_timeout(800)
        page.keyboard.press("Enter")
        log(sid, "已按 Enter 發送")
        # v0.93: 發完訊息後過 checkbox 關（跟 CA POST-SEND 模式）
        # 過唔到就唔繼續，直接返
        page.wait_for_timeout(2000)
        if not ca_checkbox_gate(page, sid, "POST-SEND"):
            log(sid, "POST-SEND checkbox 未過，停")
            return False
        # owner 2026-10-05 15:23 下令：send 完 3 秒後自動 cap 圖（捉藍 checkbox）
        page.wait_for_timeout(3000)
        try:
            page.screenshot(path=f"/tmp/{sid}-postsend-3s.png")
            log(sid, f"已cap圖 /tmp/{sid}-postsend-3s.png（send後3秒）")
        except Exception as e:
            log(sid, f"cap圖失敗: {e}")
        # A6/8874②＋A4/8924：唔可以用「過咗 POST-SEND 關」代替 ACK；三態（True／False／UNCONFIRMED）
        _dismiss_cookie_consent(page, sid, timeout_ms=2000)
        try:
            _after_text = page.locator("body").inner_text(timeout=3000)
        except Exception:
            _after_text = None
        _box_after = _box_text(inp)
        _ack = recall_ack_ok(_body_before, _after_text, _box_after, _pending_num)
        if _ack is True:
            commit_recall_sent()
            _recall_state_clear()
            _mark_session_pushed(sid, page=page)
            log(sid, f"ACK 確認：見到 exact 'Continue SESSION {_last_sent_num}' 且輸入框已清空 → 扣號（下一個 {_recall_counter}）")
            return True
        if _ack is None:
            _recall_unconfirmed_hold = True
            _recall_hold_baseline = _needle_count(_body_before, _pending_num)  # 讀唔到＝None（冇基線）
            _recall_state_mark_hold()  # v6.5：pending／baseline／hold 跨 restart 保留
            log(sid, "UNCONFIRMED：有來源讀唔到（body 前／後 或 輸入框）→ 唔扣號、設 HOLD、唔自動重試")
            return "UNCONFIRMED"
        log(sid, f"NO_ACK：三個來源都讀到，但未確認 exact 'Continue SESSION {_pending_num}' 送出 → 唔扣號")
        return False
    except Exception as e:
        log(sid, f"打字/發送出錯: {e}")
        return False

def do_send_cycle(page, sid):
    """v3 運作邏輯（用戶逐點修正）：
    1. 見 Stop 掣（生成緊）→ 乜都唔做，SKIP_GENERATING
    2. 見 Keep working → 撳 → 等 5 秒 → reload → 等頁面生成 → 等 5 秒 → 確認消失 → send
       仲有 → 再撳一次 → 等 5 秒 → reload → 等生成 → 等 5 秒 → 仲有 → HOLD_ERROR
    3. 冇 Stop 掣、冇 Keep working → 直接 send
    4. Send 後：等 10 秒 → reload → 等頁面生成 → 等 5 秒
       有 Stop 掣 → SUCCESS；有 Keep working → SUCCESS_NEXT_CYCLE（即刻下一個循環）
       兩個都冇 → 再 send 一次
    5. 第二次：等 10 秒 → reload → 等生成 → 等 5 秒
       有 Stop 掣 → SUCCESS；有 Keep working → SUCCESS_NEXT_CYCLE；兩個都冇 → _mark_daily_limit_hit + DAILY_LIMIT（應 59754/59758 自動換 URL）
    """
    _s_key_cycle = str(sid or "").upper()
    _CYCLE_SEND_ATTEMPTED[_s_key_cycle] = False
    _CYCLE_PRE_SEND_SWR_COUNT[_s_key_cycle] = 0
    # Owner 60392 + 60429：兩個正面訊號都要觀察；Daily Limit 在任何共存情況均勝出。
    initial_generating = _is_generating_with_heartbeat(page, sid)
    if has_profile_daily_limit_dom(page, sid):
        return "DAILY_LIMIT"
    if initial_generating:
        log(sid, "見到 Stop 掣（生成緊），乜都唔做，等下個 cycle")
        return "SKIP_GENERATING"
    if not ensure_rotation_url(page, sid):
        log(sid, "[URL-GUARD] cycle 中止（URL 唔喺 JSON）")
        return "URL_GUARD_ABORT"
    _dismiss_cookie_consent(page, sid)
    if has_profile_daily_limit_dom(page, sid):
        return "DAILY_LIMIT"
    # 0. recall state（跨 restart 嘅 HOLD／pending／baseline；人手 reconciliation）
    if not _recall_state_apply(sid):
        log(sid, "recall state 讀唔到（fail-closed）→ 停呢個 cycle：零扣、零送")
        return "UNCONFIRMED"
    # 2. 見 Keep working → 撳（應 59418 第1項：撳完藍色掣 → 紫色 loading 轉完 → 8 秒後出返藍色代表冇繼續行 → daily limit 換 URL 唔報 Muse）
    kw = find_keep_working(page, sid)
    if kw:
        try:
            # 議會 patch 2026-10-16：Playwright click 連續 8000ms 超時（KW_CLICK_ERROR），改用 JS click（唔做 actionability check，即時 dispatch）
            kw.evaluate("e => e.click()")
            log(sid, "撳咗藍色 Keep working 掣，等待紫色 loading 轉完後等 8 秒...")
            _wait_for_purple_loading_finished(page, sid)
            page.wait_for_timeout(8000)
            generating_after_kw = _is_generating_with_heartbeat(page, sid)
            if has_profile_daily_limit_dom(page, sid):
                return "DAILY_LIMIT"
            if find_keep_working(page, sid) is not None and not generating_after_kw:
                if _has_pushed_in_current_session(sid, page=page):
                    log(sid, "🚨 [DAILY-LIMIT:ITEM1] 撳完藍色掣，紫色 loading 轉完 8 秒後出返藍色（Keep working 重現，代表冇繼續行）→ 判定 daily limit，立即換 URL（唔報 Muse）")
                    _mark_daily_limit_hit(sid, "item1_purple_loading_8s_blue_reappear")
                    return "DAILY_LIMIT"
                log(sid, "ℹ️ [DAILY-LIMIT:ITEM1-TRY-SEND] 今個 cycle 尚未實際推過，唔因舊 Keep working 判 DAILY_LIMIT；先發送一次召回句")
            else:
                page.reload(wait_until="domcontentloaded", timeout=60000)
                wait_for_page_generated(page, sid)
                page.wait_for_timeout(5000)
                if has_profile_daily_limit_dom(page, sid):
                    return "DAILY_LIMIT"
                log(sid, "Reload 完（等頁面生成後 5 秒），確認有冇 Keep working")
                if find_keep_working(page, sid) is not None:
                    log(sid, "仲有 Keep working，再試一次")
                    kw2 = find_keep_working(page, sid)
                    if kw2:
                        # 議會 patch 2026-10-16：同上，JS click 代替 Playwright click
                        kw2.evaluate("e => e.click()")
                        _wait_for_purple_loading_finished(page, sid)
                        page.wait_for_timeout(8000)
                        generating_after_kw_retry = _is_generating_with_heartbeat(page, sid)
                        if has_profile_daily_limit_dom(page, sid):
                            return "DAILY_LIMIT"
                        if find_keep_working(page, sid) is not None and not generating_after_kw_retry:
                            if _has_pushed_in_current_session(sid, page=page):
                                log(sid, "🚨 [DAILY-LIMIT:ITEM1] 再試後紫色 loading 轉完 8 秒後仍出返藍色（Keep working 重現）→ 判定 daily limit，立即換 URL（唔報 Muse）")
                                _mark_daily_limit_hit(sid, "item1_purple_loading_8s_blue_reappear_retry")
                                return "DAILY_LIMIT"
                        else:
                            page.reload(wait_until="domcontentloaded", timeout=60000)
                            wait_for_page_generated(page, sid)
                            page.wait_for_timeout(5000)
                            if has_profile_daily_limit_dom(page, sid):
                                return "DAILY_LIMIT"
                    if has_profile_daily_limit_dom(page, sid):
                        return "DAILY_LIMIT"
                    if find_keep_working(page, sid) is not None and _has_pushed_in_current_session(sid, page=page):
                        log(sid, "🚨 [DAILY-LIMIT:ITEM1] 兩次撳藍色掣後仍出返藍色（Keep working 重現）→ 判定 daily limit，立即換 URL（唔報 Muse）")
                        _mark_daily_limit_hit(sid, "item1_keep_working_persists")
                        return "DAILY_LIMIT"
            if _is_generating_with_heartbeat(page, sid):
                log(sid, "撳 Keep working 後頁面已恢復生成緊（見到 Stop 掣），唔加推，本輪完成交棒下一席")
                return "SKIP_GENERATING"
            log(sid, "確認可進入發送步驟")
        except Exception as e:
            log(sid, f"撳 Keep working 出錯: {e}")
            return "KW_CLICK_ERROR"
    else:
        log(sid, "無 Keep working 掣，直接 send")
    if has_profile_daily_limit_dom(page, sid):
        return "DAILY_LIMIT"
    # 3. Send（應 59418 第3項 & 60007：喺推之前記低最底 Response ended 時間戳與舊錯誤基準）
    _record_response_ended_before_push(page, sid)
    _record_session_push_before_send(page, sid)
    r = _do_send_once(page, sid)
    if r == "UNCONFIRMED":
        log(sid, "發送結果未確認（UNCONFIRMED）→ 停呢個 cycle：唔行驗證、唔行第二次送")
        return "UNCONFIRMED"
    if r == "HOLD_RESOLVED":
        log(sid, "HOLD 已自解（已扣號）→ 停呢個 cycle：唔行驗證、唔行第二次送")
        return "HOLD_RESOLVED"
    if not r:
        return "NO_INPUT"
    # _do_send_once marks the session only after deterministic ACK.
    # 4. 驗證（第一次）：等 10 秒 → 10秒內有冇出現 → 無就 skip gate 直接 reload
    # owner 2026-10-05 16:30 下令：10s 內冇出現就唔使過 checkbox 關
    log(sid, "等 10 秒，監測有冇 checkbox 出現…")
    import time
    wid = _seat_window_id(sid, page=page)
    appeared = False
    for i in range(10):
        time.sleep(1)
        if not wid:
            break
        # 快 check 三套色（唔點，淨睇有冇）
        c_orange = _read_window_pixel(wid, ORANGE_CHECK_X, ORANGE_CHECK_Y)
        c_purple = _read_window_pixel(wid, PURPLE_CHECK_X, PURPLE_CHECK_Y)
        c_blue = _check_window_area_color(wid, BLUE_CHECK_X, BLUE_CHECK_Y, BLUE_CHECK_W, BLUE_CHECK_H, BLUE_CHECK_COLOR)
        if (c_orange and _color_match(c_orange, ORANGE_CHECK_COLOR)) or \
           (c_purple and _color_match(c_purple, PURPLE_CHECK_COLOR)) or c_blue:
            log(sid, f"第 {i+1} 秒見到 checkbox，行完整 gate")
            appeared = True
            break
    
    if appeared:
        # 有出現先過完整 gate
        if not ca_checkbox_gate(page, sid, "VERIFY-BEFORE-RELOAD"):
            log(sid, "VERIFY checkbox 未過，唔 reload")
            return "CHECKBOX_BLOCKED"
    else:
        log(sid, "10 秒內冇 checkbox，直接 reload")
    
    page.reload(wait_until="domcontentloaded", timeout=60000)
    _dismiss_cookie_consent(page, sid, timeout_ms=5000)
    wait_for_page_generated(page, sid)
    page.wait_for_timeout(5000)
    has_gen = _is_generating_with_heartbeat(page, sid)
    if has_profile_daily_limit_dom(page, sid):
        return "DAILY_LIMIT"
    has_kw = find_keep_working(page, sid) is not None
    if has_gen or has_kw:
        if _check_response_ended_after_push_success(page, sid):
            return "DAILY_LIMIT"
        if has_kw:
            log(sid, "Reload 後有 Keep working → 成功，即刻開始下一個循環")
            return "SUCCESS_NEXT_CYCLE"
        log(sid, "Reload 後有 Stop 掣（生成緊）→ 成功")
        return "SUCCESS"
    # 5. 兩個都冇 → 再送一次
    log(sid, "Reload 後無 Stop 掣又無 Keep working → 再送一次")
    r2 = _do_send_once(page, sid)
    if r2 == "UNCONFIRMED":
        log(sid, "第二次送出未確認（UNCONFIRMED）→ 停，唔再試")
        return "UNCONFIRMED"
    if r2 == "HOLD_RESOLVED":
        log(sid, "第二次送出前 HOLD 已自解（已扣號）→ 停，唔再試")
        return "HOLD_RESOLVED"
    if not r2:
        return "NO_INPUT_2"
    log(sid, "第二次送出，等 10 秒…")
    page.wait_for_timeout(10000)
    page.reload(wait_until="domcontentloaded", timeout=60000)
    _dismiss_cookie_consent(page, sid, timeout_ms=5000)
    wait_for_page_generated(page, sid)
    page.wait_for_timeout(5000)
    has_gen2 = _is_generating_with_heartbeat(page, sid)
    if has_profile_daily_limit_dom(page, sid):
        return "DAILY_LIMIT"
    has_kw2 = find_keep_working(page, sid) is not None
    if has_gen2 or has_kw2:
        if _check_response_ended_after_push_success(page, sid):
            return "DAILY_LIMIT"
        if has_kw2:
            log(sid, "第二次 reload 有 Keep working → 成功，即刻開始下一個循環")
            return "SUCCESS_NEXT_CYCLE"
        log(sid, "第二次 reload 有 Stop 掣（生成緊）→ 成功")
        return "SUCCESS"
    else:
        log(sid, "🚨 [DAILY-LIMIT:NO-STOP-NO-KW] 第二次 reload 後兩粒掣都無（無 Stop 掣又無 Keep working）→ 判定 DAILY_LIMIT，即刻自動換 URL")
        _mark_daily_limit_hit(sid, "no_stop_no_keepworking_after_push")
        return "DAILY_LIMIT"

def _get_browser_window_id(sid=None, page=None):
    """兼容轉發至統一本席 PID 樹視窗解析器 _seat_window_id（已徹底移除面積啟發式）"""
    return _seat_window_id(sid=sid, page=page)

def _read_window_pixel(window_id, x, y):
    """跟 CA：用 import -window 讀 window 相對座標 pixel"""
    import subprocess
    try:
        out = subprocess.run(['import', '-window', str(window_id),
                            '-crop', f'1x1+{x}+{y}', '-depth', '8', 'txt:-'],
                           capture_output=True, text=True, timeout=5,
                           env=_x_env())
        import re
        m = re.search(r'#([0-9a-fA-F]{6})', out.stdout)
        return '#' + m.group(1).lower() if m else None
    except:
        return None

def _color_match(c1, c2, tolerance=10):
    """顏色比對（容差，2026-10-05 19:50 HKT owner 指出 exact match 太嚴加嘅）
    每個 RGB channel 差唔多過 tolerance 就算 match。
    """
    try:
        c1 = c1.lstrip('#')
        c2 = c2.lstrip('#')
        r1, g1, b1 = int(c1[0:2], 16), int(c1[2:4], 16), int(c1[4:6], 16)
        r2, g2, b2 = int(c2[0:2], 16), int(c2[2:4], 16), int(c2[4:6], 16)
        return abs(r1-r2) <= tolerance and abs(g1-g2) <= tolerance and abs(b1-b2) <= tolerance
    except:
        return False

def _check_window_area_color(window_id, cx, cy, w, h, hex_color):
    """跟 CA checkAreaColor：檢查範圍內有冇目標色（有容差）"""
    import subprocess
    try:
        # 抽樣檢查範圍內幾點
        for dx, dy in [(0,0), (w//2,h//2), (w-1,0), (0,h-1), (w-1,h-1)]:
            c = _read_window_pixel(window_id, cx+dx, cy+dy)
            if c and _color_match(c, hex_color, tolerance=10):
                return True
        return False
    except:
        return False

def _xdotool_click(window_id, x, y):
    """跟 CA：xdotool 三步點擊"""
    import subprocess, time
    env = _x_env()
    try:
        subprocess.run(['xdotool', 'windowraise', str(window_id)], env=env, timeout=3, capture_output=True)
        time.sleep(0.2)
        subprocess.run(['xdotool', 'windowactivate', '--sync', str(window_id)], env=env, timeout=3, capture_output=True)
        time.sleep(0.3)
        subprocess.run(['xdotool', 'mousemove', '--window', str(window_id), str(x), str(y), 'click', '1'],
                      env=env, timeout=5, capture_output=True)
        return True
    except:
        return False

def ca_checkbox_gate(page, sid, label):
    _post_send_phase = label in ("POST-SEND", "VERIFY-BEFORE-RELOAD")
    _zok, _ = ensure_zoom_100(page, sid, f"GATE-{label}")
    if not _zok:
        log(sid, f"🚨 [CAUSAL-NOTE:Z2-HOLD] {label} 因 Zoom 未達 100% 拒絕執行座標點擊")
        return False
    """v0.93: CA 兩套 checkbox 關卡（跟足 CA）
    第1套（橙色）：import -window 讀 (527,409) #f6821f → xdotool (270,420)
    第2套（藍色）：import -window 讀 (910,420,200x60) #1A73E8 → xdotool (276,425)
    """
    try:
        wid = _seat_window_id(sid, page=page)
        if not wid:
            return True
        
        # 第1套：紫色（優先） — check (715,415) #f3e9f7 → click (580,605)
        c3 = _read_window_pixel(wid, PURPLE_CHECK_X, PURPLE_CHECK_Y)
        if c3 and _color_match(c3, PURPLE_CHECK_COLOR):
            _xdotool_click(wid, PURPLE_CLICK_X, PURPLE_CLICK_Y)
            log(sid, f"[CHECKBOX-GATE] {label} 紫色 ({c3}) 已點 ({PURPLE_CLICK_X},{PURPLE_CLICK_Y})")
            
            # 點完等 8 秒，再 5 秒內每 1 秒 check（應 59418 第1項：撳完藍色掣 → 紫色 loading 轉完 → 8 秒後出返藍色／重現 ＝ daily limit）
            log(sid, f"[CHECKBOX-GATE] {label} 等 8 秒後開始 5 秒監測...")
            time.sleep(8)
            reappeared = False
            for i in range(5):
                time.sleep(1)
                cc = _read_window_pixel(wid, PURPLE_CHECK_X, PURPLE_CHECK_Y)
                cb = _read_window_pixel(wid, PURPLE_CLICK_X, PURPLE_CLICK_Y)
                if (cc and _color_match(cc, PURPLE_CHECK_COLOR)) or (cb and _color_match(cb, BLUE_CHECK_COLOR)):
                    log(sid, f"[CHECKBOX-GATE] {label} 點後第 {i+1} 秒紫色／藍色掣再出現 (c_purple={cc}, c_blue={cb})")
                    reappeared = True
                    break
            
            if not reappeared:
                log(sid, f"[CHECKBOX-GATE] {label} 5 秒內冇再出現，pass")
                return True
            
            # 再出現：第 2 次 click
            log(sid, f"[CHECKBOX-GATE] {label} 第 2 次點擊 ({PURPLE_CLICK_X},{PURPLE_CLICK_Y})")
            _xdotool_click(wid, PURPLE_CLICK_X, PURPLE_CLICK_Y)
            time.sleep(2)
            c4 = _read_window_pixel(wid, PURPLE_CHECK_X, PURPLE_CHECK_Y)
            cb4 = _read_window_pixel(wid, PURPLE_CLICK_X, PURPLE_CLICK_Y)
            if (c4 and _color_match(c4, PURPLE_CHECK_COLOR)) or (cb4 and _color_match(cb4, BLUE_CHECK_COLOR)):
                log(sid, f"🚨 [DAILY-LIMIT:ITEM1] [CHECKBOX-GATE] {label} 撳完藍色掣後紫色 loading 轉完 8 秒後仍出返藍色/重現 → 判定 daily limit，立即換 URL（唔報 Muse）")
                if _post_send_phase and _CYCLE_SEND_ATTEMPTED.get(str(sid or "").upper(), False):
                    _mark_daily_limit_hit(sid, f"item1_gate_purple_8s_blue_reappear:{label}")
                else:
                    log(sid, f"ℹ️ [DAILY-LIMIT:ITEM1-TRY-SEND] {label} 無本 cycle send 證據，唔預先標 daily limit")
                return False
            
            log(sid, f"[CHECKBOX-GATE] {label} 第 2 次點完消失，pass")
        

        # 第2套：藍色（200x60 範圍）— v0.93：藍色＝圖片挑戰（owner 2026-10-05 20:07 HKT 下令）
        # 邏輯：紫色過咗之後，如果藍色出現又清唔走＝中圖片挑戰，停低乜都唔做等人手
        # 第一次：點之前 check
        if _check_window_area_color(wid, BLUE_CHECK_X, BLUE_CHECK_Y, BLUE_CHECK_W, BLUE_CHECK_H, BLUE_CHECK_COLOR):
            _xdotool_click(wid, BLUE_CLICK_X, BLUE_CLICK_Y)
            log(sid, f"[CHECKBOX-GATE] {label} 藍色已點 ({BLUE_CLICK_X},{BLUE_CLICK_Y})，再驗一次")
            time.sleep(2)
            if _check_window_area_color(wid, BLUE_CHECK_X, BLUE_CHECK_Y, BLUE_CHECK_W, BLUE_CHECK_H, BLUE_CHECK_COLOR):
                log(sid, f"[CHECKBOX-GATE] {label} 🚨 藍色點完仲喺度＝圖片挑戰")
                log(sid, f"[CHECKBOX-GATE] {label} 🚨 停低，乜都唔做，等 MUSE 人手處理")
                return False
            return False
        
        # 點 checkbox
        _xdotool_click(wid, BLUE_CLICK_X, BLUE_CLICK_Y)
        log(sid, f"[CHECKBOX-GATE] {label} 已點 checkbox ({BLUE_CLICK_X},{BLUE_CLICK_Y})")
        
        # v0.93：藍色出現＝圖片挑戰，HOLD 等人手（owner 2026-10-05 20:07 HKT）
        # owner 2026-10-05 20:08 HKT：中圖片挑戰一樣停低搵 MUSE 處理，乜都唔做
        for i in range(10):
            time.sleep(0.5)
            if _check_window_area_color(wid, BLUE_CHECK_X, BLUE_CHECK_Y, BLUE_CHECK_W, BLUE_CHECK_H, BLUE_CHECK_COLOR):
                log(sid, f"[CHECKBOX-GATE] {label} 🚨 點後 {(i+1)*0.5} 秒出現藍色＝圖片挑戰")
                log(sid, f"[CHECKBOX-GATE] {label} 🚨 停低，乜都唔做，等 MUSE 人手處理")
                return False
        
        # 藍色搞掂，繼續第3套

        # 第3套：橙色 — 跟足 CA 完整流程
        unreadable = 0
        for attempt in range(3):  # CA: 連續讀唔到先放行
            c1 = _read_window_pixel(wid, ORANGE_CHECK_X, ORANGE_CHECK_Y)
            if c1 is None:
                unreadable += 1
                if unreadable >= 3:
                    log(sid, f"[CHECKBOX-GATE] {label} 連續 3 次讀唔到像素，放行")
                    break
                time.sleep(0.7)
                continue
            unreadable = 0
            
            if c1.lower() != ORANGE_CHECK_COLOR.lower():
                break  # 唔係橙色，放行
            
            # 係橙色：跟 CA 流程
            log(sid, f"[CHECKBOX-GATE] {label} 橙色出現 ({c1})")
            time.sleep(5)  # CA: 等 5 秒先點
            _xdotool_click(wid, ORANGE_CLICK_X, ORANGE_CLICK_Y)
            log(sid, f"[CHECKBOX-GATE] {label} 已點 ({ORANGE_CLICK_X},{ORANGE_CLICK_Y})，等 5 秒再驗")
            time.sleep(5)
            
            # 點完再驗
            c2 = _read_window_pixel(wid, ORANGE_CHECK_X, ORANGE_CHECK_Y)
            if c2 and c2.lower() != ORANGE_CHECK_COLOR.lower():
                log(sid, f"[CHECKBOX-GATE] {label} 橙色已消失，放行")
                break
            
            # 仲係橙色：CA 會 reload（呢度簡化，返 False 等上層處理）
            log(sid, f"[CHECKBOX-GATE] {label} 橙色仲喺度，要處理")
            return False
        
        # 如果上面 loop 係因為橙色而 return False，已經返咗
        # 嚟到呢度即係冇橙色，繼續藍色檢查
        
        return True
    except Exception as e:
        log(sid, f"[CHECKBOX-GATE] {label} 異常: {e}")
        return True

def _parse_semver_tuple(ver_str):
    """Compatibility spelling used by cross-implementation acceptance suites."""
    return _parse_version_tuple(ver_str)


def ca_checkbox_click(window_id, x, y):
    """CA 式：用 xdotool 做 OS 層級滑鼠點擊（唔係 DOM click）"""
    import subprocess
    env = _x_env()
    try:
        subprocess.run(['xdotool', 'windowraise', str(window_id)], env={**os.environ, **env}, timeout=3, capture_output=True)
        subprocess.run(['xdotool', 'windowactivate', '--sync', str(window_id)], env={**os.environ, **env}, timeout=3, capture_output=True)
        subprocess.run(['xdotool', 'mousemove', '--window', str(window_id), str(x), str(y), 'click', '1'],
                      env={**os.environ, **env}, timeout=5, capture_output=True)
        return True
    except Exception as e:
        return False

def is_page_hung(page, timeout=5000):
    """
    檢測頁面 JS 是否 hang 咗（用戶 2026-10-02 22:25 提出嘅關鍵問題）
    Arena 係動態 JS 頁，有時 renderer 死咗但 DOM 停喺舊狀態呃人
    用 F12 Inspector 級別嘅檢測：心跳＋event loop
    """
    try:
        # 心跳 1: Date.now() 應該要郁
        t1 = page.evaluate("Date.now()")
        time.sleep(0.5)
        t2 = page.evaluate("Date.now()")
        if t2 <= t1:
            return True  # 時間冇郁，JS 已死

        # 心跳 2: requestAnimationFrame 測試 event loop
        raf_ok = page.evaluate("""new Promise((resolve) => {
            let done = false;
            requestAnimationFrame(() => { done = true; resolve(true); });
            setTimeout(() => { if (!done) resolve(false); }, 2000);
        })""")
        if not raf_ok:
            return True  # event loop 唔郁

        return False
    except Exception:
        return True  # evaluate 都 timeout，肯定 hang 咗

def _parse_version_tuple(ver_str):
    parts = []
    for seg in re.split(r"[^0-9]+", str(ver_str or "").strip()):
        if seg.isdigit():
            parts.append(int(seg))
    while len(parts) < 3:
        parts.append(0)
    return tuple(parts[:3])

def _preflight_check_display(sid):
    """應 60023/60025 #3.1：動態檢查 Display（先讀 $DISPLAY，無或失效則掃 /tmp/.X11-unix/ 搵可用 socket；真係無先報錯）。"""
    import stat as _st
    disp = os.environ.get("DISPLAY", "").strip()
    x11_dir = Path(os.environ.get("WATCHER_X11_UNIX_DIR", "/tmp/.X11-unix"))
    if disp:
        m = re.search(r":(\d+)", disp)
        if m:
            sock_p = x11_dir / f"X{m.group(1)}"
            try:
                if sock_p.exists() and _st.S_ISSOCK(sock_p.lstat().st_mode):
                    return True, f"DISPLAY={disp} ({sock_p})"
            except OSError:
                pass
    if x11_dir.is_dir():
        candidates = []
        try:
            for item in sorted(x11_dir.iterdir(), key=lambda p: p.name):
                m = re.fullmatch(r"X(\d+)", item.name)
                if not m:
                    continue
                try:
                    st = item.lstat()
                    if _st.S_ISSOCK(st.st_mode):
                        candidates.append((int(m.group(1)), item))
                except OSError:
                    continue
        except OSError:
            candidates = []
        if candidates:
            candidates.sort(key=lambda x: x[0])
            chosen_num, chosen_sock = candidates[0]
            os.environ["DISPLAY"] = f":{chosen_num}"
            log(sid, f"✅ [PREFLIGHT:DISPLAY] 已由 {x11_dir} 動態偵測並設定 DISPLAY=:{chosen_num} ({chosen_sock})")
            return True, f"DISPLAY=:{chosen_num} ({chosen_sock})"
    return False, f"display-missing($DISPLAY={disp or 'UNSET'}, {x11_dir} 無可用 X socket)"

def _preflight_check_playwright_chromium(sid, min_pw=None, min_cr_rev=None):
    """Prove the installed Playwright package and its actual Chromium executable."""
    requested_pw = str(min_pw or WATCHER_MIN_PLAYWRIGHT_VERSION).strip()
    requested_rev = int(min_cr_rev if min_cr_rev is not None else WATCHER_MIN_CHROMIUM_REVISION)
    req_pw = max(_parse_version_tuple(requested_pw), _parse_version_tuple(WATCHER_MIN_PLAYWRIGHT_VERSION))
    req_rev = max(requested_rev, WATCHER_MIN_CHROMIUM_REVISION)
    try:
        import importlib.metadata as _im
        pw_ver = _im.version("playwright")
    except Exception:
        return False, f"playwright-not-installed(required>={'.'.join(map(str, req_pw))})"
    if _parse_version_tuple(pw_ver) < req_pw:
        return False, f"playwright-version-too-low(installed={pw_ver}, required>={'.'.join(map(str, req_pw))})"
    try:
        from playwright.sync_api import sync_playwright as _sync_playwright
        with _sync_playwright() as _pw:
            executable = Path(_pw.chromium.executable_path)
    except Exception as e:
        return False, f"chromium-executable-unavailable({type(e).__name__})"
    if not executable.is_file():
        return False, f"chromium-executable-missing({executable})"
    revision = None
    for part in executable.parts:
        m_rev = re.search(r"(?:chromium|chromium_headless_shell|chrome)[-_](\d+)", part, re.I)
        if m_rev:
            revision = int(m_rev.group(1))
            break
    if revision is None:
        return False, f"chromium-revision-unprovable({executable})"
    if revision < req_rev:
        return False, f"chromium-revision-too-low(installed={revision}, required>={req_rev}, playwright={pw_ver})"
    return True, f"playwright={pw_ver}(>={'.'.join(map(str, req_pw))}) chromium_rev={revision}(>={req_rev})"

def _preflight_check_server_rotation_json(sid):
    """Require a fresh, non-empty response from the configured rotation server."""
    tail = _resolve_rotation_tail(sid)
    if not tail:
        return True, "non-rotation-seat"
    template = os.environ.get("WATCHER_ROTATION_SERVER_URL_TEMPLATE", "").strip() or ROTATION_SERVER_URL_TEMPLATE
    try:
        url = str(template).format(tail=tail)
    except Exception:
        return False, "rotation-server-template-invalid"
    try:
        req = urllib.request.Request(url, headers={"Cache-Control": "no-cache", "User-Agent": "watcher-preflight/1.0"})
        with urllib.request.urlopen(req, timeout=ROTATION_HTTP_TIMEOUT_S) as resp:
            status = int(getattr(resp, "status", 200))
            raw = json.loads(resp.read().decode("utf-8", errors="strict"))
        if status != 200:
            return False, f"rotation-server-http-{status}"
        entries = _extract_tail_entries_from_raw(sid, raw, url)
        if not entries:
            return False, f"rotation-server-json-empty(tail={tail})"
        return True, f"tail={tail} remote_entries={len(entries)}"
    except urllib.error.HTTPError as e:
        return False, f"rotation-server-http-{getattr(e, 'code', 'error')}"
    except Exception as e:
        return False, f"rotation-server-unavailable(tail={tail}, err={type(e).__name__})"

def _preflight_check_profile_dir(sid, profile_name, seed_root=None):
    """應 60023/60025 #3.5：按傳入 seat 與 profile 參數動態拼出 Profile 目錄並檢查存在性。"""
    prof = str(profile_name or "").strip()
    if not _is_valid_profile_name(prof):
        return False, f"invalid-profile-name({prof!r})"
    seed_dir = _resolve_seed_profile_dir(prof, seed_root=seed_root)
    if seed_dir.is_dir():
        return True, f"profile_dir={seed_dir}"
    alt_dir = Path(PROFILES_DIR) / prof
    if alt_dir.is_dir():
        return True, f"profile_dir={alt_dir}"
    return False, f"profile-dir-missing(seat={sid}, profile={prof}, expected={seed_dir})"

def _profile_tree_size_bytes(root):
    total = 0
    for base, dirs, files in os.walk(root, followlinks=False):
        dirs[:] = [d for d in dirs if not (Path(base) / d).is_symlink()]
        for name in files:
            path = Path(base) / name
            if path.is_symlink():
                continue
            try:
                total += path.stat().st_size
            except OSError:
                pass
    return total


def _nearest_existing_path(path):
    cur = Path(path)
    while not cur.exists() and cur != cur.parent:
        cur = cur.parent
    return cur


def _preflight_check_disk_space(sid, profile_name=None, seed_root=None, ramdisk_root=None):
    """Require room for the full profile copy plus configured reserve."""
    seed_dir = _resolve_seed_profile_dir(profile_name or "default", seed_root=seed_root)
    if not seed_dir.is_dir():
        return False, f"profile-dir-missing-for-disk-check({seed_dir})"
    rroot = _resolve_ramdisk_root(ramdisk_root)
    r_check = _nearest_existing_path(rroot)
    profile_bytes = _profile_tree_size_bytes(seed_dir)
    ram_reserve = WATCHER_MIN_RAMDISK_FREE_MB * 1024 * 1024
    disk_reserve = WATCHER_MIN_DISK_FREE_MB * 1024 * 1024
    try:
        r_free = shutil.disk_usage(r_check).free
        p_free = shutil.disk_usage(seed_dir).free
    except OSError as e:
        return False, f"disk-stat-failed({type(e).__name__})"
    required_ram = profile_bytes + ram_reserve
    if r_free < required_ram:
        return False, f"ramdisk-space-low(required_bytes={required_ram}, free_bytes={r_free})"
    if p_free < disk_reserve:
        return False, f"profile-disk-space-low(required_bytes={disk_reserve}, free_bytes={p_free})"
    return True, f"profile_bytes={profile_bytes} ramdisk_free={r_free} disk_free={p_free}"

def _preflight_check_vpn_and_arena(sid, socks_port=None, profile_dir=None, profiles_dir=None, require_chain=False):
    """Prove VPN reachability and Arena access; never silently probe direct in strict mode."""
    strict_vpn = not (os.environ.get("VPN_FAIL_OPEN", "0") == "1" or VPN_FAIL_OPEN)
    ws_pdir = _resolve_ws_profiles_dir(profiles_dir)
    ws_list = _list_available_ws_profiles(ws_pdir, include_core=True)
    has_ext = bool(profile_dir and _discover_unpacked_extensions(profile_dir))
    socks_ok = False
    if socks_port:
        try:
            with _socket.create_connection(("127.0.0.1", int(socks_port)), timeout=2.5):
                socks_ok = True
        except OSError:
            socks_ok = False
    chain = _get_active_chain_proxy(sid) if sid else None
    chain_ready = bool(
        chain is not None
        and getattr(chain, "listen_port", None)
        and (not hasattr(chain, "is_ready") or chain.is_ready())
    )
    if strict_vpn:
        if require_chain and not chain_ready:
            return False, "vpn-chain-not-ready"
        if not require_chain and not socks_ok:
            return False, f"vpn-socks-unreachable(port={socks_port}, ws_pool={len(ws_list)}, has_ext={has_ext})"
    if require_chain and chain_ready:
        proxy_url = f"http://127.0.0.1:{chain.listen_port}"
    elif socks_ok and socks_port:
        proxy_url = f"socks5h://127.0.0.1:{int(socks_port)}"
    else:
        proxy_url = None
    if strict_vpn and not proxy_url:
        return False, "vpn-proxy-unavailable"
    post_ip = None
    if strict_vpn and require_chain:
        baseline_ip, baseline_src, baseline_err = _resolve_pre_vpn_baseline_ip(socks_port=socks_port, sid=sid)
        if not baseline_ip:
            return False, f"vpn-{baseline_src}({baseline_err or '-'})"
        post_ip = _probe_chain_proxy_exit_ip_host_side(chain.listen_port, timeout=6.0)
        if not post_ip:
            return False, "vpn-post-extension-ip-unavailable"
        if not _is_valid_public_exit_ip(post_ip):
            return False, "vpn-exit-private-ip"
        if post_ip == baseline_ip:
            return False, f"vpn-ip-unchanged(source={baseline_src})"
        if _is_ip_blacklisted(post_ip):
            _demote_chain_upstream_host(chain)
            return False, "vpn-exit-blacklisted"
    arena_url = os.environ.get("ARENA_PREFLIGHT_URL", "https://arena.ai/agent").strip() or "https://arena.ai/agent"
    cmd = ["curl", "-sS", "-i", "--max-time", "8"]
    if proxy_url:
        cmd += ["-x", proxy_url]
    else:
        cmd += ["--noproxy", "*"]
    cmd.append(arena_url)
    try:
        r = subprocess.run(
            cmd, capture_output=True, text=True, timeout=10,
            env=_clean_proxy_env(force_direct=not bool(proxy_url)),
        )
    except Exception as e:
        return False, f"arena-probe-error({type(e).__name__})"
    raw = r.stdout or ""
    if r.returncode != 0 or not raw.strip():
        return False, f"arena-unreachable(proxy={proxy_url or 'direct'}, rc={r.returncode})"
    status_codes = [int(mt.group(1)) for mt in re.finditer(r"^HTTP/[0-9.]+\s+(\d{3})", raw, re.M)]
    code = status_codes[-1] if status_codes else 0
    if code == 403:
        if post_ip:
            _record_blacklisted_ip(
                post_ip, reason="preflight_arena_403", sid=sid, port=socks_port,
                upstream_host=(chain.last_ok_host if chain and getattr(chain, "last_ok_host", None) else None),
                url=arena_url,
            )
        log(sid, f"❌ [PREFLIGHT:ARENA-403] IP 俾 Cloudflare 擋 (HTTP 403, proxy={proxy_url or 'direct'})")
        return False, f"IP 俾 Cloudflare 擋 (HTTP 403, proxy={proxy_url or 'direct'})"
    if code < 200 or code >= 400:
        return False, f"arena-unexpected-http-{code or 'unknown'}"
    return True, f"arena_http={code} proxy={proxy_url or 'direct'} socks_ok={socks_ok} ws_pool={len(ws_list)}"

def run_watcher_preflight(sid, cfg=None, socks_port=None, seed_root=None, ramdisk_root=None, profiles_dir=None, include_network=True, require_chain=False, profile_dir=None):
    """Dynamic startup preflight.  Static gates run before staging; network gates can run after chain preparation."""
    s_key = str(sid or "WATCHER").upper()
    if cfg is None:
        seats = load_seats()
        cfg = seats.get(s_key) or {}
    if socks_port is None and cfg.get("vpn"):
        vpn_ports = load_vpn_ports()
        if cfg["vpn"] in vpn_ports:
            socks_port = vpn_ports[cfg["vpn"]]
    prof_name = cfg.get("profile") or "default"
    checks = [
        ("server_tunnel_forwards", lambda: _preflight_check_server_tunnel_forwards(s_key)),
        ("server_direct", lambda: _preflight_check_server_direct_carrier(s_key)),
        ("display", lambda: _preflight_check_display(s_key)),
        ("playwright_chromium", lambda: _preflight_check_playwright_chromium(s_key)),
        ("server_rotation_json", lambda: _preflight_check_server_rotation_json(s_key)),
        ("profile_dir", lambda: _preflight_check_profile_dir(s_key, prof_name, seed_root=seed_root)),
        ("disk_space", lambda: _preflight_check_disk_space(s_key, prof_name, seed_root=seed_root, ramdisk_root=ramdisk_root)),
    ]
    if include_network:
        checks.append(("vpn_and_arena", lambda: _preflight_check_vpn_and_arena(
            s_key, socks_port=socks_port, profile_dir=profile_dir,
            profiles_dir=profiles_dir, require_chain=require_chain,
        )))
    results = {}
    for name, fn in checks:
        ok, detail = fn()
        results[name] = {"ok": bool(ok), "detail": str(detail)}
        if not ok:
            log(s_key, f"🛑 [PREFLIGHT:FAIL] {name} 檢查未過：{detail}（停低報錯，唔盲推）")
            return False, {"ok": False, "failed_check": name, "reason": f"{name}:{detail}", "checks": results}
    log(s_key, f"✅ [PREFLIGHT:PASS] checks={','.join(results)}")
    return True, {"ok": True, "failed_check": None, "reason": None, "checks": results}

def run_watcher(sid, once=False):
    try:
        from playwright.sync_api import sync_playwright
    except ImportError:
        log(sid, "ERROR: playwright 未安裝")
        return 1

    seats = load_seats()
    vpn_ports = load_vpn_ports()

    if sid not in seats:
        log(sid, f"ERROR: 席位 {sid} 不在 seats.conf")
        _rot_council_write_next_turn(sid)
        return 1

    cfg = seats[sid]
    if cfg["status"] != "active":
        log(sid, f"席位狀態為 {cfg['status']}，跳過")
        _rot_council_write_next_turn(sid)
        return 0

    if cfg["vpn"] not in vpn_ports:
        log(sid, f"ERROR: VPN {cfg['vpn']} 不在 vpn-proxies.conf")
        _rot_council_write_next_turn(sid)
        return 1

    port = _select_non_blacklisted_socks_port(sid, vpn_ports[cfg["vpn"]], vpn_ports=vpn_ports)

    _fallback_seat_url = cfg["url"]
    _fallback_seat_profile = cfg["profile"]
    _active_slot_label = sid
    if _resolve_rotation_tail(sid):
        _rot_init = load_url_rotation(sid)
        # 應 Owner 60606 #4 & 59758：若當前 URL 或當前 profile 今日已觸發 DAILY_LIMIT 收工，啟動前檢查是否尚有未收工 profile；若當日已收工則直接寫 turn 交棒下一席
        if (_rot_init.get("url") and _is_url_daily_limited_today(sid, _rot_init["url"])) or (
            _rot_init.get("profile") and _is_profile_daily_limited_today(sid, _rot_init["profile"])
        ):
            _rot_init = _with_rotation_flock(rotation_advance_on_daily_limit, sid, _rot_init.get("profile"), "startup_already_daily_limited")
            if _rot_init.get("all_profiles_exhausted") or _is_profile_daily_limited_today(sid, _rot_init.get("profile")):
                log(sid, f"🚨 [DAILY-LIMIT:ALL-PROFILES-DONE] {sid} 今日已撞 DAILY_LIMIT 當日收工，唔開 browser 直接寫 turn 交棒下一席")
                _rot_council_write_next_turn(sid)
                return 0
        if _rot_init.get("url"):
            cfg["url"] = _rot_init["url"]
        if _rot_init.get("profile") and _is_valid_profile_name(_rot_init["profile"]):
            cfg["profile"] = _rot_init["profile"]
        if _rot_init.get("label"):
            _active_slot_label = _rot_init["label"]
    elif _is_profile_daily_limited_today(sid, cfg.get("profile")):
        log(sid, f"🚨 [DAILY-LIMIT:SEAT-DONE-TODAY] {sid} (profile={cfg.get('profile')}) 今日已撞 DAILY_LIMIT 當日收工，直接寫 turn 交棒下一席")
        _rot_council_write_next_turn(sid)
        return 0

    # 應 60023/60025 #3：mandatory static preflight；network gate waits for the prepared current chain.
    _pf_ok, _pf_info = run_watcher_preflight(sid, cfg=cfg, socks_port=port, include_network=False)
    if not _pf_ok:
        _rot_council_write_next_turn(sid)
        return 1
    _reset_session_push_state(sid, url=cfg.get("url"))

    # 應 59641 #3/#4：種／運行分離——由 persistent workshop 種 CP 當前單一 profile 去 ramdisk (tmpfs)
    try:
        profile_dir = _stage_seed_profile_to_ramdisk(sid, cfg["profile"])
    except Exception as e:
        log(sid, f"❌ [RAMDISK:STAGE-FAIL] 無法將種 {cfg['profile']} CP 去 ramdisk：{e}")
        _cleanup_ramdisk_profile(sid)
        _rot_council_write_next_turn(sid)
        return 1

    _active_ws_ext = _select_and_apply_startup_ws_extension(sid, profile_dir, _resolve_ws_profiles_dir())
    _sanitize_profile_zoom_prefs(profile_dir, sid)
    log(sid, f"啟動 watcher (ramdisk 單一 profile): profile={cfg['profile']} ({profile_dir}), ws_ext={_active_ws_ext}, vpn={cfg['vpn']}:{port}, url={cfg['url']}")

    with sync_playwright() as p:
        browser = None
        page = None
        vpn_ext_activated = False
        _vpn_boot_fail_count = 0
        _vpn_strict_limit = _vpn_strict_retry_limit()
        _force_rotate_upstream = False
        if os.environ.get("VPN_FAIL_OPEN") == "1" or VPN_FAIL_OPEN:
            log(sid, f"ℹ️ [VPN-LATCH-FIX] 偵測到 VPN_FAIL_OPEN=1；按 Owner 59824/59825 已停用短路，仍會嚴格驗證 WS 出口（pool_retry_limit={_vpn_strict_limit}）")
        try:
            _boot_rt = _prepare_seat_vpn_runtime(p, sid, profile_dir, port)
            if not _boot_rt.get("ok"):
                log(sid, f"❌ [PREFLIGHT:FAIL] vpn-runtime:{_boot_rt.get('reason')}；push browser 未開，立即停機交棒")
                return 1
            _net_ok, _net_detail = _preflight_check_vpn_and_arena(
                sid, socks_port=port, profile_dir=profile_dir,
                profiles_dir=_resolve_ws_profiles_dir(), require_chain=True,
            )
            if not _net_ok:
                log(sid, f"❌ [PREFLIGHT:FAIL] vpn_and_arena:{_net_detail}；push browser 未開，立即停機交棒")
                return 1
            if _boot_rt.get("ok"):
                browser = p.chromium.launch_persistent_context(
                    str(profile_dir),
                    headless=False,
                    device_scale_factor=1,
                    proxy={"server": _boot_rt["proxy_server"]},
                    args=_build_chromium_launch_args(profile_dir, load_extensions=_boot_rt["load_extensions"]),
                    ignore_default_args=["--enable-automation"],
                    viewport={'width': 1400, 'height': 900},
                )
                page = browser.new_page() if not browser.pages else browser.pages[0]
            first_load = True
            cycle_count = 0  # 計 cycle 數，每 120 個 cycle（約 1 小時）做一次登入檢查
            _consec_err_result = None  # 議會 patch：連續同一錯誤追蹤（結果字串）
            _consec_err_count = 0  # 議會 patch：連續同一錯誤次數

            while True:
                try:
                    # Owner 60495：每輪 cycle 第一件事硬檢查 7 條 VM→server tunnel forwards；全數斷線即明示頭號死因並 fail-closed，絕不行 VM-direct bridge。
                    _forward_ok, _forward_detail = _check_server_tunnel_forward_listeners(sid, phase="cycle")
                    if not _forward_ok:
                        if once:
                            break
                        time.sleep(CHECK_INTERVAL)
                        continue

                    # 檢查 browser / page 仲生唔生（應 A93/58517 ② & A2/58518：補齊 page is None 保護，防 AttributeError crash-loop）
                    if browser is None or page is None:
                        if browser is not None:
                            try:
                                browser.close()
                            except Exception:
                                pass
                        log(sid, "Browser 或 page 已死／切換失敗，重開中...")
                        _sanitize_profile_zoom_prefs(profile_dir, sid)
                        _reopen_rt = _prepare_seat_vpn_runtime(p, sid, profile_dir, port, rotate_upstream=_force_rotate_upstream)
                        _force_rotate_upstream = False
                        if not _reopen_rt.get("ok"):
                            _vpn_boot_fail_count += 1
                            if _vpn_boot_fail_count >= _vpn_strict_limit:
                                log(sid, f"🛑 [VPN-LATCH-FIX:WS-POOL-EXHAUSTED] Stage A/B 連續 {_vpn_boot_fail_count}/{_vpn_strict_limit} 次失敗 ({_reopen_rt.get('reason')})；禁止 direct-SOCKS fallback，clean stop 並交棒")
                                browser = None
                                page = None
                                vpn_ext_activated = False
                                break
                            try:
                                _switch_ws_extension_for_seat(sid, profile_dir, _resolve_ws_profiles_dir())
                                _force_rotate_upstream = True
                            except Exception:
                                pass
                            log(sid, f"❌ [VPN-CHAIN:REOPEN] 重開時 Stage A/B 失敗 ({_reopen_rt.get('reason')})，已切換下一個 ws-*／upstream（retry={_vpn_boot_fail_count}/{_vpn_strict_limit}）")
                            browser = None
                            page = None
                            vpn_ext_activated = False
                            if once:
                                break
                            time.sleep(CHECK_INTERVAL)
                            continue
                        browser = p.chromium.launch_persistent_context(
                            str(profile_dir), headless=False, device_scale_factor=1,
                            proxy={"server": _reopen_rt["proxy_server"]},
                            args=_build_chromium_launch_args(profile_dir, load_extensions=_reopen_rt["load_extensions"]),
                            ignore_default_args=["--enable-automation"],
                            viewport={'width': 1400, 'height': 900},
                        )
                        page = browser.new_page() if not browser.pages else browser.pages[0]
                        enforce_window_geometry(sid, stage="REOPEN", page=page)
                        first_load = True
                        vpn_ext_activated = False

                    if not vpn_ext_activated:
                        # 應 Owner 59824/59825：任何 VPN latch 前必須核實 WS 出口；失敗輪換完整 ws-*／upstream pool，
                        # pool 耗盡後 clean stop/交棒，禁止 VPN_FAIL_OPEN／no-extension／direct-SOCKS 靜默放行。
                        _boot_vpn_ok = _activate_vpn_extension_once(
                            browser, page, sid, profile_dir, require_on=True
                        )
                        if not _boot_vpn_ok:
                            _vpn_boot_fail_count += 1
                            if _vpn_boot_fail_count >= _vpn_strict_limit:
                                log(sid, f"🛑 [VPN-LATCH-FIX:WS-POOL-EXHAUSTED] WS 出口驗證連續 {_vpn_boot_fail_count}/{_vpn_strict_limit} 次未過；禁止 direct-SOCKS fallback，clean stop 並交棒")
                                try:
                                    browser.close()
                                except Exception:
                                    pass
                                browser = None
                                page = None
                                vpn_ext_activated = False
                                break
                            try:
                                _sw_ws = _switch_ws_extension_for_seat(sid, profile_dir, _resolve_ws_profiles_dir())
                                _force_rotate_upstream = True
                            except Exception:
                                _sw_ws = None
                            log(sid, f"❌ [VPN-LATCH-FIX] WS 出口驗證失敗 (retry={_vpn_boot_fail_count}/{_vpn_strict_limit}, next_ws={_sw_ws})；唔上 latch，輪換 ws-*／upstream 後再試")
                            try:
                                browser.close()
                            except Exception:
                                pass
                            browser = None
                            page = None
                            first_load = True
                            time.sleep(CHECK_INTERVAL)
                            continue
                        _vpn_boot_fail_count = 0
                        vpn_ext_activated = True

                    # 首次載入或需要時先 goto，之後直接 check DOM（唔好每 30 秒 reload）
                    if first_load:
                        # 先去 https://arena.ai/agent 登入，登入咗先再去指定 URL
                        # 搵到email=登入成功；搵唔到email但搵到login=要登入；兩個都搵唔到=有問題（page未load/阻塞）
                        _agent_nav_resp = page.goto("https://arena.ai/agent", wait_until="domcontentloaded", timeout=60000)
                        _dismiss_cookie_consent(page, sid)
                        # v0.93: URL 變動後過 checkbox 關（跟 CA URL-CHANGE 模式）
                        ca_checkbox_gate(page, sid, "URL-CHANGE")
                        _blk_a, _blk_ip_a, _blk_rsn_a = _check_page_arena_ip_blocked(page, _agent_nav_resp, sid=sid, port=port)
                        if _blk_a:
                            try:
                                _sw_ws = _switch_ws_extension_for_seat(sid, profile_dir, _resolve_ws_profiles_dir())
                            except Exception:
                                _sw_ws = None
                            _force_rotate_upstream = True
                            log(sid, f"🚫 [IP-BLACKLIST:403-ROTATE] arena.ai/agent 偵測到出口 ({_mask_ip_for_log(_blk_ip_a)}) 被 403 封鎖 ({_blk_rsn_a})，已寫入黑名單並切換 next_ws={_sw_ws} 重開 browser")
                            try:
                                browser.close()
                            except Exception:
                                pass
                            browser = None
                            page = None
                            vpn_ext_activated = False
                            first_load = True
                            continue
                        log(sid, "先去 arena.ai/agent 登入頁，120s 內搵 slide menu 制（搵到=loaded）...")
                        wait_for_sidebar_button(page, sid)
                        _dismiss_cookie_consent(page, sid)
                        # startup 登入檢查：等登入指標（電郵/Log In掣）出現先行
                        wait_for_login_indicators(page, sid)
                        login_state = check_login_state(page, sid, cfg["account"], browser)
                        log(sid, f"Startup 登入檢查（agent 頁）：{login_state}")
                        if login_state == 'session_cleared_retry':
                            log(sid, "Arena session missing 已清 arena，重開 browser 再試")
                            try:
                                browser.close()
                            except:
                                pass
                            browser = None
                            continue
                        # 淨係搵到 email（登入成功）先至去指定 URL；其他狀態唔去，留返 first_load=True 重試
                        # 雙重確認：用 sidebar 明確 verify 一次 email，冇就唔去 URL
                        if login_state == 'logged_in':
                            verified_email = verify_email_via_sidebar(page, sid)
                            if not verified_email:
                                log(sid, "⚠️ sidebar 二次確認搵唔到 email → 唔去指定 URL，視為登入失敗並轉下一個 profile")
                                login_state = 'logged_out'
                            else:
                                log(sid, f"已登入（sidebar 確認有email），去指定 URL：{cfg['url']}")
                                if _resolve_rotation_tail(sid):
                                    _rot_cur = load_url_rotation(sid)
                                    if _rot_cur.get("url"):
                                        cfg["url"] = _rot_cur["url"]
                                    if _rot_cur.get("label"):
                                        _active_slot_label = _rot_cur["label"]
                                _target_nav_resp = page.goto(cfg["url"], wait_until="domcontentloaded", timeout=60000)
                                _dismiss_cookie_consent(page, sid)
                                enforce_window_geometry(sid, stage="TARGET-URL", page=page)
                                ensure_zoom_100(page, sid, "TARGET-URL", profile_dir)
                                # v0.93: URL 變動後過 checkbox 關（跟 CA URL-CHANGE 模式）
                                ca_checkbox_gate(page, sid, "URL-CHANGE")
                                _blk_t, _blk_ip_t, _blk_rsn_t = _check_page_arena_ip_blocked(page, _target_nav_resp, sid=sid, port=port)
                                if _blk_t:
                                    try:
                                        _sw_ws = _switch_ws_extension_for_seat(sid, profile_dir, _resolve_ws_profiles_dir())
                                    except Exception:
                                        _sw_ws = None
                                    _force_rotate_upstream = True
                                    log(sid, f"🚫 [IP-BLACKLIST:403-ROTATE] 目標 URL 偵測到出口 ({_mask_ip_for_log(_blk_ip_t)}) 被 403 封鎖 ({_blk_rsn_t})，已寫入黑名單並切換 next_ws={_sw_ws} 重開 browser")
                                    try:
                                        browser.close()
                                    except Exception:
                                        pass
                                    browser = None
                                    page = None
                                    vpn_ext_activated = False
                                    first_load = True
                                    continue
                                log(sid, "指定 URL 載入中，120s 內搵 slide menu 制...")
                                wait_for_sidebar_button(page, sid)
                                _dismiss_cookie_consent(page, sid)
                                _reset_session_push_state(sid, url=cfg.get("url"))
                                first_load = False
                        if login_state in ('logged_out', 'login_failed'):
                            # 應 59654 修訂：自動補密碼／登入失敗時唔好停、唔好 retry loop；上報（profile＋原因＋時間）後直接 pass 去下一個 profile 繼續推
                            _s_key = str(sid or "").strip().upper()
                            _pw_reason = _LAST_GOOGLE_PW_FATAL.pop(_s_key, None)
                            if not _pw_reason:
                                _pw_reason = f"startup_{login_state}"
                                _report_google_login_failure_to_muse(sid, cfg.get("profile"), _pw_reason)
                            if _resolve_rotation_tail(sid):
                                _rot_np = _with_rotation_flock(rotation_advance_to_next_profile, sid, cfg.get("profile"), _pw_reason)
                                log(sid, f"⏭️ [GOOGLE-PW:HANDOFF] {sid} 已上報登入失敗 profile ({_rot_np.get('skipped_profile')}: {_pw_reason}) 並推進至下一個 profile={_rot_np.get('profile')} 供下輪使用，本輪即刻交棒下一席")
                            break
                        elif login_state not in ('logged_in',):  # unknown
                            log(sid, "⚠️ 搵唔到email+搵唔到login=有問題（page未load/阻塞），唔去指定URL，重試")
                    else:
                        # 非首次：唔 goto，直接檢查當前 DOM
                        pass

                    # 先檢查頁面係咪 hang 咗（唔好俾假 DOM 呃）
                    # 注意：首次載入後等夠耐先 check，唔好誤判
                    # owner 2026-10-05 14:50-14:51 下令：is_page_hung 只准用喺 Arena URL
                    # （指定 URL＋agent 頁＋Arena 主頁），其他 URL（Google 登入等）唔好用，
                    # 會誤判閂 browser
                    _cur_url = page.url if hasattr(page, 'url') else ''
                    # 應 59651 #8 & 59654 修訂：運行中途若 Google session 過期撞到 Google 登入密碼頁（input[type="password"]），
                    # 自動由 `.google-pw`（0600）補密碼 → 撳 Next → 等登入完成 → 返指定 URL 繼續原流程；
                    # 若自動補密碼失敗（密碼錯／彈驗證碼／其他異常）：唔好停、唔好 retry loop，上報（profile＋原因＋時間）後直接 pass 去下一個 profile 繼續推
                    if "accounts.google.com" in _cur_url or _is_google_password_prompt_visible(page):
                        log(sid, "🔐 [GOOGLE-PW] 運行中偵測到 Google 登入／密碼頁（Google session 已失效）→ 自動補密碼登入並繼續原流程")
                        _mid_login = handle_arena_login_flow(page, sid, browser)
                        if _mid_login == "SESSION_CLEARED":
                            log(sid, "Arena session missing 已清 arena，重開 browser 再試")
                            try:
                                browser.close()
                            except Exception:
                                pass
                            browser = None
                            first_load = True
                            continue
                        if not _mid_login:
                            _s_key = str(sid or "").strip().upper()
                            _pw_reason = _LAST_GOOGLE_PW_FATAL.pop(_s_key, None)
                            if not _pw_reason:
                                _pw_reason = "mid_run_google_login_failed"
                                _report_google_login_failure_to_muse(sid, cfg.get("profile"), _pw_reason)
                            if _resolve_rotation_tail(sid):
                                _rot_np = _with_rotation_flock(rotation_advance_to_next_profile, sid, cfg.get("profile"), _pw_reason)
                                log(sid, f"⏭️ [GOOGLE-PW:HANDOFF] {sid} 運行中補密碼失敗已上報 ({_rot_np.get('skipped_profile')}: {_pw_reason}) 並推進至下一個 profile={_rot_np.get('profile')} 供下輪使用，本輪即刻交棒下一席")
                            break
                        log(sid, f"自動補密碼登入完成，返回指定 URL 繼續原流程：{cfg['url']}")
                        page.goto(cfg["url"], wait_until="domcontentloaded", timeout=60000)
                        _dismiss_cookie_consent(page, sid)
                        enforce_window_geometry(sid, stage="TARGET-URL", page=page)
                        ensure_zoom_100(page, sid, "TARGET-URL", profile_dir)
                        ca_checkbox_gate(page, sid, "URL-CHANGE")
                        wait_for_sidebar_button(page, sid)
                        _dismiss_cookie_consent(page, sid)
                        _cur_url = page.url if hasattr(page, 'url') else ''
                    if "arena.ai" in _cur_url and is_page_hung(page):
                        log(sid, "⚠️ 頁面 JS hang 咗（DOM 可能係假狀態），reload 緊...")
                        page.reload(wait_until="domcontentloaded", timeout=60000)
                        time.sleep(3)
                        # reload 後再 check 一次，如果仲 hang 就當 browser 死重開
                        if is_page_hung(page):
                            log(sid, "Reload 後仲 hang，懷疑 renderer 死咗，重開 browser")
                            try:
                                browser.close()
                            except:
                                pass
                            browser = None
                            continue
                        else:
                            log(sid, "Reload 後恢復正常")

                    # 檢查 DOM 狀態
                    _zok_c, _zmeas_c = ensure_zoom_100(page, sid, "CYCLE", profile_dir)
                    if not _zok_c:
                        log(sid, f"🚨 [CAUSAL-NOTE:Z2-HOLD] 本 cycle 因 Zoom 校唔實 ({_zmeas_c}) 跳過所有點擊；即刻收 Browser -> 清磁碟 Preferences -> 下輪重開")
                        try:
                            browser.close()
                        except Exception:
                            pass
                        browser = None
                        _sanitize_profile_zoom_prefs(profile_dir, sid)
                        if once:
                            break
                        time.sleep(CHECK_INTERVAL)
                        continue
                    content = page.content()

                    # 心跳記錄（防假成功）：每次 cycle 記錄 page 狀態
                    heartbeat = get_page_heartbeat(page, sid)
                    log(sid, f"心跳: {heartbeat}")

                    # 強制 window 尺寸（2026-10-05 19:49 HKT owner 下令：硬性規定）
                    # 唔係 1408x900 就唔准運行，跳過呢個 cycle
                    if not enforce_window_geometry(sid, page=page):
                        log(sid, "🚨 尺寸唔啱，呢個 cycle 跳過，等 30 秒再試")
                        time.sleep(CHECK_INTERVAL)
                        continue

                    # v3：一個 cycle 做晒（do_send_cycle 處理：Stop掣→skip；Keep working→撳+5s+reload；send；10s+reload驗證）
                    result = do_send_cycle(page, sid)
                    log(sid, f"Cycle 結果: {result}")

                    # 應 59672 & 59680：每當成功推完一個 SLOT，即刻寫低 {state_dir}/<slot>-last-profile.txt（純文字 profile ID）並 POST :18888/report 更新 updated_hkt heartbeat
                    if result in ("SUCCESS", "SUCCESS_NEXT_CYCLE", "HOLD_RESOLVED"):
                        _record_slot_last_profile(sid, cfg.get("profile"), slot_label=_active_slot_label, url=cfg.get("url"))

                    # 應 Owner 60606 #4（DAILY_LIMIT 語義不變跟 profile：撞限額嗰席當日收工，照樣交棒下一席）：
                    # 撞到 DAILY_LIMIT 時標記該 profile 當日收工（並推進 rotation 狀態供未來輪次用），嚴禁喺同一輪重開 Chrome 繼續推，即刻 break 閂 browser 寫 turn 交棒下一席！
                    if result == "DAILY_LIMIT" or is_daily_limit_error(page, sid):
                        _dl_reason = _consume_daily_limit_hit(sid) or "item2_page_error_banner"
                        _reset_response_ended_tracker(sid)
                        _mark_profile_daily_limit_today(sid, cfg.get("profile"), reason=_dl_reason)
                        if cfg.get("url"):
                            _mark_url_daily_limit_today(sid, cfg.get("url"), reason=_dl_reason)
                        if _resolve_rotation_tail(sid):
                            _rot_dl = _with_rotation_flock(rotation_advance_on_daily_limit, sid, cfg.get("profile"), _dl_reason)
                            if _rot_dl.get("label"):
                                _active_slot_label = _rot_dl["label"]
                        log(sid, f"🚨 [DAILY-LIMIT:HANDOFF] {sid} (profile={cfg.get('profile')}) 觸發 DAILY_LIMIT (reason={_dl_reason}) 當日收工 → 應 60606 #4 即刻閂 browser、清 ramdisk 並寫 turn 照樣交棒下一席")
                        break

                    # 檢測對話超長 → 報 Muse 並推進 URL 狀態後即刻交棒下一席（應 60606 #1/#3 禁止同輪重開連推）
                    if is_conversation_too_long(page, sid):
                        _dead_url = cfg.get("url")
                        _dead_profile = cfg.get("profile")
                        _reset_response_ended_tracker(sid)
                        log(sid, f"🚨 [TOO-LONG] 對話超長確認：呢個 AI 已完結，URL 永久退役（{_dead_url}）→ 同步報 Muse 並推進 URL 後交棒下一席")
                        _report_conversation_too_long_to_muse(sid, _dead_url, dead_profile=_dead_profile)
                        if _resolve_rotation_tail(sid):
                            _with_rotation_flock(rotation_advance, sid)
                        break

                    # 應 Owner 60606 #2：輪到開某席嗰陣，如果嗰席仲喺 relay 生成緊（上一推未完），唔等、唔加推，直接跳下一席
                    if result == "SKIP_GENERATING":
                        log(sid, f"⏭️ [TURN-SKIP:GENERATING] {sid} 仲喺 relay 生成緊（上一推未完）→ 應 60606 #2 唔等、唔加推，即刻閂 browser、清 ramdisk profile ({cfg.get('profile')}) 並寫 turn 跳下一席")
                        break

                    # 應 Owner 60606 #1 & #3：一席一輪只推一次（SUCCESS / SUCCESS_NEXT_CYCLE / HOLD_RESOLVED 均代表本輪已完成一次推送），嚴禁連環推好多 cycle 霸住成輪，即刻寫 turn 交棒下一席
                    if result in ("SUCCESS", "SUCCESS_NEXT_CYCLE", "HOLD_RESOLVED"):
                        if WATCHER_ADVANCE_URL_ON_TURN_DONE and _resolve_rotation_tail(sid):
                            _with_rotation_flock(rotation_advance, sid)
                        log(sid, f"✅ [TURN-DONE:ONE-PUSH] {sid} 本輪已完成一次推送 (result={result}) → 應 60606 #1/#3 即刻閂 browser、清 ramdisk profile ({cfg.get('profile')}) 並寫 turn 交棒下一席")
                        break

                    if result in ("NO_INPUT", "NO_INPUT_2", "KW_CLICK_ERROR", "UNCONFIRMED", "URL_GUARD_ABORT", "CHECKBOX_BLOCKED"):
                        log(sid, f"⚠️ [TURN-ABORT] {sid} 本輪推 cycle 未能完成 (result={result}) → 應 60606 #3 唔霸輪，即刻閂 browser 並寫 turn 交棒下一席")
                        break

                    cycle_count += 1
                    if once or WATCHER_STRICT_ONE_PUSH_PER_TURN or cycle_count >= MAX_PUSH_CYCLES_PER_TURN:
                        log(sid, f"✅ [TURN-DONE] {sid} 單輪上限已達 (cycle_count={cycle_count}, result={result}) → 寫 turn 交棒下一席")
                        break

                except Exception as e:
                    log(sid, f"檢查出錯: {e}，{CHECK_INTERVAL}秒後重試")
                    # 嘗試關閉壞掉的 browser，下輪重開
                    try:
                        if browser:
                            browser.close()
                    except:
                        pass
                    browser = None
                    if once:
                        break
                    time.sleep(CHECK_INTERVAL)

        finally:
            if browser:
                try:
                    browser.close()
                except:
                    pass
            _stop_seat_chain_proxy(sid)
            # 應 59641 #3/#4：閂 browser 後即刻清走 ramdisk 嗰個 profile，確保 tmpfs 唔殘留
            _cleanup_ramdisk_profile(sid, profile_dir)
            # 應 59641 #4/#7：退出前寫 rotation-turn.txt（唔理跑完／自停／正常退出／例外，內建 coordinator 照 turn 檔輪下一席）
            _rot_council_write_next_turn(sid)

    return 0

def run_coordinator(initial_sid=None, once=False, max_turns=None):
    """應 59641 #1/#4/#7：內建 Coordinator turn loop（取代外部 rotation-coordinator.sh）。
    單一 Python 程序內建讀取 rotation-turn.txt＋rotation-seats.txt，跳過 rotation-paused.txt，
    全程只准開一個 headed browser、ramdisk 全程只放當前嗰一個 profile。"""
    if initial_sid:
        init_s = str(initial_sid).strip().upper()
        tp = _rot_council_turn_path()
        if not tp.is_file():
            try:
                tp.parent.mkdir(parents=True, exist_ok=True)
                tp.write_text(init_s + "\n", encoding="utf-8")
            except Exception:
                pass
    turns_done = 0
    last_rc = 0
    while True:
        seats = _rot_council_load_seats(default_fallback=True, hint_sid=initial_sid)
        if initial_sid and str(initial_sid).strip().upper() not in seats:
            seats.insert(0, str(initial_sid).strip().upper())
        paused = set(_rot_council_get_paused())
        turn_sid = _rot_council_read_turn(seats, hint_sid=initial_sid)
        if not turn_sid and seats:
            turn_sid = seats[0]
        if turn_sid in paused:
            log("COORD", f"⏸️ {turn_sid} 已暫停（rotation-paused.txt），跳過")
            nxt = _rot_council_next_seat(turn_sid, seats=seats, paused=paused)
            if not nxt:
                log("COORD", f"⏸️ 全部席位已暫停，瞓 {COORD_ALL_PAUSED_SLEEP_S} 秒")
                if once or (max_turns is not None and turns_done >= max_turns):
                    return 0
                time.sleep(COORD_ALL_PAUSED_SLEEP_S)
                continue
            try:
                tp = _rot_council_turn_path()
                tp.parent.mkdir(parents=True, exist_ok=True)
                tp.write_text(nxt + "\n", encoding="utf-8")
            except Exception:
                pass
            if once and max_turns is not None and turns_done >= max_turns:
                return 0
            continue
        log("COORD", f"▶️ 開 {turn_sid}（單一 Python 內建 coordinator｜一席一輪只推一次｜一次只開一個 headed browser｜ramdisk 單一 profile）")
        last_rc = run_watcher(turn_sid, once=once)
        turns_done += 1
        after_turn = _rot_council_read_turn(seats, hint_sid=turn_sid)
        if after_turn == turn_sid:
            nxt_fallback = _rot_council_next_seat(turn_sid, seats=seats, paused=set(_rot_council_get_paused()))
            if nxt_fallback and nxt_fallback != turn_sid:
                _rot_council_write_next_turn(turn_sid, seats=seats)
        log("COORD", f"⏹️ {turn_sid} 本輪結束 (rc={last_rc}, turns_done={turns_done})")
        if once or (max_turns is not None and turns_done >= max_turns):
            return last_rc
        time.sleep(COORD_TURN_PAUSE_S)

if __name__ == "__main__":
    args = [a for a in sys.argv[1:] if not a.startswith("-")]
    flags = {a for a in sys.argv[1:] if a.startswith("-")}
    once = "--once" in flags
    single_seat = "--single-seat" in flags or os.environ.get("WATCHER_SINGLE_SEAT_ONLY", "0") == "1"
    coord_flag = "--coordinator" in flags or (len(args) == 0) or (args[0].upper() in ("COORD", "COORDINATOR", "ALL"))
    if coord_flag:
        init_seat = args[0].upper() if (args and args[0].upper() not in ("COORD", "COORDINATOR", "ALL")) else None
        sys.exit(run_coordinator(initial_sid=init_seat, once=once))
    sid = args[0].upper()
    if "--preflight" in flags or "--preflight-only" in flags:
        _pf_ok, _ = run_watcher_preflight(sid)
        sys.exit(0 if _pf_ok else 1)
    if single_seat or once:
        sys.exit(run_watcher(sid, once=once))
    sys.exit(run_coordinator(initial_sid=sid, once=False))
