#!/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                    (62,239B | 1,379L | md5=797357a7755baa381bee249121e05b3d | sha256=1b89afc9655d19a0b73647ebc8dae36fd8cf442a28196694f8e1c968537f7251 | measured_at=2026-10-06T11:36: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  # 秒

# 議會 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", "DAILY_LIMIT")

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

# 議會架構定案 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")
WATCHER_EXIT_TURN_ON_DONE = os.environ.get("WATCHER_EXIT_TURN_ON_DONE", "1") != "0"
WATCHER_EXIT_TURN_ON_SKIP_GENERATING = os.environ.get("WATCHER_EXIT_TURN_ON_SKIP_GENERATING", "1") != "0"
WATCHER_ADVANCE_URL_ON_TURN_DONE = os.environ.get("WATCHER_ADVANCE_URL_ON_TURN_DONE", "0") == "1"

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):
    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 active:
                return active
        except Exception:
            pass
        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 順序搵下一隻未喺 rotation-paused.txt 嘅席位；全部暫停回 None。"""
    seats_list = list(seats) if seats is not None else _rot_council_load_seats(default_fallback=True)
    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):
    """讀取 rotation-turn.txt；若檔案唔存在或席位唔喺清單，初始化為第一隻席位並寫入。"""
    seats_list = list(seats) if seats is not None else _rot_council_load_seats(default_fallback=True)
    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):
    """run_watcher 退出前（跑完／自停／正常退出／例外）寫下一隻未暫停席位入 rotation-turn.txt。"""
    try:
        seats = _rot_council_load_seats(default_fallback=False)
        if not seats:
            return None
        paused = _rot_council_get_paused()
        nxt = _rot_council_next_seat(sid, seats=seats, 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                    (62,239B | 1,379L | md5=797357a7755baa381bee249121e05b3d | sha256=1b89afc9655d19a0b73647ebc8dae36fd8cf442a28196694f8e1c968537f7251 | measured_at=2026-10-06T11:36: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", "A5": "5", "A6": "6", "A7": "7"}
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):
    """由 SLOT_Y_POS 或 seats.conf 席位順序（三個一組 0/900/1800）決定目標 Y 座標。"""
    if "SLOT_Y_POS" in globals() and sid in SLOT_Y_POS:
        return int(SLOT_Y_POS[sid])
    try:
        sconf = SYSTEM_DIR / "seats.conf"
        if sconf.exists():
            seat_ids = []
            for line in sconf.read_text(encoding="utf-8", errors="ignore").splitlines():
                line = line.strip()
                if not line or line.startswith("#"):
                    continue
                parts = line.split()
                if parts:
                    seat_ids.append(parts[0])
            if sid in seat_ids:
                return (seat_ids.index(sid) % 3) * 900
    except Exception:
        pass
    m = re.match(r"^A(\d+)$", str(sid or ""))
    if m:
        return ((int(m.group(1)) - 2) % 3) * 900
    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 = {}

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"))
            if isinstance(obj, dict) and obj.get("daily_limit_date") == today:
                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):
                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_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：當指定 profile 名下全部 URL 今日均已觸發 DAILY_LIMIT 時，標記該 profile 今日收工並寫入 per-tail 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"
    if per_tail.exists():
        try:
            obj = json.loads(per_tail.read_text(encoding="utf-8"))
            if isinstance(obj, dict):
                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)
                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_date": today, "daily_limit_profiles": dl_profs,
            "daily_limit_urls": dl_urls,
            "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=""):
    """應 59754＋59758（Owner 強調）& A13/F35：
    1. 撞到 DAILY_LIMIT 時先標記當前 URL 今日已耗盡（daily_limit_urls）。
    2. 優先即刻轉去【同一個 Profile 嘅另一條未耗盡 URL】（新架構 1 Profile 綁 2 URL 正為此設，亦完全兼容 1×10 單一 profile JSON）。
    3. 只有當該 Profile 名下全部 URL 今日均已耗盡時，先至呼叫 _mark_profile_daily_limit_today() 標記該 Profile 今日收工，並轉去下一個未耗盡 Profile 嘅 URL。
    4. 只有當本席全部 URL 均已耗盡時，先回傳 all_profiles_exhausted=True。"""
    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": False}
    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", "all_profiles_exhausted": False}
    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()
)
VPN_EXIT_PROVIDER_KEYWORDS = ("windscribe", "m247", "totallyacdn")

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 _resolve_ws_profiles_dir(profiles_dir=None):
    """應 59641 #6：解析現有 24 個 WS profiles 所在嘅 persistent 目錄（唔起新 WS profile；即使當前運行 profile 喺 ramdisk 仍自動搵返 persistent WS 目錄）。"""
    cands = []
    if profiles_dir is not None:
        cands.append(Path(profiles_dir))
    env_ws = os.environ.get("WATCHER_WS_PROFILES_DIR")
    if env_ws:
        cands.append(Path(env_ws))
    cands.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",
    ])
    seen = set()
    for c in cands:
        try:
            rc = c.resolve()
        except Exception:
            rc = c
        if rc in seen or not c.is_dir():
            continue
        seen.add(rc)
        try:
            for item in c.iterdir():
                if item.is_dir() and _WS_PROFILE_NAME_RE.match(item.name):
                    return c
        except OSError:
            continue
    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 _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():
        shutil.copytree(
            seed_dir,
            ram_dir,
            symlinks=True,
            ignore=shutil.ignore_patterns("SingletonLock", "SingletonCookie", "SingletonSocket", ".google-pw", ".arena-common-pw"),
        )
        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 _merge_ws_extension_layer(src_ws_dir, dst_seat_dir):
    """應 58489 & bm.js WS1_EXT_MERGE_V1..V4：將單一 ws-* profile 嘅 Extension 與設定合併入席位 profile（零 Cache/History/Cookies/憑證寫入）。"""
    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 = (
        "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)
            _shutil.copytree(s_sub, d_sub)
    # 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)
        _shutil.copytree(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)
        for item in s_idb.iterdir():
            if item.is_dir() and item.name.startswith("chrome-extension_"):
                target = d_idb / item.name
                if target.exists():
                    _shutil.rmtree(target, ignore_errors=True)
                _shutil.copytree(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"
    if core_dir.is_dir() and ws_name != "ws-core":
        _merge_ws_extension_layer(core_dir, seat_dir)
    ok = _merge_ws_extension_layer(ws_dir, seat_dir)
    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)
        if sid:
            log(sid, f"✅ [VPN-EXT] 已由現有 WS 池輪流載入收割源：{ws_name} -> {seat_dir.name}")
    return ok

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]
    _apply_ws_extension_to_seat_profile(seat_dir, chosen, pdir, sid=sid)
    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]
    _apply_ws_extension_to_seat_profile(seat_dir, chosen, pdir, sid=sid)
    if sid:
        log(sid, f"🔁 [VPN-EXT] 輪流切換 WS 收割 profile：{prev_ws or 'NONE'} -> {chosen}")
    return chosen

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-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", "ovpn_x509"):
            hv = obj.get(hk)
            if isinstance(hv, str) and ("totallyacdn." in hv or "windscribe." in hv):
                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

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, 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:
                try:
                    proxy_port = int(proxy_obj.get(pk))
                    break
                except Exception:
                    pass
    if unwrapped.get("proxyPort") is not None and proxy_port is None:
        try:
            proxy_port = int(unwrapped.get("proxyPort"))
        except Exception:
            pass
    # 應 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 = int(m.group(2))
    port_final = int(proxy_port) if (proxy_port and 1 <= int(proxy_port) <= 65535) else 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 _stage_a_harvest_windscribe(p, sid, profile_dir, socks_port, timeout_ms=None):
    """應 59406 Stage A：以 socks5://127.0.0.1:<socks_port> ＋ --load-extension 開 popup 收割憑證與 proxy.hosts（唔撳 Connect），收割完即關 browser。"""
    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

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._upstream_hosts = []
        self._upstream_port = 443
        self._auth_b64 = None
        self._server_sock = None
        self._running = False
        self.tunnel_ok_count = 0
        self.tunnel_err_count = 0
        self.last_ok_host = None
        self.last_error = None

    def update_upstream(self, socks_port, hosts, proxy_port, username, password, socks_host="127.0.0.1"):
        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")
        with self._lock:
            self._socks_host, self._socks_port = str(socks_host or "127.0.0.1"), int(socks_port)
            self._upstream_hosts, self._upstream_port = clean_hosts, int(proxy_port or 443)
            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
            hosts, up_port, auth_b64 = list(self._upstream_hosts), self._upstream_port, self._auth_b64
        if not socks_port or not hosts or not auth_b64:
            raise RuntimeError("Chain proxy upstream not configured")
        last_exc = None
        for ws_host in hosts:
            raw_sock = tls_sock = None
            try:
                raw_sock = self._socks5_connect(socks_host, socks_port, ws_host, up_port, timeout=timeout)
                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
                    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
                for sck in (tls_sock, raw_sock):
                    if sck is not None:
                        try:
                            sck.close()
                        except Exception:
                            pass
        with self._lock:
            self.tunnel_err_count += 1
            self.last_error = f"{type(last_exc).__name__}:{last_exc}"
        raise RuntimeError(f"All Windscribe hosts failed ({hosts}): {last_exc}")

    @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 _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_windscribe_tls_tunnel(t_host.strip("[]"), t_port, timeout=15.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_windscribe_tls_tunnel(sp.hostname or "", sp.port or 80, timeout=15.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

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

def _stop_all_chain_proxies():
    with _SEAT_CHAIN_LOCK:
        keys = list(_SEAT_CHAIN_PROXIES.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))
    if not has_unpacked_ext or not VPN_USE_CHAIN_PROXY:
        return {
            "ok": True, "mode": "direct_socks", "proxy_server": f"socks5://127.0.0.1:{socks_port}",
            "load_extensions": False, "chain_port": None, "hosts": [],
            "reason": "no-unpacked-ext" if not has_unpacked_ext else "chain-disabled",
        }
    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)
    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=socks_port))
                _SEAT_CHAIN_PROXIES[key] = chain
            elif prev_host is None and chain.last_ok_host:
                prev_host = chain.last_ok_host
            chain.update_upstream(
                socks_port=socks_port, hosts=ordered_hosts, proxy_port=harvest["port"],
                username=harvest["username"], password=harvest["password"],
            )
            listen_port = chain.start()
        if rotate_upstream:
            log(sid, f"🔁 [VPN-CHAIN:ROTATE] 換 URL 同步切換 Windscribe upstream：{prev_host or 'NONE'} -> 首選 {ordered_hosts[0]} (候選池共 {len(ordered_hosts)} 粒: {ordered_hosts})")
        log(sid, f"🔗 [VPN-CHAIN:STAGE-B] 本地 Chain Proxy 就緒：127.0.0.1:{listen_port} -> socks5://127.0.0.1:{socks_port} -> TLS {ordered_hosts}:{harvest['port']}")
        return {
            "ok": True, "mode": "chain", "proxy_server": f"http://127.0.0.1:{listen_port}",
            "load_extensions": False, "chain_port": listen_port, "hosts": ordered_hosts,
            "prev_host": prev_host, "chosen_host": ordered_hosts[0] if ordered_hosts else None, "reason": None,
        }
    except Exception as e:
        log(sid, f"❌ [VPN-CHAIN:STAGE-B] 啟動或更新 Chain Proxy 失敗：{e}")
        return {
            "ok": False, "mode": "chain", "proxy_server": None, "load_extensions": False,
            "chain_port": None, "hosts": [], "reason": f"chain-start-exc:{type(e).__name__}:{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=6.0, allow_cached=True):
    """Probe SOCKS exit IP. Cache is valid for chain baseline only, never for failover liveness proof."""
    if not socks_port:
        return None, "no-socks-port"
    sp = int(socks_port)
    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://ipinfo.io/json",
        "https://api.ipify.org?format=json",
        "https://checkip.amazonaws.com",
        "https://icanhazip.com",
        "https://www.cloudflare.com/cdn-cgi/trace",
    )
    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 (
        ("ipinfo.io", "/json"),
        ("api.ipify.org", "/?format=json"),
        ("checkip.amazonaws.com", "/"),
        ("icanhazip.com", "/"),
        ("www.cloudflare.com", "/cdn-cgi/trace"),
    ):
        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
    cached = _SOCKS_TUNNEL_IP_CACHE.get(sp)
    if allow_cached and cached and (time.time() - cached[1]) < 600.0:
        return cached[0], None
    return None, "; ".join(errs)[:200] or "socks-probe-empty"

def _probe_chain_proxy_exit_ip_host_side(chain_port, timeout=8.0):
    """應 59726：當 browser 處於 about:blank 執行 fetch 被攔或超時時，由 host 端直接經 127.0.0.1:<chain_port> 探測出口 IP 作後備驗證。"""
    if not chain_port:
        return None
    cp = int(chain_port)
    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,
            )
            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 _verify_windscribe_exit(page, sid, socks_port=None):
    """應 59426（取代 59425）& 59726：
    1. 先經 SOCKS（唔經 Windscribe chain）打一次攞隧道基準出口 IP（tunnel_ip）
    2. 再經 chain proxy（1808x → Windscribe）打一次攞出口 IP（ip），支援多端點＋host-side curl 後備探測
    3. 對比：ip == tunnel_ip → reject；ip != tunnel_ip → accept。"""
    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 = None
    tunnel_err = None
    if sp is not None:
        tunnel_ip, tunnel_err = _probe_socks_tunnel_exit_ip(sp, sid=sid)
        if not tunnel_ip:
            return False, f"ip=- tunnel_ip=- socks_port={sp} reason=tunnel-baseline-failed err={tunnel_err or '-'}"
    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(10000) });
            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(10000) });
                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(8000) });
                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(8000) });
                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 False, "evaluate-failed:" + type(e).__name__
    if not isinstance(res, dict):
        return False, "bad-response:" + repr(res)[:120]
    ip = (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=8.0)
            if host_ip:
                ip = host_ip
    detail = (f"ip={ip or '-'} tunnel_ip={tunnel_ip or '-'} org={res.get('org') or '-'} host={res.get('hostname') or '-'} "
              f"err={str(res.get('err') or '-')[:200]}")
    if not ip:
        return False, detail + " reason=empty-exit-ip"
    if tunnel_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 _activate_vpn_extension_once(browser, page, sid, profile_dir, require_on=False):
    """應 58325 #3b & 58489 & 59406（Fix 2）& 59419（問題二）& 59426 & 59726：Chain Proxy 模式直接以 _verify_windscribe_exit 對比 SOCKS 基準 IP 與 Chain 出口 IP；否則行 popup 啟用＋驗證；支援 VPN_FAIL_OPEN=1。"""
    if os.environ.get("VPN_FAIL_OPEN") == "1" or VPN_FAIL_OPEN:
        log(sid, "⚠️ [VPN-LATCH-FIX] VPN_FAIL_OPEN=1，跳過嚴格 Extension VPN 啟用檢查（放行）")
        return True
    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
    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=2000)
                    st0 = kn.get("state")
                    if st0 == "on":
                        log(sid, f"[VPN-EXT] 初始狀態已係 ON (cls={kn.get('cls')!r} text={kn.get('text')!r}) → 執行 on->off->on 重新連線")
                        joy_loc.first.click(timeout=5000)
                        off_r = _wait_vpn_toggle_state(ext_page, ("off",), timeout_ms=3000)
                        if off_r.get("ok"):
                            joy_loc.first.click(timeout=5000)
                            on_r = _wait_vpn_toggle_state(ext_page, ("on",), timeout_ms=3000)
                            activated = bool(on_r.get("ok"))
                    elif st0 == "off":
                        log(sid, f"[VPN-EXT] 初始狀態係 OFF (cls={kn.get('cls')!r} text={kn.get('text')!r}) → 撳 1 次轉 ON")
                        joy_loc.first.click(timeout=5000)
                        on_r = _wait_vpn_toggle_state(ext_page, ("on",), timeout_ms=3000)
                        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
    # 應 dj_host1 59308/59310（Fix 1 #3）：UI 話 ON 唔等於真連咗 —— 經 browser
    # 實取出口 IP、核到 Windscribe 先准當成功；驗證失敗即改 activated=False。
    if activated:
        exit_ok, exit_detail = _verify_windscribe_exit(page, sid)
        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 require_on and not activated:
        # 應 59727 #3（Owner 指示）：Chain proxy 唔 ready 跌落後備路時，底層已掛本席 VPN SOCKS5 隧道；
        # 除非顯式設 VPN_STRICT_FAIL_CLOSED=1，否則 extension 撳唔到時記警告繼續行（或由外層轉下一個），絕不 fail-closed 無限 loop 卡死席位
        if os.environ.get("VPN_STRICT_FAIL_CLOSED", "0") == "1":
            log(sid, "❌ [VPN-EXT] Extension VPN 啟用失敗 (activated=False)，VPN_STRICT_FAIL_CLOSED=1 fail-closed")
            return False
        log(sid, "⚠️ [VPN-EXT] 後備路 Extension VPN 撳掣未確認 (activated=False)，底層已行本席 VPN SOCKS5 隧道，按 59727 #3 記警告放行繼續推（唔卡死席位）")
        return True
    if not activated:
        # 應主持 58524（A93 修復版）：lax mode 下「未確認 ON」唔可以印 ✅——舊版呢句係「靜默失敗」嘅幫兇之一
        log(sid, "⚠️ [VPN-EXT] 啟用未確認（activated=False），lax mode 放行——請查本 profile 嘅 ws-* extension 狀態")
    else:
        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

    # 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 has_unpacked_ext and 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:
        _t_ip, _t_err = _probe_socks_tunnel_exit_ip(port, sid=sid, allow_cached=False) if port else (None, "no-port")
        if _t_ip or os.environ.get("VPN_FAIL_OPEN") == "1" or VPN_FAIL_OPEN:
            log(sid, f"⚠️ [PROFILE-SWITCH:STEP2-VPN] Extension/Chain 啟用未過，已核實本席專屬 VPN SOCKS5 隧道 (127.0.0.1:{port} exit_ip={_t_ip or 'FAIL_OPEN'}) 正常，切換直連 SOCKS5 隧道繼續切換 profile={next_profile}")
            try:
                new_browser.close()
            except Exception:
                pass
            _stop_seat_chain_proxy(sid)
            try:
                new_browser = p.chromium.launch_persistent_context(
                    str(new_profile_dir),
                    headless=False,
                    device_scale_factor=1,
                    proxy={"server": f"socks5://127.0.0.1:{port}"},
                    args=_build_chromium_launch_args(new_profile_dir, load_extensions=False),
                    ignore_default_args=["--enable-automation"],
                    viewport={"width": 1400, "height": 900},
                )
                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)
                vpn_ok = True
            except Exception as _fb_e:
                log(sid, f"❌ [PROFILE-SWITCH-FAIL:STEP2-SOCKS-FALLBACK] 切換直連 SOCKS5 重開 Chrome 失敗 ({_fb_e})")
                vpn_ok = False
        if not vpn_ok:
            log(sid, f"❌ [PROFILE-SWITCH-FAIL:STEP2-VPN] profile={next_profile} 開啟 Extension VPN 失敗，fail-closed 中止")
            try:
                new_browser.close()
            except Exception:
                pass
            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:
        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)
    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():
    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:
                ports[parts[0]] = int(parts[1])
    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': 900, 'A4': 1800,
    'A5': 0, 'A6': 900, 'A7': 1800,
    'A8': 0, 'A9': 900, 'A10': 1800,
}

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(page)
        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 = {}

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

def is_daily_limit_error(page, sid):
    """應主持 58489 & 59418（第1、2、3項）：檢測 daily limit（第1項藍掣8s重現／第2項紅字 Something went wrong + try again／第3項連續3輪時間戳唔變）→ 觸發換 URL（唔報 Muse）。"""
    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):
            log(sid, "⚠️ [DAILY-LIMIT:ITEM2] 檢測到每日限制紅字（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()
            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()
            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）
    """
    if not ensure_rotation_url(page, sid):
        log(sid, "[URL-GUARD] cycle 中止（URL 唔喺 JSON）")
        return "URL_GUARD_ABORT"
    _dismiss_cookie_consent(page, sid)
    # 0. recall state（跨 restart 嘅 HOLD／pending／baseline；人手 reconciliation）
    if not _recall_state_apply(sid):
        log(sid, "recall state 讀唔到（fail-closed）→ 停呢個 cycle：零扣、零送")
        return "UNCONFIRMED"
    # 1. 見 Stop 掣（生成緊）→ 乜都唔做
    if is_generating(page):
        log(sid, "見到 Stop 掣（生成緊），乜都唔做，等下個 cycle")
        return "SKIP_GENERATING"
    # 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)
            if find_keep_working(page, sid) is not None and not is_generating(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"
            page.reload(wait_until="domcontentloaded", timeout=60000)
            wait_for_page_generated(page, sid)
            page.wait_for_timeout(5000)
            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)
                    if find_keep_working(page, sid) is not None and not is_generating(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"
                    page.reload(wait_until="domcontentloaded", timeout=60000)
                    wait_for_page_generated(page, sid)
                    page.wait_for_timeout(5000)
                if find_keep_working(page, sid) is not None:
                    log(sid, "🚨 [DAILY-LIMIT:ITEM1] 兩次撳藍色掣後仍出返藍色（Keep working 重現）→ 判定 daily limit，立即換 URL（唔報 Muse）")
                    _mark_daily_limit_hit(sid, "item1_keep_working_persists")
                    return "DAILY_LIMIT"
            log(sid, "確認冇 Keep working，可以 send")
        except Exception as e:
            log(sid, f"撳 Keep working 出錯: {e}")
            return "KW_CLICK_ERROR"
    else:
        log(sid, "無 Keep working 掣，直接 send")
    # 3. Send（應 59418 第3項：喺推之前記低最底 Response ended 時間戳）
    _record_response_ended_before_push(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"
    # 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(page)
    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(page)
    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):
    _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）")
                _mark_daily_limit_hit(sid, f"item1_gate_purple_8s_blue_reappear:{label}")
                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 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 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 = vpn_ports[cfg["vpn"]]

    _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)
        # 應 59758 & 59641 #5：若當前 URL 或當前 profile 今日已觸發 DAILY_LIMIT 耗盡，啟動前自動跳去下一個可用 URL/profile
        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"):
                log(sid, f"🚨 [DAILY-LIMIT:ALL-PROFILES-DONE] {sid} 今日全部 URL/profile 已收工，直接寫 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"]

    # 應 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
        _force_rotate_upstream = False
        try:
            _boot_rt = _prepare_seat_vpn_runtime(p, sid, profile_dir, port)
            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]
            else:
                log(sid, f"❌ [VPN-CHAIN:BOOT] 啟動 Stage A/B 失敗 ({_boot_rt.get('reason')})，進入主循環 fail-closed 重試")
            first_load = True
            cycle_count = 0  # 計 cycle 數，每 120 個 cycle（約 1 小時）做一次登入檢查
            _consec_err_result = None  # 議會 patch：連續同一錯誤追蹤（結果字串）
            _consec_err_count = 0  # 議會 patch：連續同一錯誤次數

            while True:
                try:
                    # 檢查 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
                            _t_ip_ro, _ = _probe_socks_tunnel_exit_ip(port, sid=sid, allow_cached=False) if port else (None, None)
                            if (_vpn_boot_fail_count >= VPN_MAX_STRICT_RETRIES and _t_ip_ro) or os.environ.get("VPN_FAIL_OPEN") == "1" or VPN_FAIL_OPEN:
                                log(sid, f"⚠️ [VPN-CHAIN:REOPEN] Stage A/B 連續 {_vpn_boot_fail_count} 次失敗 ({_reopen_rt.get('reason')})，已核實本席專屬 VPN SOCKS5 隧道 (127.0.0.1:{port} exit_ip={_t_ip_ro or 'FAIL_OPEN'}) 正常，切換直連 SOCKS5 隧道重開 browser")
                                _stop_seat_chain_proxy(sid)
                                _reopen_rt = {
                                    "ok": True, "mode": "direct_socks",
                                    "proxy_server": f"socks5://127.0.0.1:{port}",
                                    "load_extensions": False,
                                }
                            else:
                                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-* 等 {CHECK_INTERVAL} 秒再試")
                                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 = (_reopen_rt.get("mode") == "direct_socks" and _vpn_boot_fail_count >= VPN_MAX_STRICT_RETRIES)

                    if not vpn_ext_activated:
                        # 應主持 58524（A93 修復版）& 59726（防 fail-closed 無限循環）：
                        #   ① 接住返回值，require_on=True
                        #   ② 初次失敗時自動輪換下一個 ws-* profile 及 upstream host 再試
                        #   ③ 若連續失敗達 VPN_MAX_STRICT_RETRIES（預設 2 次）或 VPN_FAIL_OPEN=1，且本席專屬 VPN SOCKS5 隧道 (127.0.0.1:port) 驗證正常，
                        #      自動切換 browser 直連該席 VPN SOCKS5 隧道並上 latch 繼續推，徹底消除 1650+ 次無限循環
                        _boot_has_ext = bool(_discover_unpacked_extensions(profile_dir))
                        if not _boot_has_ext and VPN_BOOT_ALLOW_NO_EXT:
                            log(sid, "⚠️ [VPN-LATCH-FIX] 本 profile 無 unpacked ws-* extension，VPN_BOOT_ALLOW_NO_EXT=1 放行，跳過 Extension VPN 啟用")
                            vpn_ext_activated = True
                        else:
                            _boot_vpn_ok = _activate_vpn_extension_once(
                                browser, page, sid, profile_dir, require_on=_boot_has_ext
                            )
                            if not _boot_vpn_ok:
                                _vpn_boot_fail_count += 1
                                _t_ip_boot, _ = _probe_socks_tunnel_exit_ip(port, sid=sid, allow_cached=False) if port else (None, None)
                                if (_vpn_boot_fail_count >= VPN_MAX_STRICT_RETRIES and _t_ip_boot) or os.environ.get("VPN_FAIL_OPEN") == "1" or VPN_FAIL_OPEN:
                                    log(sid, f"⚠️ [VPN-LATCH-FIX] Extension/Chain 連續 {_vpn_boot_fail_count} 次啟用未過，已核實本席專屬 VPN SOCKS5 隧道 (127.0.0.1:{port} exit_ip={_t_ip_boot or 'FAIL_OPEN'}) 正常，切換直連 SOCKS5 隧道並上 latch 繼續推（防 fail-closed 無限循環）")
                                    try:
                                        browser.close()
                                    except Exception:
                                        pass
                                    _stop_seat_chain_proxy(sid)
                                    browser = p.chromium.launch_persistent_context(
                                        str(profile_dir), headless=False, device_scale_factor=1,
                                        proxy={"server": f"socks5://127.0.0.1:{port}"},
                                        args=_build_chromium_launch_args(profile_dir, load_extensions=False),
                                        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 = True
                                else:
                                    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] 啟動時 Extension VPN 啟用失敗 (retry={_vpn_boot_fail_count}/{VPN_MAX_STRICT_RETRIES}, next_ws={_sw_ws})，fail-closed：唔上 latch，關 browser 並輪換 ws-* 後下一輪重試")
                                    try:
                                        browser.close()
                                    except Exception:
                                        pass
                                    browser = None
                                    page = None
                                    first_load = True
                                    time.sleep(CHECK_INTERVAL)
                                    continue
                            else:
                                _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/阻塞）
                        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")
                        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"]
                                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")
                                log(sid, "指定 URL 載入中，120s 內搵 slide menu 制...")
                                wait_for_sidebar_button(page, sid)
                                _dismiss_cookie_consent(page, sid)
                                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)
                                if _rot_np.get("all_profiles_exhausted"):
                                    log(sid, f"🚨 [GOOGLE-PW:ALL-PROFILES-TRIED] {sid} 本輪全部 profile 均已嘗試或收工，結束本席輪次交棒下一席")
                                    break
                                _sw_np = _reopen_chrome_for_profile_switch(p, browser, sid, cfg, port, _rot_np, PROFILES_DIR, cur_page=page)
                                browser = _sw_np.get("browser")
                                page = _sw_np.get("page")
                                if _sw_np.get("profile_dir") is not None:
                                    profile_dir = _sw_np["profile_dir"]
                                vpn_ext_activated = bool(_sw_np.get("ok"))
                                first_load = True
                                log(sid, f"⏭️ [GOOGLE-PW:PASS] {sid} 已上報失敗 profile ({_rot_np.get('skipped_profile')}: {_pw_reason}) 並直接 pass 去下一個 profile={cfg['profile']}（{_rot_np.get('label')}: {cfg['url']}）繼續推")
                                continue
                            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)
                                if _rot_np.get("all_profiles_exhausted"):
                                    log(sid, f"🚨 [GOOGLE-PW:ALL-PROFILES-TRIED] {sid} 本輪全部 profile 均已嘗試或收工，結束本席輪次交棒下一席")
                                    break
                                _sw_np = _reopen_chrome_for_profile_switch(p, browser, sid, cfg, port, _rot_np, PROFILES_DIR, cur_page=page)
                                browser = _sw_np.get("browser")
                                page = _sw_np.get("page")
                                if _sw_np.get("profile_dir") is not None:
                                    profile_dir = _sw_np["profile_dir"]
                                vpn_ext_activated = bool(_sw_np.get("ok"))
                                first_load = True
                                log(sid, f"⏭️ [GOOGLE-PW:PASS] {sid} 運行中補密碼失敗已上報 ({_rot_np.get('skipped_profile')}: {_pw_reason})，直接 pass 去下一個 profile={cfg['profile']}（{_rot_np.get('label')}: {cfg['url']}）繼續推")
                                continue
                            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"))

                    # 應 59754＋59758（Owner 強調）& A13/F35：撞到 DAILY_LIMIT 必須即刻自動轉另一條 URL（優先轉同一個 Profile 嘅另一條未耗盡 URL，同 Profile 全部 URL 耗盡後轉下一個 Profile，絕不停喺度）
                    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)
                        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("all_profiles_exhausted"):
                                log(sid, f"🚨 [DAILY-LIMIT:ALL-PROFILES-DONE] {sid} 今日全部 URL/profile 已觸發 DAILY_LIMIT 收工，結束本輪並交棒下一席")
                                break
                            if _rot_dl.get("label"):
                                _active_slot_label = _rot_dl["label"]
                            _sw_dl = _reopen_chrome_for_profile_switch(p, browser, sid, cfg, port, _rot_dl, PROFILES_DIR, cur_page=page)
                            browser = _sw_dl.get("browser")
                            page = _sw_dl.get("page")
                            if _sw_dl.get("profile_dir") is not None:
                                profile_dir = _sw_dl["profile_dir"]
                            if not _sw_dl.get("ok"):
                                if _sw_dl.get("phase") != "validate":
                                    vpn_ext_activated = False
                                    first_load = True
                                log(sid, f"❌ [DAILY-LIMIT-FAIL] {sid} 跳轉下一個 URL/profile 重開失敗 (reason={_dl_reason}, phase={_sw_dl.get('phase')})，fail-closed 停手等待下輪")
                                time.sleep(CHECK_INTERVAL)
                            else:
                                vpn_ext_activated = True
                                first_load = True
                                if _rot_dl.get("same_profile_next_url"):
                                    log(sid, f"🚨 [DAILY-LIMIT:SAME-PROFILE-NEXT-URL] {sid} 觸發 DAILY_LIMIT (reason={_dl_reason})，已即刻轉去同一 profile={cfg['profile']} 嘅另一條 URL=（{_rot_dl.get('label')}: {cfg['url']}）＋ VPN={_sw_dl.get('ws_ext')} 繼續推")
                                else:
                                    log(sid, f"🚨 [DAILY-LIMIT] {sid} profile ({_rot_dl.get('skipped_profile')}) 名下全部 URL 今日收工，已切換至新 ramdisk profile={cfg['profile']} ＋ VPN={_sw_dl.get('ws_ext')} ＋ URL=（{_rot_dl.get('label')}: {cfg['url']}）")
                            continue

                    # 檢測對話超長 → 應 59419 第4項更正：對話耗盡（唔係 daily limit），既要報 Muse（通知呢個 SLOT 死咗要招新人、呢條 URL 永久退役），亦要換 URL 繼續跑下一個 SLOT
                    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):
                            _rot_nxt = _with_rotation_flock(rotation_advance, sid)
                            _sw_tl = _reopen_chrome_for_profile_switch(p, browser, sid, cfg, port, _rot_nxt, PROFILES_DIR, cur_page=page)
                            browser = _sw_tl.get("browser")
                            page = _sw_tl.get("page")
                            if _sw_tl.get("profile_dir") is not None:
                                profile_dir = _sw_tl["profile_dir"]
                            if not _sw_tl.get("ok"):
                                if _sw_tl.get("phase") != "validate":
                                    vpn_ext_activated = False
                                    first_load = True
                                log(sid, f"❌ [TOO-LONG-SWITCH-FAIL] {sid} 對話超長（已報 Muse）三步重開失敗 (phase={_sw_tl.get('phase')})，fail-closed 停手等待下輪")
                                time.sleep(CHECK_INTERVAL)
                            else:
                                vpn_ext_activated = True
                                first_load = True
                                log(sid, f"🚨 [TOO-LONG:ROTATE+MUSE] 對話超長確認：{sid} 已報 Muse 通知舊 SLOT 退役，並已三步重開轉去 URL（{_rot_nxt.get('label')}｜profile={cfg['profile']}: {cfg['url']}）")
                            continue
                        # 非 ROTATION_TAILS 席位：已報 Muse，停呢個 watcher 等 Muse AI 開新對話
                        log(sid, "停 watcher，等 Muse AI 開新對話")
                        break

                    if result in ("NO_INPUT", "NO_INPUT_2", "KW_CLICK_ERROR", "UNCONFIRMED"):
                        log(sid, f"⚠️ {result} → 需要人手處理，{CHECK_INTERVAL}秒後重試")
                    elif result == "HOLD_RESOLVED":
                        log(sid, f"✅ HOLD 已自解（pending 已確認送出、已扣號）→ 等 {CHECK_INTERVAL} 秒入下一個 cycle；唔需要人手")
                        # （is_login_flow_stuck_on_session_missing 只准喺 Google login 期間用，唔喺主 loop 用）

                    # 議會 patch 2026-10-16（59641 #7 保留）：連續 N 個 cycle 同一錯誤 → 自動停止（防無限 wedge）；其他結果 reset 計數
                    if result in _CONSEC_ERROR_RESULTS:
                        if result == _consec_err_result:
                            _consec_err_count += 1
                        else:
                            _consec_err_result = result
                            _consec_err_count = 1
                        if _consec_err_count >= MAX_CONSECUTIVE_SAME_ERROR:
                            log(sid, f"🛑 連續 {MAX_CONSECUTIVE_SAME_ERROR} 個 cycle 同一錯誤 ({result})，自動停止")
                            break
                    else:
                        _consec_err_result = None
                        _consec_err_count = 0

                    # 每 120 個 cycle（約 1 小時）做一次登入檢查
                    cycle_count += 1
                    if cycle_count % 120 == 0:
                        login_state = check_login_state(page, sid, cfg["account"], browser)
                        log(sid, f"定時登入檢查：{login_state}")
                        if login_state == 'session_cleared_retry':
                            log(sid, "Arena session missing 已清 arena，重開 browser 再試")
                            try:
                                browser.close()
                            except:
                                pass
                            browser = None
                            continue
                        if login_state in ('logged_out', 'login_failed'):
                            _s_key = str(sid or "").strip().upper()
                            _pw_reason = _LAST_GOOGLE_PW_FATAL.pop(_s_key, None)
                            if not _pw_reason:
                                _pw_reason = f"periodic_{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)
                                if _rot_np.get("all_profiles_exhausted"):
                                    log(sid, f"🚨 [GOOGLE-PW:ALL-PROFILES-TRIED] {sid} 定時檢查：本輪全部 profile 均已嘗試或收工，結束本席輪次交棒下一席")
                                    break
                                _sw_np = _reopen_chrome_for_profile_switch(p, browser, sid, cfg, port, _rot_np, PROFILES_DIR, cur_page=page)
                                browser = _sw_np.get("browser")
                                page = _sw_np.get("page")
                                if _sw_np.get("profile_dir") is not None:
                                    profile_dir = _sw_np["profile_dir"]
                                vpn_ext_activated = bool(_sw_np.get("ok"))
                                first_load = True
                                log(sid, f"⏭️ [GOOGLE-PW:PASS] {sid} 定時檢查登入失敗已上報 ({_rot_np.get('skipped_profile')}: {_pw_reason})，直接 pass 去下一個 profile={cfg['profile']}（{_rot_np.get('label')}: {cfg['url']}）繼續推")
                                continue
                            break
                        elif login_state == 'logged_in' and cfg.get("url") and cfg["url"] not in str(getattr(page, "url", "") or ""):
                            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")
                            _dismiss_cookie_consent(page, sid)
                        elif login_state == 'unknown':
                            log(sid, "⚠️ 登入狀態不明，已截圖留證")

                    if once:
                        break

                    # SUCCESS_NEXT_CYCLE：即刻下一個循環，唔等 30 秒
                    if result == "SUCCESS_NEXT_CYCLE":
                        log(sid, "即刻開始下一個循環（唔等 30 秒）")
                        continue

                    # 應 59641 #4：流程「CP 種→ramdisk → 開 browser → 跑推 cycle → 跑完／自停／例外 → 閂 browser → 清 ramdisk 嗰個 profile → 寫 turn → 下一個 profile」
                    if WATCHER_EXIT_TURN_ON_DONE and (
                        result == "SUCCESS"
                        or (result == "SKIP_GENERATING" and WATCHER_EXIT_TURN_ON_SKIP_GENERATING)
                    ):
                        if WATCHER_ADVANCE_URL_ON_TURN_DONE and _resolve_rotation_tail(sid):
                            _with_rotation_flock(rotation_advance, sid)
                        log(sid, f"✅ [TURN-DONE] {sid} 本輪推 cycle 跑完 (result={result}) → 準備閂 browser、清 ramdisk profile ({cfg.get('profile')}) 並寫 turn 交棒")
                        break

                    time.sleep(CHECK_INTERVAL)

                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)
        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)
        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)
        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)
        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 single_seat or once:
        sys.exit(run_watcher(sid, once=once))
    sys.exit(run_coordinator(initial_sid=sid, once=False))
