#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
futu.py — Kline Probe & Canonical Batch Producer
================================================================================
Single-file market-data producer for the AutoTrade ingest pipeline.

Contract      : autotrade.canonical-batch.v1   (contract_revision 2026-07-24)
Version       : v9.0.0-canonical
Baseline      : AUTH-B futu.py v8.9.7/v8.10 (Redroid + uiautomator2 crawler)
Deployment    : exactly ONE executable python file (no package split)
Target        : ARM64, 2 CPU cores, 12 GB RAM, Redroid container per machine

What this file contains (workstream map, all merged into one file):
  W1  normalize .... canonical bar normalization (symbol / time / fixed point /
                     is_final + revision state machine inputs)
  W2  outbox ....... durable SQLite outbox (WAL, synchronous=FULL,
                     busy_timeout, BEGIN IMMEDIATE) + producer_state + bar_state
  W3  transport .... requests.Session pooling, gzip payload, HMAC-SHA256 over the
                     raw gzip bytes, ACK validation, bounded backoff + jitter
  W4  crawler ...... baseline Redroid/uiautomator2 scraping reworked into
                     scrape -> normalize -> enqueue -> send, watchdog preserved
  W5  health ....... health HTTP endpoint + health file + graceful SIGINT/SIGTERM
  W6  self-test .... --self-test (temp SQLite + local mock ingest server, gates
                     A..M) and --generate-fixture (integration artifacts)

Delivery guarantee:
  The normal data path is a DIRECT PUSH of canonical batches to INGEST_URL.
  Files (new_klines_1.json / renew_klines_1.json) are OPTIONAL legacy diagnostics
  and are NEVER the delivery truth. Every un-ACKed batch stays in the persistent
  SQLite outbox until the server ACKs it.

Dependency policy (AUTH-A <dependencies>):
  third-party allowed .... requests, uiautomator2
  third-party forbidden .. redis, psycopg2, aiosqlite, SQLAlchemy, ORM, pandas,
                           numpy, pydantic, FastAPI, aiohttp, celery, RPC frameworks
  stdlib used ............ sqlite3, json, os, re, time, threading, gc, zoneinfo,
                           argparse, xml.etree.ElementTree, datetime, collections,
                           subprocess, hashlib, hmac, uuid, gzip, http.server,
                           signal  (all explicitly allowed) plus the following
                           stdlib-only support modules, declared in the handoff
                           PACKAGE_CHANGES: sys, io, traceback, tempfile, shutil
                           (tempfile/shutil are used by --self-test; tempfile also by FIX K-15 atomic_write_json).
  NOTE: `random` is deliberately NOT imported; retry jitter is derived
        deterministically from sha256(batch_id, attempt) so the retry schedule is
        reproducible and no extra module is required.
"""

from __future__ import annotations

import argparse
import gc
import gzip
import hashlib
import hmac
import io
import json
import os
import re
import signal
import sqlite3
import subprocess
import sys
import threading
import time
import traceback
import uuid
import zoneinfo
import xml.etree.ElementTree as ET
from collections import defaultdict
from datetime import date, datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

# ── third-party: requests (transport) ─────────────────────────────────────────
try:
    import requests
    from requests.adapters import HTTPAdapter

    REQUESTS_IMPORT_ERROR = None
except Exception as _req_err:  # pragma: no cover - environment dependent
    requests = None
    HTTPAdapter = None
    REQUESTS_IMPORT_ERROR = f"{type(_req_err).__name__}: {_req_err}"

# ── third-party: uiautomator2 (device automation, crawl mode only) ────────────
try:
    import uiautomator2 as u2

    U2_IMPORT_ERROR = None
except Exception as _u2_err:  # pragma: no cover - environment dependent
    u2 = None
    U2_IMPORT_ERROR = f"{type(_u2_err).__name__}: {_u2_err}"


APP_VERSION = "9.0.0-canonical"

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 1 — INTEGRATION LOCK CONSTANTS (frozen, verbatim semantics from v1)
#   contract_id / revision / payload field order / scales / HMAC source rule.
#   These constants MUST NOT be changed by any engineer (AUTH-A R7).
# ══════════════════════════════════════════════════════════════════════════════
CONTRACT_ID = "autotrade.canonical-batch.v1"
CONTRACT_REVISION = "2026-07-24"
SCHEMA_VERSION = 1
TIMEFRAME_SEC = 60
INGEST_PATH = "/v1/ingest/batches"

# fixed_bar_row_order — index -> name (frozen)
BAR_ROW_FIELDS = (
    "symbol",           # 0  string
    "timeframe_sec",    # 1  integer
    "bar_start_utc_ms",  # 2  integer
    "open_ticks",       # 3  integer
    "high_ticks",       # 4  integer
    "low_ticks",        # 5  integer
    "close_ticks",      # 6  integer
    "volume",           # 7  integer
    "amount_minor",     # 8  integer
    "is_final",         # 9  boolean
    "revision",         # 10 integer, minimum 1
)

# canonical payload top-level key order (frozen)
PAYLOAD_FIELDS = (
    "schema_version",
    "producer_id",
    "batch_id",
    "sequence",
    "market",
    "captured_at_utc_ms",
    "watermark_utc_ms",
    "bars",
)

# ACK contract (frozen)
ACK_REQUIRED_FIELDS = ("batch_id", "status", "accepted", "duplicate", "rejected", "highest_sequence")
ACK_STATUS_COMMITTED = "committed"

# JavaScript / JSON safe integer boundary — a value above this must be rejected.
MAX_SAFE_INT = (2 ** 53) - 1

# Deterministic gzip parameters (so the server engineer can recompute byte-identical
# payloads from the fixture): gzip.GzipFile, compresslevel=6, mtime=0, no filename.
GZIP_COMPRESS_LEVEL = 6

# The single test-only secret used by --self-test and by the published fixture.
# It is NOT a production secret and MUST NOT be used in production.
FIXTURE_TEST_SECRET = "test-only-secret-do-not-use-in-production"


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 2 — CONFIGURATION (.env driven, nothing hardcoded per fleet machine)
# ══════════════════════════════════════════════════════════════════════════════
_ENV_LINE_RE = re.compile(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$")


def _strip_inline_comment(value: str) -> str:
    """Strip an unquoted trailing ` # comment` from a .env value."""
    if not value:
        return value
    if value[0] in "\"'":
        return value
    idx = value.find(" #")
    if idx >= 0:
        return value[:idx].rstrip()
    return value


def parse_env_file(path: str) -> dict:
    """Minimal, dependency-free .env parser (KEY=VALUE, # comments, quotes)."""
    out = {}
    try:
        with open(path, "r", encoding="utf-8") as fh:
            for raw_line in fh:
                line = raw_line.rstrip("\n").rstrip("\r")
                if not line or line.lstrip().startswith("#"):
                    continue
                m = _ENV_LINE_RE.match(line)
                if not m:
                    continue
                key, value = m.group(1), _strip_inline_comment(m.group(2))
                if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
                    value = value[1:-1]
                out[key] = value
    except FileNotFoundError:
        return {}
    except Exception as exc:  # never fatal — configuration continues from os.environ
        sys.stderr.write(f"[config] .env parse warning ({path}): {type(exc).__name__}: {exc}\n")
    return out


class Config(object):
    """Immutable-ish runtime configuration. Real environment always wins over .env."""

    def __init__(self, env_file=None, overrides=None):
        self.env_file = env_file or os.environ.get("FUTU_ENV_FILE") or os.path.join(
            os.path.dirname(os.path.abspath(__file__)), ".env"
        )
        file_env = parse_env_file(self.env_file)
        merged = dict(file_env)
        merged.update({k: v for k, v in os.environ.items()})
        if overrides:
            merged.update({str(k): str(v) for k, v in overrides.items()})
        self._raw = merged
        # FIX K-24：漏讀設定檔唔准靜靜用出廠——即場報警（唔 fatal：容器可以淨靠真 env）
        if not os.path.exists(self.env_file):
            sys.stderr.write(f"[config] ⚠️ 設定檔搵唔到，全部用出廠預設（漏讀唔會靜靜雞）: {self.env_file}\n")

        g = self._get
        # ── identity / environment ────────────────────────────────────────────
        self.FUTU_ENV = g("FUTU_ENV", "production").strip().lower()
        self.PRODUCER_ID = g("PRODUCER_ID", "").strip()
        self.MARKET_MODE = g("MARKET_MODE", "AUTO").strip().upper()
        self.TAB_WHITELIST = tuple(
            t.strip() for t in g("TAB_WHITELIST", "").split(",") if t.strip()
        )
        # ── ingest / transport ────────────────────────────────────────────────
        self.INGEST_URL = g("INGEST_URL", "").strip()
        self.INGEST_HMAC_SECRET = g("INGEST_HMAC_SECRET", "")
        self.HTTP_CONNECT_TIMEOUT_SEC = self._float("HTTP_CONNECT_TIMEOUT_SEC", 5.0)
        self.HTTP_READ_TIMEOUT_SEC = self._float("HTTP_READ_TIMEOUT_SEC", 90.0)  # FIX K-24：出廠值同 futu.env=90 對齊——server 大件 commit+HMAC+WAL fsync 會爆 30s
        self.HTTP_POOL_SIZE = self._int("HTTP_POOL_SIZE", 4)
        # ── outbox ────────────────────────────────────────────────────────────
        self.PUBLIC_DIR = os.path.expanduser(g("PUBLIC_DIR", "~/public"))
        self.OUTBOX_DB_PATH = os.path.expanduser(
            g("OUTBOX_DB_PATH", os.path.join(self.PUBLIC_DIR, "outbox.sqlite3"))
        )
        self.OUTBOX_MAX_ATTEMPTS = self._int("OUTBOX_MAX_ATTEMPTS", 0)
        self.OUTBOX_BACKOFF_BASE_SEC = self._float("OUTBOX_BACKOFF_BASE_SEC", 1.0)
        self.OUTBOX_BACKOFF_MAX_SEC = self._float("OUTBOX_BACKOFF_MAX_SEC", 60.0)
        self.OUTBOX_RETENTION_HOURS = self._float("OUTBOX_RETENTION_HOURS", 168.0)
        self.OUTBOX_BUSY_TIMEOUT_MS = self._int("OUTBOX_BUSY_TIMEOUT_MS", 30000)  # FIX K-21：三線程共用一本簿，肯等 30s 大部分撞車自然消化（PRAGMA 已有，得返預設偏細）
        self.BATCH_MAX_BARS = max(1, self._int("BATCH_MAX_BARS", 800))
        self.SENDER_IDLE_SLEEP_SEC = self._float("SENDER_IDLE_SLEEP_SEC", 0.5)
        self.STARTUP_REPLAY_TIMEOUT_SEC = self._float("STARTUP_REPLAY_TIMEOUT_SEC", 120.0)
        # ── scales (frozen defaults, still externalised per contract) ─────────
        self.PRICE_SCALE = self._int("PRICE_SCALE", 10000)
        self.AMOUNT_SCALE = self._int("AMOUNT_SCALE", 100)
        # ── legacy compatibility (never the delivery truth) ───────────────────
        self.LEGACY_FILE_OUTPUT = self._bool("LEGACY_FILE_OUTPUT", False)
        self.LEGACY_WEBHOOK_URL = g("LEGACY_WEBHOOK_URL", "").strip()
        self.LEGACY_MAPPING_WEBHOOK_URL = g(
            "LEGACY_MAPPING_WEBHOOK_URL", ""
        ).strip()  # P1-09：出廠空＝唔通知舊伺服器；要開自己填 URL
        # Admin token for the server /api/update-mapping webhook (server returns
        # 401 without it). Value = server .env ADMIN_API_TOKEN; keep in .env only.
        self.MAPPING_WEBHOOK_ADMIN_TOKEN = g("MAPPING_WEBHOOK_ADMIN_TOKEN", "").strip()
        self.OW_REMOTE_URL = g("OW_REMOTE_URL", "").strip()  # P1-09：出廠空
        # ── health / shutdown ─────────────────────────────────────────────────
        self.HEALTH_BIND_HOST = g("HEALTH_BIND_HOST", "127.0.0.1").strip()
        self.HEALTH_PORT = self._int("HEALTH_PORT", 8091)
        self.HEALTH_FILE_PATH = os.path.expanduser(
            g("HEALTH_FILE_PATH", os.path.join(self.PUBLIC_DIR, "futu_health.json"))
        )
        self.HEALTH_FILE_INTERVAL_SEC = self._float("HEALTH_FILE_INTERVAL_SEC", 5.0)
        self.SHUTDOWN_GRACE_SEC = self._float("SHUTDOWN_GRACE_SEC", 20.0)
        # ── crawler / device ──────────────────────────────────────────────────
        self.KLINE_BAR_COUNT = max(1, min(8, self._int("KLINE_BAR_COUNT", 8)))  # P1-01: 上限同預設對齊 8（舊 min(5,8) 令 8 永遠用唔到）
        self.WATCHDOG_TIMEOUT_SEC = self._float("WATCHDOG_TIMEOUT_SEC", 120.0)  # FIX K-18：要 ≥ 最長健康 wait（HTTP_READ 90s）＋ margin；25s 會殺死慢而正常嘅 POST 同 interactive 重連
        self.MACHINE_NUM = self._int("MACHINE_NUM", 1)
        _mn = max(1, self.MACHINE_NUM)
        # FIX E-09：留空先食推導值（合約同 futu.env 註解一致）——唔再全場寫死 redroid_1:5555；
        # 預設 n=1 時推導結果同舊預設一模一樣（redroid_1 / 5555 / 127.0.0.1:5555）。
        self.DOCKER_NAME = (g("DOCKER_NAME", "") or "").strip() or f"redroid_{_mn}"
        self.DOCKER_PORT = (g("DOCKER_PORT", "") or "").strip() or str(5554 + _mn)
        self.DEVICE_ID = (g("DEVICE_ID", "") or "").strip() or f"127.0.0.1:{self.DOCKER_PORT}"
        self.DOCKER_IMAGE = g("DOCKER_IMAGE", "redroid/redroid:12.0.0_64only-latest").strip()
        self.DOCKER_SEED_DIR_TEMPLATE = (g("DOCKER_SEED_DIR_TEMPLATE", "") or "").strip() or "/root/redroid_{n}{market}"
        self.STRICT_SESSION_FILTER = self._bool("STRICT_SESSION_FILTER", True)
        # FIX P2-14：切市提前／延後秒數入守則檔（預設同舊寫死一樣，淨係可以由 .env 調）
        self.SWITCH_US_OPEN_LEAD_SEC = self._int("SWITCH_US_OPEN_LEAD_SEC", 15)
        self.SWITCH_US_CLOSE_TRAIL_SEC = self._int("SWITCH_US_CLOSE_TRAIL_SEC", 15 * 60 + 45)
        # R69:APP-HKT — Futu app 而家統一用 HKT（手機時區）顯示所有市場 K 線時間。
        # "HKT"    = 抓到嘅 HHMM 係 HKT 牆鐘；US symbols 自動換算（EDT/EST 自動適應）。
        # "MARKET" = 舊行為（HHMM 係市場當地時間）。
        self.BAR_TIME_DISPLAY = (g("BAR_TIME_DISPLAY", "HKT").strip().upper() or "HKT")
        # R87:SESSURL — 外部統一時間設定 JSON（Google Drive raw download URL；空 = 唔 load 用內建）
        self.SESSIONS_JSON_URL = g("SESSIONS_JSON_URL", "")
        # R99V3:CACHE — 爬蟲本地獨立：GD fetch 成功寫本地 public cache（PUBLIC_DIR/gd_sessions.json）；
        # GD 攞唔到 → 讀 public 舊檔。全部 cache 統一喺 public 資料夾，唔放第二啲位置、唔靠主程序部機。
        self.SESSIONS_CACHE_FILE = g("SESSIONS_CACHE_FILE", "")
        # 登入密碼（BUG B fix）：由 .env FUTU_LOGIN_PASSWORD 讀取，唔硬編碼、唔 log
        self.FUTU_LOGIN_PASSWORD = g("FUTU_LOGIN_PASSWORD", "")
        # Telegram 通知（驗證碼/登入中斷時用；由 .env 讀，唔硬編碼）
        self.TELEGRAM_BOT_TOKEN = g("TELEGRAM_BOT_TOKEN", "").strip()
        self.TELEGRAM_CHAT_ID = g("TELEGRAM_CHAT_ID", "").strip()
        self.MY_IP = g("MY_IP", "").strip()   # 本機 IP（通知用）
        self.MAX_STALE_ROUNDS = self._int("MAX_STALE_ROUNDS", 15)
        self.LOG_LEVEL = g("LOG_LEVEL", "info").strip().lower()

        # ── derived paths (baseline public files are PROTECTED, keep names) ───
        self.ROUND0_FILE = os.path.join(self.PUBLIC_DIR, "combined_stocks.json")
        self.ROUND0_CACHE_HK_FILE = os.path.join(self.PUBLIC_DIR, "combined_stocks_hk.json")
        self.ROUND0_CACHE_US_FILE = os.path.join(self.PUBLIC_DIR, "combined_stocks_us.json")
        self.ROUND0_CACHE_META_FILE = os.path.join(self.PUBLIC_DIR, "combined_stocks_cache_meta.json")
        self.ROUND2_FILE = os.path.join(self.PUBLIC_DIR, "new_klines_1.json")
        self.ROUND2_ALL_FILE = os.path.join(self.PUBLIC_DIR, "renew_klines_1.json")
        self.LOG_FILE = os.path.join(self.PUBLIC_DIR, "kline_probe_log.json")
        self.IMPORTANT_LOG_FILE = os.path.join(self.PUBLIC_DIR, "futu_important.log")
        self.DOCKER_SHM = (g("DOCKER_SHM", "") or "").strip() or f"/dev/shm/{self.DOCKER_NAME}"  # FIX E-09：留空食推導

    # ── helpers ───────────────────────────────────────────────────────────────
    def _get(self, key, default=""):
        # P2-10：空字串係「關掉」，唔好當冇填而用出廠舊地址
        val = self._raw.get(key)
        if val is None:
            return default
        return val

    def _int(self, key, default):
        try:
            return int(str(self._get(key, default)).strip())
        except (TypeError, ValueError):
            return int(default)

    def _float(self, key, default):
        try:
            return float(str(self._get(key, default)).strip())
        except (TypeError, ValueError):
            return float(default)

    def _bool(self, key, default):
        raw = str(self._get(key, "true" if default else "false")).strip().lower()
        return raw in ("1", "true", "yes", "on", "y")

    @property
    def is_production(self) -> bool:
        return self.FUTU_ENV in ("", "production", "prod")

    def validate_for_production(self):
        """Fail fast on boot when a production secret/URL is missing (AUTH-A security)."""
        problems = []
        if not self.INGEST_URL:
            problems.append("INGEST_URL is not set")
        if not self.INGEST_HMAC_SECRET:
            problems.append("INGEST_HMAC_SECRET is empty")
        if not self.PRODUCER_ID:
            problems.append("PRODUCER_ID is not set")
        if self.INGEST_URL and not self.INGEST_URL.lower().startswith(("http://", "https://")):
            problems.append("INGEST_URL must start with http:// or https://")
        return problems

    def redact(self, text):
        """Remove any occurrence of the HMAC secret from a string (defence in depth)."""
        if not text:
            return text
        text = str(text)
        secret = self.INGEST_HMAC_SECRET
        if secret and secret in text:
            text = text.replace(secret, "***REDACTED***")
        return text

    def public_snapshot(self) -> dict:
        """Configuration snapshot that is SAFE to log (no secret values, ever)."""
        return {
            "version": APP_VERSION,
            "contract_id": CONTRACT_ID,
            "contract_revision": CONTRACT_REVISION,
            "futu_env": self.FUTU_ENV,
            "producer_id": self.PRODUCER_ID,
            "market_mode": self.MARKET_MODE,
            "tab_whitelist": list(self.TAB_WHITELIST),
            "ingest_url": self.INGEST_URL,
            "ingest_hmac_secret_set": bool(self.INGEST_HMAC_SECRET),
            "ingest_hmac_secret_len": len(self.INGEST_HMAC_SECRET or ""),
            "outbox_db_path": self.OUTBOX_DB_PATH,
            "public_dir": self.PUBLIC_DIR,
            "price_scale": self.PRICE_SCALE,
            "amount_scale": self.AMOUNT_SCALE,
            "http_connect_timeout_sec": self.HTTP_CONNECT_TIMEOUT_SEC,
            "http_read_timeout_sec": self.HTTP_READ_TIMEOUT_SEC,
            "outbox_max_attempts": self.OUTBOX_MAX_ATTEMPTS,
            "outbox_backoff_base_sec": self.OUTBOX_BACKOFF_BASE_SEC,
            "outbox_backoff_max_sec": self.OUTBOX_BACKOFF_MAX_SEC,
            "outbox_retention_hours": self.OUTBOX_RETENTION_HOURS,
            "batch_max_bars": self.BATCH_MAX_BARS,
            "legacy_file_output": self.LEGACY_FILE_OUTPUT,
            "legacy_webhook_enabled": bool(self.LEGACY_WEBHOOK_URL),
            "health_bind": f"{self.HEALTH_BIND_HOST}:{self.HEALTH_PORT}",
            "health_file": self.HEALTH_FILE_PATH,
            "kline_bar_count": self.KLINE_BAR_COUNT,
            "watchdog_timeout_sec": self.WATCHDOG_TIMEOUT_SEC,
            "device_id": self.DEVICE_ID,
            "docker_name": self.DOCKER_NAME,
        }


CONFIG = Config()

# Baseline-compatible module globals (kept so preserved baseline code reads the
# same names as AUTH-B; they are now sourced from CONFIG).
def _apply_config_globals(cfg):
    """P0-02: refresh snapshots after --env-file replaces CONFIG."""
    global MACHINE_NUM, DEVICE_ID, DOCKER_NAME, DOCKER_PORT, DOCKER_SHM
    global PUBLIC_DIR, ROUND0_FILE, ROUND2_FILE, ROUND2_ALL_FILE, LOG_FILE
    global IMPORTANT_LOG_FILE, ROUND0_CACHE_HK_FILE, ROUND0_CACHE_US_FILE
    global ROUND0_CACHE_META_FILE, KLINE_BAR_COUNT, WATCHDOG_TIMEOUT
    global SWITCH_US_OPEN_LEAD_SEC, SWITCH_US_CLOSE_TRAIL_SEC
    MACHINE_NUM = cfg.MACHINE_NUM
    DEVICE_ID = cfg.DEVICE_ID
    DOCKER_NAME = cfg.DOCKER_NAME
    DOCKER_PORT = cfg.DOCKER_PORT
    DOCKER_SHM = cfg.DOCKER_SHM
    PUBLIC_DIR = cfg.PUBLIC_DIR
    ROUND0_FILE = cfg.ROUND0_FILE
    ROUND2_FILE = cfg.ROUND2_FILE
    ROUND2_ALL_FILE = cfg.ROUND2_ALL_FILE
    LOG_FILE = cfg.LOG_FILE
    IMPORTANT_LOG_FILE = cfg.IMPORTANT_LOG_FILE
    ROUND0_CACHE_HK_FILE = cfg.ROUND0_CACHE_HK_FILE
    ROUND0_CACHE_US_FILE = cfg.ROUND0_CACHE_US_FILE
    ROUND0_CACHE_META_FILE = cfg.ROUND0_CACHE_META_FILE
    KLINE_BAR_COUNT = cfg.KLINE_BAR_COUNT
    WATCHDOG_TIMEOUT = cfg.WATCHDOG_TIMEOUT_SEC
    SWITCH_US_OPEN_LEAD_SEC = cfg.SWITCH_US_OPEN_LEAD_SEC      # FIX P2-14（.env 生效位）
    SWITCH_US_CLOSE_TRAIL_SEC = cfg.SWITCH_US_CLOSE_TRAIL_SEC  # FIX P2-14


_apply_config_globals(CONFIG)

FORCE_MARKET = "AUTO"
MARKET_MODE = "AUTO"
MAX_DEPTH = 29

# UI resource ids (baseline, protected)
RID_TAB_TITLE = "cn.futu.trader:id/tab_title"
RID_OPTIONAL_GROUP = "cn.futu.trader:id/filter_entrance_optional_group"
RID_FILTER_TITLE = "cn.futu.trader:id/filter_entrance_title"
RID_HDR_LIST = "cn.futu.trader:id/header_to_stock_list"
RID_INDEX = "cn.futu.trader:id/index_info_content"
RID_STOCK_NAME = "cn.futu.trader:id/tv_stock_name_and_code"
RID_RV_ROOT = "cn.futu.trader:id/rv_root"
RID_UPDATE_NEGATIVE = "cn.futu.trader:id/negative_btn"
UPDATE_LATER_TEXT = "以後再說"

APP_PACKAGE = "cn.futu.trader"
APP_ACTIVITY = "cn.futu.trader/.launch.activity.LaunchActivity"

TAB_VALID_PAT = re.compile(r"^(us|hk)\d+$", re.IGNORECASE)


def ensure_public_dir():
    try:
        os.makedirs(CONFIG.PUBLIC_DIR, exist_ok=True)
    except Exception as exc:
        sys.stderr.write(f"[config] cannot create PUBLIC_DIR {CONFIG.PUBLIC_DIR}: {exc}\n")


ensure_public_dir()


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 3 — LOGGING (human line log + JSONL event log, always secret-redacted)
# ══════════════════════════════════════════════════════════════════════════════
_LOG_LOCK = threading.Lock()


def ts() -> str:
    return datetime.now().strftime("%H:%M:%S")


def now_ms() -> int:
    return int(time.time() * 1000)


def lp(msg):
    """Baseline human log line (stdout, pm2 friendly), secret-redacted."""
    try:
        print(f"[{ts()}] {CONFIG.redact(msg)}", flush=True)
    except Exception:
        pass


def append_log(event: str, details: str = ""):
    """Baseline JSON-lines event log (kept, semantics unchanged)."""
    try:
        entry = {
            "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "market": MARKET_MODE,
            "event": event,
            "details": CONFIG.redact(details),
        }
        with _LOG_LOCK:
            with open(CONFIG.LOG_FILE, "a", encoding="utf-8") as fh:
                fh.write(json.dumps(entry, ensure_ascii=False) + "\n")
    except Exception:
        pass


def jlog(event: str, **fields):
    """Structured event log. Never contains secrets or full payload bodies."""
    safe = {}
    for key, value in fields.items():
        if key.lower() in ("secret", "hmac_secret", "authorization", "payload", "body"):
            continue
        if isinstance(value, (bytes, bytearray)):
            value = f"<{len(value)} bytes>"
        if isinstance(value, str):
            value = CONFIG.redact(value)
        safe[key] = value
    append_log(event, json.dumps(safe, ensure_ascii=False, default=str))
    if CONFIG.LOG_LEVEL != "quiet":
        detail = " ".join(f"{k}={v}" for k, v in safe.items())
        lp(f"[{event}] {detail}" if detail else f"[{event}]")


def log_important(event: str, details: str = "", print_to_pm2: bool = True):
    """Baseline important-event log (kept)."""
    try:
        line = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [{MARKET_MODE}] {event}"
        if details:
            line += f" {CONFIG.redact(details)}"
        with _LOG_LOCK:
            with open(CONFIG.IMPORTANT_LOG_FILE, "a", encoding="utf-8") as fh:
                fh.write(line + "\n")
    except Exception:
        pass
    try:
        append_log(event, details)
    except Exception:
        pass
    if print_to_pm2:
        lp(f"[{event}] {details}" if details else f"[{event}]")


def log_exception(event: str, exc: BaseException, **fields):
    """Log an exception WITHOUT swallowing it silently (AUTH-A R5)."""
    fields = dict(fields)
    fields["error_type"] = type(exc).__name__
    fields["error"] = CONFIG.redact(str(exc))
    fields["traceback_tail"] = CONFIG.redact(
        "".join(traceback.format_exception_only(type(exc), exc)).strip()
    )
    jlog(event, **fields)


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 4 — HASH / GZIP / HMAC PRIMITIVES (contract critical)
# ══════════════════════════════════════════════════════════════════════════════
def sha256_hex(data) -> str:
    if isinstance(data, str):
        data = data.encode("utf-8")
    return hashlib.sha256(data).hexdigest()


def canonical_json_text(payload: dict) -> str:
    """Canonical JSON serialisation used for the wire payload.

    Key order follows PAYLOAD_FIELDS exactly (frozen contract order); separators
    are compact so the byte stream is reproducible for the server engineer.
    """
    ordered = {}
    for key in PAYLOAD_FIELDS:
        if key in payload:
            ordered[key] = payload[key]
    for key in payload:  # defensive: never drop an unexpected key silently
        if key not in ordered:
            ordered[key] = payload[key]
    return json.dumps(ordered, ensure_ascii=False, separators=(",", ":"))


def gzip_bytes(raw: bytes) -> bytes:
    """Deterministic gzip (mtime=0, level=6, no embedded filename)."""
    buf = io.BytesIO()
    with gzip.GzipFile(fileobj=buf, mode="wb", compresslevel=GZIP_COMPRESS_LEVEL, mtime=0) as gz:
        gz.write(raw)
    return buf.getvalue()


def atomic_write_json(final_path, text):
    """FIX K-15：tmp + fsync + os.replace——主機 poll 唔會再攞到半份 JSON（POSIX/Windows 都原子）。
    失敗即刻 cleanup tmp，唔留 .tmp 墓碑。"""
    d = os.path.dirname(os.path.abspath(final_path)) or "."
    os.makedirs(d, exist_ok=True)
    fd, tmp = tempfile.mkstemp(dir=d, prefix=".tmp-legacy-")
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            f.write(text)
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp, final_path)
    finally:
        try:
            os.unlink(tmp)
        except Exception:
            pass


def gunzip_bytes(raw: bytes) -> bytes:
    with gzip.GzipFile(fileobj=io.BytesIO(raw), mode="rb") as gz:
        return gz.read()


def hmac_sha256_hex(secret: str, payload: bytes) -> str:
    """HMAC-SHA256 over the RAW GZIP BYTES actually sent (frozen contract rule 7)."""
    if isinstance(secret, str):
        secret = secret.encode("utf-8")
    return hmac.new(secret, payload, hashlib.sha256).hexdigest()


def signature_header_value(secret: str, payload: bytes) -> str:
    return "sha256=" + hmac_sha256_hex(secret, payload)


def constant_time_equals(a: str, b: str) -> bool:
    return hmac.compare_digest(str(a), str(b))


def deterministic_jitter(seed_text: str, upper: float) -> float:
    """Reproducible jitter in [0, upper) derived from sha256 (no `random` import)."""
    if upper <= 0:
        return 0.0
    digest = hashlib.sha256(seed_text.encode("utf-8")).digest()
    frac = int.from_bytes(digest[:8], "big") / float(1 << 64)
    return frac * upper


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 5 — W1 NORMALIZE: time rules, fixed point, symbols, canonical bars
# ══════════════════════════════════════════════════════════════════════════════
HK_TZ = zoneinfo.ZoneInfo("Asia/Hong_Kong")
US_TZ = zoneinfo.ZoneInfo("America/New_York")
UTC = timezone.utc

MARKET_TZ = {"HK": HK_TZ, "US": US_TZ}

# Session windows expressed in market-local minutes-of-day.
#   HK : morning 09:30-12:00, afternoon 13:00-16:00 (no bars during lunch)
#   US : regular 09:30-16:00
# A 1-minute bar identified by HHMM is the bar STARTING at HHMM, therefore the
# last valid bar start is (session_end - 1 minute).
SESSION_WINDOWS = {
    # R106:LABEL-F2 — 對齊 GD sessions_config：
    #   HK_STOCK 09:30-12:00(AM) + 13:01-16:08(PM)；港期夜盤 17:01-03:00 由 session_for_minutes 特判 NGT
    #   US_STOCK 04:01-20:00 → PRE 04:01-09:29 / REG 09:30-16:00 / POST 16:01-20:00（閉合端點收）
    "HK": (("AM", 9 * 60 + 31, 12 * 60), ("PM", 13 * 60 + 1, 16 * 60 + 8)),  # P1-06 LAST_RESORT＝GD v7 09:31
    "US": (("PRE", 4 * 60 + 1, 9 * 60 + 30), ("REG", 9 * 60 + 31, 16 * 60), ("POST", 16 * 60 + 1, 20 * 60)),  # P1-06 同 GD labels
}

# ── PER-SYMBOL CLASSIFICATION (外科手術新增，唔郁主 loop) ──────────────
# 用 E 值（時段類型）判時區：
#   E=330 港股 / E=960,975 港期 -> 香港時區
#   其它 (E=390 美股 / E=1380 美期 / E=1440 crypto) -> 美東時區
# 港期 E 值由 960 更新做 975（開市由 HKT 17:15 改做 HKT 17:00）。
# F/E map 同元祖板 classifyBackupType 一致。
SYMBOL_E = {
    "ETH": 1440, "BTC": 1440,
    "VXMAIN": 1380, "CLMAIN": 1380, "SIMAIN": 1380, "HOMAIN": 1380, "RBMAIN": 1380,
    "PLMAIN": 1380, "HEMAIN": 1380, "ZLMAIN": 1380, "ZCMAIN": 1380, "ZSMAIN": 1380,
    "YMMAIN": 1380, "EMDMAIN": 1380, "RTYMAIN": 1380, "GCMAIN": 1380, "1OZMAIN": 1380,
    "ZWMAIN": 1380, "ESMAIN": 1380, "ZMMAIN": 1380, "ALIMAIN": 1380, "PAMAIN": 1380,
    "NGMAIN": 1380, "HGMAIN": 1380, "NQMAIN": 1380, "NKDMAIN": 1380,
    "HTIMAIN": 975, "HHIMAIN": 975, "HSIMAIN": 975, "HBIMAIN": 975,  # 港期 E=975（原 960）
}


def symbol_e(symbol: str) -> int:
    """E 值（時段類型）：GD 三名單先查；否則 SYMBOL_E；再 default 數字→330、字母→390。"""
    s = str(symbol or "").strip().upper()
    # P1-17: 雲端 hk_fut / us_fut / crypto 名單先於內建 map（新品種唔好當美股）
    if CRYPTO_SYMBOLS is not None and s in CRYPTO_SYMBOLS:
        return 1440
    if HK_FUT_SYMBOLS is not None and s in HK_FUT_SYMBOLS:
        return 975
    if US_FUT_SYMBOLS is not None and s in US_FUT_SYMBOLS:
        return 1380
    e = SYMBOL_E.get(s)
    if e is not None:
        return e
    if s.isdigit():
        return 330
    return 390


def symbol_market(symbol: str) -> str:
    """用 E 值判時區：E=330(港股)/960/975(港期) → HK；其它(390/1380/1440) → US。"""
    e = symbol_e(symbol)
    if e in (330, 960, 975):
        return "HK"
    return "US"


def symbol_kind(symbol: str) -> str:
    """symbol 類型：HK_STOCK / HK_FUT / US_STOCK / US_FUT / CRYPTO。"""
    e = symbol_e(symbol)
    if e == 330:
        return "HK_STOCK"
    if e in (960, 975):
        return "HK_FUT"
    if e == 1380:
        return "US_FUT"
    if e == 1440:
        return "CRYPTO"
    return "US_STOCK"


# Per-kind session windows（market-local minutes-of-day）：
#   (start_min, end_min, cross_midnight)
#   HK_STOCK : 09:30-12:00, 13:00-16:00
#   HK_FUT   : 夜期 17:01-03:00（跨日，03:00 收）＋日盤 09:16-12:00 ＋ 13:01-16:30（HHMM 端點收；其餘休息唔收）  # R105:HKFUT4
#   US_STOCK : PRE 04:00-09:30, REG 09:30-16:00, POST 16:00-20:00（pre/post 100% 要收）
#   US_FUT   : 近 24 小時（06:00-05:59 跨日，寬鬆唔誤 reject）
#   CRYPTO   : 24/7（None = 唔 filter）
KIND_SESSION_WINDOWS = {
    # R86:WINDOWS — 完全跟 server R75 tradingWindowsFor 對齊（半開 [start,end)）
    #   HK_STOCK : 09:30-12:00 + 13:00-16:08（16:08 收，同 server 968）
    #   HK_FUT   : 17:01-03:00 跨日 + 09:16-12:00 + 13:01-16:30（同 server 1021/180/556/720/781/990）  # R105:HKFUT5
    #   US_STOCK : 04:01-20:00（同 server 241-1200）
    #   US_FUT   : 18:01-17:00 跨日（同 server 1081/1020；17:01-18:00 CME 休市）
    #   CRYPTO   : 24/7
    "HK_STOCK": ((571, 720, False), (781, 968, False)),  # P1-06 LAST_RESORT＝GD v7 09:31（舊 570＝09:30）
    "HK_FUT": ((1021, 180, True), (556, 720, False), (781, 990, False)),  # R105:HKFUT3 13:01-16:30 閉合（780=13:00 錯）
    "US_STOCK": ((241, 1200, False),),
    "US_FUT": ((1081, 1020, True),),
    "CRYPTO": None,
}


SESSIONS_CFG = None  # R87:EXTCFG — 外部 JSON 載入後嘅統一時間設定（None = 用內建）
CRYPTO_SYMBOLS = None  # R8:GDCRYPTO — GD crypto_symbols 對照（None＝內建 SYMBOL_E map BTC/ETH）
HK_FUT_SYMBOLS = None  # P1-17: GD hk_fut_symbols（None＝只用 SYMBOL_E 兜底）
US_FUT_SYMBOLS = None  # P1-17: GD us_fut_symbols


def _parse_sessions_json(cfg):
    """R87:EXTCFG — 將外部 JSON 轉成 {kind: {"windows":[(s,e,cross)...], "weekend":{dow:...}}}。"""
    _DOW = {"Mon": 0, "Tue": 1, "Wed": 2, "Thu": 3, "Fri": 4, "Sat": 5, "Sun": 6}
    def _m(t):
        try:
            h, mi = t.split(":")
            return int(h) * 60 + int(mi)
        except Exception:
            return 0
    out = {}
    for kind, spec in (cfg.get("sessions") or {}).items():
        wins = []
        for w in spec.get("windows") or []:
            if not isinstance(w, (list, tuple)) or len(w) < 2:
                continue
            st, en = str(w[0]), str(w[1])
            cross = en.endswith("+1")
            if cross:
                en = en[:-2]
            wins.append((_m(st), _m(en), cross))
        raw_weekend = spec.get("weekend")
        weekend = None
        if isinstance(raw_weekend, dict) and raw_weekend:
            weekend = {}
            for dn, rule in raw_weekend.items():
                dow = _DOW.get(dn)
                if dow is None:
                    continue
                if rule == "closed":
                    weekend[dow] = "closed"
                elif isinstance(rule, list):
                    weekend[dow] = [(_m(str(x[0])), _m(str(x[1]).replace("+1", "")), str(x[1]).endswith("+1")) for x in rule if isinstance(x, (list, tuple)) and len(x) >= 2]
                elif rule is None:
                    continue  # omitted day → auto weekend, not open
                else:
                    weekend[dow] = "closed"
        labels = []
        for lb in (spec.get("labels") or []):
            if not isinstance(lb, dict) or not lb.get("code"):
                continue
            _w = lb.get("window")
            if not isinstance(_w, (list, tuple)) or len(_w) < 2:
                continue
            _ls, _le = str(_w[0]), str(_w[1])
            _lcross = _le.endswith("+1")
            if _lcross:
                _le = _le[:-2]
            labels.append({"code": str(lb["code"]), "s": _m(_ls), "e": _m(_le), "cross": _lcross})
        out[kind] = {"windows": wins, "weekend": weekend, "labels": labels}  # F-TIME:LBL-PARSE
    return out


def _absorb_gd_symbol_sets(src):
    """P1-17: 從 GD／cache JSON 吸收 crypto / hk_fut / us_fut 三個 array。空／缺＝唔覆蓋（保留兜底）。"""
    global CRYPTO_SYMBOLS, HK_FUT_SYMBOLS, US_FUT_SYMBOLS
    if not isinstance(src, dict):
        return
    def _as_set(key):
        arr = src.get(key)
        if not isinstance(arr, list) or not arr:
            return None
        return {str(x).strip().upper() for x in arr if str(x).strip()}
    cs, hk, us = _as_set("crypto_symbols"), _as_set("hk_fut_symbols"), _as_set("us_fut_symbols")
    if cs is not None:
        CRYPTO_SYMBOLS = cs
        print(f"[sessions] crypto_symbols: {len(CRYPTO_SYMBOLS)} 隻")
    if hk is not None:
        HK_FUT_SYMBOLS = hk
        print(f"[sessions] hk_fut_symbols: {len(HK_FUT_SYMBOLS)} 隻")
    if us is not None:
        US_FUT_SYMBOLS = us
        print(f"[sessions] us_fut_symbols: {len(US_FUT_SYMBOLS)} 隻")



def _http_get_follow(url, timeout=15, max_hops=5):
    """P2-09：跟跳轉（最多 5 次），Google Drive 大檔確認頁再跟一次。"""
    import re
    import urllib.request
    opener = urllib.request.build_opener(urllib.request.HTTPRedirectHandler)
    current = url
    raw = ""
    for _ in range(max_hops):
        req = urllib.request.Request(current, headers={"User-Agent": "futu-py-sessions/1.0"})
        with opener.open(req, timeout=timeout) as resp:
            raw = resp.read().decode("utf-8", "replace")
            current = resp.geturl() or current
        stripped = raw.lstrip()
        if stripped.startswith("{") or stripped.startswith("["):
            return raw
        m = re.search(r'href="(/uc\?export=download[^"]+)"', raw)
        if m:
            nxt = "https://drive.google.com" + m.group(1).replace("&amp;", "&")
            if nxt == current:
                break
            current = nxt
            continue
        m2 = re.search(r"confirm=([0-9A-Za-z_-]+)", raw)
        if m2 and "id=" in current:
            sep = "&" if "?" in current else "?"
            nxt = current + sep + "confirm=" + m2.group(1)
            if nxt == current:
                break
            current = nxt
            continue
        break
    return raw

def load_sessions_config():
    """R99V3:LOAD — 爬蟲本地獨立：GD fetch → 成功寫 public/gd_sessions.json；GD 攞唔到 → 讀 public 舊檔；
    都冇 → 內建（None）。cache 統一喺 PUBLIC_DIR，唔放第二啲位置、唔靠主程序部機。"""
    global SESSIONS_CFG, CRYPTO_SYMBOLS, HK_FUT_SYMBOLS, US_FUT_SYMBOLS
    gd_url = (getattr(CONFIG, "SESSIONS_JSON_URL", "") or "").strip()
    cache_path = (getattr(CONFIG, "SESSIONS_CACHE_FILE", "") or "").strip()
    if not cache_path:
        cache_path = os.path.join(getattr(CONFIG, "PUBLIC_DIR", ""), "gd_sessions.json")
    # 1) public cache 即時讀入（上次 GD 成功嘅副本，唔使等網絡）
    try:
        with open(cache_path, "r", encoding="utf-8") as f:
            cached = json.load(f)
        parsed = _parse_sessions_json(cached)
        if parsed:
            SESSIONS_CFG = parsed
            _absorb_gd_symbol_sets(cached)  # P1-17
            print(f"[sessions] public cache 載入: {len(parsed)} kinds ({cache_path})")
    except Exception:
        pass
    if not gd_url:
        # FIX P1-18：URL 留白唔准靜靜雞——講明而家食緊 public cache 定內建兜底
        print("[sessions] SESSIONS_JSON_URL 未設定：" + ("食 public cache（來源已喺上面 log）" if SESSIONS_CFG else "⚠️ 冇 cache——全程用內建 LAST_RESORT 兜底表"))
        return
    # 2) GD 更新 → 寫 public cache；GD 攞唔到 → 保留 cache/內建
    try:
        raw = _http_get_follow(gd_url, timeout=15, max_hops=5)
        cfg = json.loads(raw)
        parsed = _parse_sessions_json(cfg)
        if parsed:
            SESSIONS_CFG = parsed
            _absorb_gd_symbol_sets(cfg)  # P1-17
            try:
                os.makedirs(cache_path and os.path.dirname(os.path.abspath(cache_path)) or ".", exist_ok=True)
                tmp = cache_path + ".tmp"
                with open(tmp, "w", encoding="utf-8") as f:
                    json.dump(cfg, f, ensure_ascii=False)
                os.replace(tmp, cache_path)
            except Exception as e:
                print(f"[sessions] public cache 寫入失敗: {e}")
            print(f"[sessions] GD 載入成功: {len(parsed)} kinds（已寫 public cache）")
        else:
            print("[sessions] GD JSON 無有效 sessions，保留 cache/內建")
    except Exception as e:
        print(f"[sessions] GD 載入失敗（保留 cache/內建）: {e}")


def session_for_symbol(symbol: str, minutes: int) -> bool:
    """Bar start (market-local minutes-of-day) 合唔合法（per-symbol kind）。"""
    kind = symbol_kind(symbol)
    _ext = (SESSIONS_CFG or {}).get(kind)  # R87:EXTCFG-SESS
    windows = _ext["windows"] if _ext and _ext.get("windows") else KIND_SESSION_WINDOWS.get(kind)
    if windows is None:  # CRYPTO: 24/7
        return True
    for start, end, cross in windows:
        if cross:
            if minutes >= start or minutes <= end:
                return True
        else:
            if start <= minutes <= end:  # R92:CLOSE — 用戶數字全部收（16:08/12:00/16:30 等收市嗰支都收）
                return True
    return False


def _gd_weekend_bounds(kind):
    """R107:OOS — 由 GD sessions windows 計算週末休市邊界：
    last_end     = 每週最後一支 K 線收市分鐘（有凌晨段 [0,e] 就用 e；冇就用 max(ends)）
    first_start  = 每週第一支 K 線開市分鐘（非凌晨段 min(starts)）
    overnight    = 有冇凌晨段 [0,e]（跨日交易）
    休市範圍 = last_end+1 分鐘 ～ first_start-1 分鐘（唔記錄）。
    返回 (last_end, first_start, overnight) 或 None（冇 GD windows / CRYPTO）。"""
    ext = (SESSIONS_CFG or {}).get(kind)
    if not ext or not ext.get("windows") or kind == "CRYPTO":
        return None
    wins = ext["windows"]
    overnight = [tup[1] for tup in wins if len(tup) >= 2 and tup[0] == 0]
    if not overnight:
        overnight = [tup[1] for tup in wins if len(tup) >= 3 and tup[2] and tup[1] < 480]
    ends = [tup[1] for tup in wins if len(tup) >= 2 and tup[1] < 1440]
    starts = [tup[0] for tup in wins if len(tup) >= 2 and tup[0] > 0]
    if not starts or not ends:
        return None
    last_end = overnight[0] if overnight else max(ends)
    return (last_end, min(starts), bool(overnight))


def _weekday_session_ok(symbol: str, local_dt) -> bool:
    """R107:WEEKEND — 週末休市機制（同 server R75 窗口對齊）。
    local_dt = bar 嘅 market-local aware datetime（HK 系=HKT、US 系=ET）。
    返回 False = 週末休市，唔收。
    優先：GD weekend 欄位（用戶喺 GD 檔編輯）；冇 weekend 欄位就由 GD windows
    自動計（每週最後一支 K 線 +1 分鐘 ～ 每週第一支 K 線 -1 分鐘）；都冇先
    fallback 內建規則（R86/R92 原樣保留）。BTC/ETH：24/7。
    """
    kind = symbol_kind(symbol)
    if kind == "CRYPTO":
        return True  # 24/7
    dow = local_dt.weekday()  # 0=Mon .. 6=Sun
    t = local_dt.hour * 60 + local_dt.minute
    _ext = (SESSIONS_CFG or {}).get(kind)  # R87:EXTCFG-WK
    weekend = _ext.get("weekend") if _ext else None
    if isinstance(weekend, dict) and weekend:
        rule = weekend.get(dow)
        if rule == "closed":
            return False
        if isinstance(rule, list):
            return any(st <= t <= en for (st, en, _c) in rule)  # R92:CLOSE-WK
        # missing/null day rule → auto weekend, not open
    # R107:OOS — 冇 weekend 欄位：由 GD windows 自動計週末休市範圍
    gb = _gd_weekend_bounds(kind)
    if gb is not None:
        last_end, first_start, overnight = gb
        if dow == 5:            # 星期六：跨日市場凌晨段（e<480）先收；否則全日唔收
            return overnight and last_end < 480 and t <= last_end
        if dow == 6:            # 星期日：傍晚開市市場（first_start>=1080）先開；否則唔收
            return first_start >= 1080 and t >= first_start
        if dow == 0:            # 星期一：傍晚開市市場（first_start>=1080）照 windows（跨日全日交易）；
            # 朝早開市市場 first_start-1 前唔收（first_start 嗰支收）
            return True if first_start >= 1080 else (t >= first_start)
        return True             # 星期二至五照窗口（星期五收市由 session_for_symbol 窗口處理）

    # F-TIME:WK-FALLBACK — 由內建 windows 推導週末休市（同 _gd_weekend_bounds 同款邏輯，唔寫死分鐘）
    _bws = KIND_SESSION_WINDOWS.get(kind)
    if _bws:
        _overnight = [e for (s, e, _c) in _bws if s == 0]
        _ends = [e for (s, e, _c) in _bws if e < 1440]
        _starts = [s for (s, e, _c) in _bws if s > 0]
        if _starts and _ends:
            _last_end = _overnight[0] if _overnight else max(_ends)
            _first_start = min(_starts)
            if dow == 5:
                return bool(_overnight) and _last_end < 480 and t <= _last_end
            if dow == 6:
                return _first_start >= 1080 and t >= _first_start
            if dow == 0:
                return True if _first_start >= 1080 else (t >= _first_start)
            return True
    return True


class NormalizeReject(Exception):
    """Raised internally when a raw row cannot be turned into a canonical bar."""

    def __init__(self, reason, **context):
        super().__init__(reason)
        self.reason = reason
        self.context = context


NORMALIZE_STATS = defaultdict(int)


def market_timezone(market: str):
    tz = MARKET_TZ.get(str(market or "").upper())
    if tz is None:
        raise NormalizeReject("UNKNOWN_MARKET", market=market)
    return tz


def market_local_now(market: str) -> datetime:
    return datetime.now(market_timezone(market))


def trade_date_local(market: str, at_ms=None) -> date:
    """Trading-day local date: the market-local calendar date at the crawl instant."""
    if at_ms is None:
        return market_local_now(market).date()
    return datetime.fromtimestamp(at_ms / 1000.0, tz=market_timezone(market)).date()


def parse_hhmm_to_minutes(hhmm, minute_bias: bool = False) -> int:
    """`930`, `0930`, `9:30`, `09:30`, `00:09`, `0009` -> minutes-of-day.

    PATCH BUG-021（K-28）— 舊嘅 1-2 位規則自相矛盾：裸 token <=23 當鐘數（"16"→16:00）、
    >23 又當分鐘（"36"→00:36）。Futubull 剝頭零，"00:09" 可以合法變 "9" 到嘴，
    舊碼會 stamp 成 09:00（遲成九個鐘），仲會俾 STRICT_SESSION_FILTER 彈 OUT_OF_SESSION。

    而家公約講到明：
      * 3-4 位 token 永遠 zero-padded HHMM        -> "0009" = 00:09
      * 有冒號 token 永遠 HH:MM                   -> "0:09"  = 00:09
      * 裸 1-2 位 token 跟 minute_bias：
          minute_bias=True  -> 凌晨 00 時嘅分鐘   ("9" -> 00:09)
          minute_bias=False -> 舊行為鐘數          ("9" -> 09:00)
    生產者應該搬去明確 padded 式。
    """
    raw = str(hhmm if hhmm is not None else "").strip()
    if not raw:
        raise NormalizeReject("EMPTY_HHMM")
    if ":" in raw:
        parts = raw.split(":")
        if len(parts) != 2 or not parts[0].isdigit() or not parts[1].isdigit():
            raise NormalizeReject("BAD_HHMM_FORMAT", hhmm=raw)
        hh, mm = int(parts[0]), int(parts[1])
    else:
        if not raw.isdigit() or len(raw) > 4:
            raise NormalizeReject("BAD_HHMM_FORMAT", hhmm=raw)
        if len(raw) <= 2:
            _n2 = int(raw)
            if minute_bias:
                hh, mm = 0, _n2          # 明確：凌晨 00 時之後幾多分鐘
            elif _n2 > 23:
                hh, mm = 0, _n2          # 舊 futu 剝零凌晨式（"36"）
            else:
                hh, mm = _n2, 0          # 舊鐘數式（"16" -> 16:00）
        else:
            padded = raw.zfill(4)        # "930" -> "0930"
            hh, mm = int(padded[:2]), int(padded[2:])
    if hh > 23 or mm > 59:
        raise NormalizeReject("HHMM_OUT_OF_RANGE", hhmm=raw)
    return hh * 60 + mm


def session_for_minutes(market: str, minutes: int):
    """Return the session code ('AM'|'PM'|'REG'|'PRE'|'POST'|'NGT') owning this bar start, else None.
    F-TIME:LABEL — label 由 GD sessions 派生（HK=HK_STOCK AM/PM＋HK_FUT 凌晨 NGT；US=拍板 3 段）；GD 冇先內建兜底。"""
    m = str(market or "").upper()
    if m == "HK":
        _lb_hkstk = ((SESSIONS_CFG or {}).get("HK_STOCK") or {}).get("labels")
        _lb_hkfut = ((SESSIONS_CFG or {}).get("HK_FUT") or {}).get("labels")
        if _lb_hkfut or _lb_hkstk:
            # F-TIME:LABEL2-PY — GD labels 話事（NGT 先，再 AM/PM）；labels 有載入就唔 fallback 舊寫死表
            for _lb in (_lb_hkfut or []):
                if (_lb.get("cross") and (minutes >= _lb["s"] or minutes <= _lb["e"])) or (not _lb.get("cross") and _lb["s"] <= minutes <= _lb["e"]):
                    return _lb["code"]
            for _lb in (_lb_hkstk or []):
                if _lb["s"] <= minutes <= _lb["e"]:
                    return _lb["code"]
            return None
        _hkstk = ((SESSIONS_CFG or {}).get("HK_STOCK") or {}).get("windows")
        _hkfut = ((SESSIONS_CFG or {}).get("HK_FUT") or {}).get("windows")
        if _hkfut:
            for _s, _e, _c in _hkfut:
                if _e == 1440 and minutes >= _s:  # 夜期上半夜段（17:01-24:00 展開後 [s,1440]）
                    return "NGT"
                if _s == 0 and minutes <= _e:      # 夜期凌晨段（17:01-03:00+1 展開後 [0,e]）
                    return "NGT"
        if _hkstk:
            for _i, (_s, _e, _c) in enumerate(_hkstk):
                if _s <= minutes <= _e:
                    return "AM" if _i == 0 else "PM"  # P2-06／P0-05：午前午後由窗序派生，唔寫死 13:00
        if _hkfut or _hkstk:
            return None  # F-TIME:LABEL GD 已載入 = 完全由 GD 話事（唔 fallback 舊寫死表）
        # LAST_RESORT 兜底（GD 完全冇先到呢度）
        if minutes >= 17 * 60 + 1 or minutes <= 3 * 60:
            return "NGT"
        for code, start, end in SESSION_WINDOWS.get(m, ()):
            if start <= minutes <= end:
                return code
        return None
    _lb_us = ((SESSIONS_CFG or {}).get("US_STOCK") or {}).get("labels")
    if _lb_us:
        # F-TIME:LABEL2-PY2 — GD labels 話事（PRE/REG/POST）
        for _lb in _lb_us:
            if _lb["s"] <= minutes <= _lb["e"]:
                return _lb["code"]
        return None
    _usstk = ((SESSIONS_CFG or {}).get("US_STOCK") or {}).get("windows")
    if _usstk:
        # P0-05：有 GD windows 但冇 labels → 唔寫死 570/571/960 切三段；大窗內標 REG
        for _s, _e, _c in _usstk:
            if _c:
                if minutes >= _s or minutes <= _e:
                    return "REG"
            elif _s <= minutes <= _e:
                return "REG"
        return None
    for code, start, end in SESSION_WINDOWS.get(m, ()):
        if start <= minutes <= end:
            return code
    return None


# R44:BACKFILL — tolerance for the future-bar rollback in derive_bar_start_utc_ms.
# A legitimate bar start is never more than a few seconds ahead of the crawl instant;
# anything further ahead is a next-day backfill of the previous session's closing bars.
BACKFILL_SKEW_MS = 5 * 60 * 1000


def derive_bar_start_utc_ms(symbol, hhmm, crawl_ctx) -> int:
    """Derive the canonical bar start (UTC ms) from trading date + HHMM + session.

    PER-SYMBOL：時區由 symbol 嘅 E 值判定（唔再靠 worker market）——
      港股/港期(E=330/960/975) -> 香港時區；美股/美期/crypto -> 美東時區。
    FORBIDDEN: 用 capture wall-clock 當 bar 時間。
    Formula (contract <bar_start_formula>):
        bar_start_utc_ms = market_local_midnight_utc + hhmm_minutes*60000 - tz_offset_ms
    trade_date：crossMidnight（元祖板邏輯）——bar 屬於跨午夜 session 嘅凌晨段時，
      trade_date 推返前一日（session 開始日）。
    """
    market_up = symbol_market(symbol)   # per-symbol 時區
    tz = market_timezone(market_up)
    # FIX K-28（BUG-021）：Futubull 剝頭零——裸 1-2 位 token 落喺 00:00-00:23 窗係歧義；
    # 當佢係「凌晨 00 時後嘅分鐘」並 log 低，等真 dump 可以埋嚟覆核呢個假設。
    _raw_hhmm = str(hhmm if hhmm is not None else "").strip()
    _minute_bias = (len(_raw_hhmm) <= 2 and _raw_hhmm.isdigit() and int(_raw_hhmm) <= 23)  # isdigit 鞏固：怪 token 唔准炸 int()（較清單原稿加上）
    if _minute_bias:
        log_important("HHMM_AMBIGUOUS", details=f"bare token {_raw_hhmm!r} parsed as 00:{int(_raw_hhmm):02d}")
    minutes = parse_hhmm_to_minutes(hhmm, minute_bias=_minute_bias)
    # R69:APP-HKT — app 統一用 HKT 顯示 K 線時間。US symbols（美股/美期/crypto）抓到嘅
    # HHMM 係 HKT 牆鐘而唔係 ET：錨定「唔遲過 crawl 時刻（+skew）嘅最近一次 HKT 出現」
    # 直接得出精確 UTC bar start。HKT 固定 UTC+8（無 DST）；ET 只出現喺 session filter
    # 嘅 zoneinfo 轉換，EDT/EST 冬夏令自動適應——無需人手 ±12/±13 小時。
    if CONFIG.BAR_TIME_DISPLAY == "HKT" and market_up == "US":
        # FIX-MIDNIGHT — 錨點改用真實 capture 時刻（crawl_once normalize 前注入）：
        # 舊版用 loop_ts（round 開始時刻）——跨 HKT 午夜嘅 round 會將 00:0x bar 個日期當咗琴日 →
        # BTC/ETH 00:00-00:30 全部 stamp 早 24 小時 → server V2 卡停喺 23:59。
        # 真正 backfill（比 capture 遲 >5 分鐘）照樣減一日；冇 capture 欄位（self-test）fallback 舊行為。
        cap_ms = getattr(crawl_ctx, "capture_ts_ms", None) or getattr(crawl_ctx, "loop_ts_ms", None) or now_ms()
        now_hkt = datetime.fromtimestamp(cap_ms / 1000.0, tz=HK_TZ)
        cand = now_hkt.replace(hour=minutes // 60, minute=minutes % 60, second=0, microsecond=0)
        if (cand - now_hkt).total_seconds() * 1000 > BACKFILL_SKEW_MS:
            cand -= timedelta(days=1)  # 屬前一日（跨午夜／補回 bar）
        if CONFIG.STRICT_SESSION_FILTER:
            et = cand.astimezone(US_TZ)
            if not session_for_symbol(symbol, et.hour * 60 + et.minute):
                raise NormalizeReject("OUT_OF_SESSION", symbol=str(symbol), hhmm=str(hhmm),
                                      et_hhmm=f"{et.hour:02d}{et.minute:02d}", market=market_up)
            # R86:WEEKEND-US 週末休市（US 系用 ET weekday）
            if not _weekday_session_ok(symbol, et):
                # R8:WK-BACK — 週末 stale bars（上星期五尾段 dump 重複出現）錨返上一個合法 session 日（最多 4 日）
                _fixed = None
                for _back in range(1, 5):
                    _c2 = cand - timedelta(days=_back)
                    _et2 = _c2.astimezone(US_TZ)
                    if session_for_symbol(symbol, _et2.hour * 60 + _et2.minute) and _weekday_session_ok(symbol, _et2):
                        _fixed = _c2
                        break
                if _fixed is None:
                    raise NormalizeReject("WEEKEND_CLOSED", symbol=str(symbol), hhmm=str(hhmm),
                                          local=f"{et.strftime('%a %H:%M')}", market=market_up)
                cand = _fixed
        return int(cand.timestamp() * 1000)

    if not session_for_symbol(symbol, minutes) and CONFIG.STRICT_SESSION_FILTER:
        raise NormalizeReject("OUT_OF_SESSION", symbol=str(symbol), hhmm=str(hhmm), market=market_up)

    # trade_day 用 symbol 嘅 market 時區計（唔用 worker market 嘅日期）
    # P1-03: 同美股路對齊——優先真實 capture 時刻，唔好用 round 開始嘅 loop_ts 令 00:05 早一日
    stamp_ms = getattr(crawl_ctx, "capture_ts_ms", None) or getattr(crawl_ctx, "loop_ts_ms", None) or now_ms()
    trade_day = trade_date_local(market_up, stamp_ms)
    if isinstance(trade_day, datetime):
        trade_day = trade_day.date()
    if not isinstance(trade_day, date):
        raise NormalizeReject("BAD_TRADE_DATE", trade_date=str(trade_day))

    # crossMidnight（元祖板 computeSessionKey 同款）：凌晨段 bar 屬前一日 session
    # P1-03: 有 capture_ts 時用當日牆鐘（00:05 喺 0:06 收到 = 當日），唔再 -1 日。
    # 無 capture（self-test）維持舊 session-day 行為。
    kind = symbol_kind(symbol)
    windows = ((SESSIONS_CFG or {}).get(kind) or {}).get("windows") or KIND_SESSION_WINDOWS.get(kind) or ()  # F-TIME:XDAY GD 優先
    if not getattr(crawl_ctx, "capture_ts_ms", None):
        for start, end, cross in windows:
            if cross and minutes < end and minutes < start:
                trade_day = trade_day - timedelta(days=1)
                break

    local_dt = datetime(
        trade_day.year, trade_day.month, trade_day.day, minutes // 60, minutes % 60, 0, tzinfo=tz
    )
    # R44:BACKFILL — 換市後第一輪會補回上一個交易日收市尾段 bar（例如 HK 1558/1559/1600/1608，
    # 對備份 Kline 重要、唔可以丟）。舊邏輯用本輪 crawl 日期 stamp 所有 bar，令補回 bar 被當成
    # 「今天的未來 bar」（server 側出現 15:59 標籤／污染今日 session）。修正：若 bar 起點超前
    # crawl 時刻多過 BACKFILL_SKEW_MS，逐日推返前一日，直到唔再係未來（歸返佢真正屬嘅交易日）。
    crawl_ms = stamp_ms if stamp_ms else int(datetime.now(tz).timestamp() * 1000)
    _backfill_guard = 0
    while int(local_dt.timestamp() * 1000) > crawl_ms + BACKFILL_SKEW_MS and _backfill_guard < 10:
        local_dt -= timedelta(days=1)
        _backfill_guard += 1
    # R86:WEEKEND-HK 週末休市（HK 系用 HKT weekday）
    if CONFIG.STRICT_SESSION_FILTER and not _weekday_session_ok(symbol, local_dt):
        # R8:WK-BACK-HK — 週末 stale bars 錨返上一個合法 session 日（最多 4 日）
        _fixed = None
        for _back in range(1, 5):
            _c2 = local_dt - timedelta(days=_back)
            if session_for_symbol(symbol, _c2.hour * 60 + _c2.minute) and _weekday_session_ok(symbol, _c2):
                _fixed = _c2
                break
        if _fixed is None:
            raise NormalizeReject("WEEKEND_CLOSED", symbol=str(symbol), hhmm=str(hhmm),
                                  local=f"{local_dt.strftime('%a %H:%M')}", market=market_up)
        local_dt = _fixed
    return int(local_dt.timestamp() * 1000)


def bar_start_to_local_string(market: str, bar_start_utc_ms: int) -> str:
    tz = market_timezone(market)
    return datetime.fromtimestamp(bar_start_utc_ms / 1000.0, tz=tz).strftime("%Y-%m-%d %H:%M:%S%z")


# ── fixed-point conversion (round-half-up, exact decimal-string arithmetic) ───
_DECIMAL_RE = re.compile(r"^([+-]?)(\d*)(?:\.(\d*))?$")
_SCIENTIFIC_RE = re.compile(r"^([+-]?)(\d*)(?:\.(\d*))?[eE]([+-]?\d+)$")


def _decimal_string(value) -> str:
    """Return a plain (non-scientific) decimal string for int/float/str input."""
    if isinstance(value, bool):
        raise NormalizeReject("BAD_NUMBER_TYPE", value=str(value))
    if isinstance(value, int):
        return str(value)
    if isinstance(value, float):
        if value != value or value in (float("inf"), float("-inf")):
            raise NormalizeReject("NON_FINITE_NUMBER", value=str(value))
        text = repr(value)
    else:
        text = str(value if value is not None else "").strip().replace(",", "").replace("_", "")
    if not text:
        raise NormalizeReject("EMPTY_NUMBER")
    m = _SCIENTIFIC_RE.match(text)
    if m:
        sign, int_part, frac_part, exp = m.group(1), m.group(2) or "0", m.group(3) or "", int(m.group(4))
        digits = int_part + frac_part
        point = len(int_part) + exp
        if point <= 0:
            digits = "0" * (-point) + digits
            point = 0
        if point >= len(digits):
            digits = digits + "0" * (point - len(digits))
        text = f"{sign}{digits[:point] or '0'}.{digits[point:] or '0'}"
    return text


def _to_scaled_int(value, scale: int, field: str = "") -> int:
    """Round-half-away-from-zero to the nearest 1/scale, returned as an integer.

    Exact string arithmetic — never float rounding — so 1.00005 * 10000 == 10001.
    """
    text = _decimal_string(value)
    m = _DECIMAL_RE.match(text)
    if not m:
        raise NormalizeReject("BAD_NUMBER_FORMAT", field=field, value=text)
    sign, int_part, frac_part = m.group(1), m.group(2) or "0", m.group(3) or ""
    if int_part == "" and frac_part == "":
        raise NormalizeReject("BAD_NUMBER_FORMAT", field=field, value=text)

    digits = int(scale)
    if digits <= 0:
        raise NormalizeReject("BAD_SCALE", field=field, scale=scale)
    ndp = len(str(digits)) - 1  # 10000 -> 4 decimals, 100 -> 2 decimals
    if 10 ** ndp != digits:
        # Non power-of-ten scale: fall back to exact integer multiplication.
        numerator = int((int_part + frac_part) or "0") * digits
        denominator = 10 ** len(frac_part)
        scaled, remainder = divmod(numerator, denominator)
        if remainder * 2 >= denominator:
            scaled += 1
    else:
        frac_keep = (frac_part + "0" * (ndp + 1))[: ndp + 1]
        scaled = int((int_part or "0") + frac_keep[:ndp]) if ndp else int(int_part or "0")
        round_digit = int(frac_keep[ndp])
        if round_digit >= 5:  # round half away from zero on the magnitude
            scaled += 1
    result = -scaled if sign == "-" else scaled
    if abs(result) > MAX_SAFE_INT:
        raise NormalizeReject("VALUE_EXCEEDS_SAFE_INTEGER", field=field, value=text)
    return int(result)


def to_fixed_point_price(f) -> int:
    """PRICE_SCALE fixed point (default 10000, i.e. 0.0001 tick), round-half-up."""
    return _to_scaled_int(f, CONFIG.PRICE_SCALE, field="price")


def to_fixed_point_amount(f) -> int:
    """AMOUNT_SCALE fixed point (default 100, i.e. 0.01 minor unit), round-half-up."""
    return _to_scaled_int(f, CONFIG.AMOUNT_SCALE, field="amount")


def to_integer_volume(v) -> int:
    """Volume is a share/contract count: round-half-up to a whole integer."""
    return _to_scaled_int(v, 1, field="volume")


def normalize_symbol(raw_symbol: str, market: str) -> str:
    """HK: pure numeric padded to 5 digits (700 -> 00700). US: as-is."""
    symbol = str(raw_symbol or "").strip()
    if not symbol:
        raise NormalizeReject("EMPTY_SYMBOL")
    symbol = re.sub(r"\s+", "", symbol)
    if str(market or "").upper() == "HK" and symbol.isdigit():
        symbol = symbol.zfill(5) if len(symbol) <= 5 else symbol
    return symbol


class CrawlContext(object):
    """CrawlContext = {market, trade_date_local, session, loop_ts_ms, bar_count_ui}"""

    # FIX-MIDNIGHT — capture_ts_ms = 真實 capture 時刻（normalize 前一刻注入；跨午夜判定用）
    __slots__ = ("market", "trade_date_local", "session", "loop_ts_ms", "bar_count_ui", "capture_ts_ms")

    def __init__(self, market, trade_date_local_value, session, loop_ts_ms, bar_count_ui, capture_ts_ms=None):
        self.market = str(market or "").upper()
        self.trade_date_local = trade_date_local_value
        self.session = session
        self.loop_ts_ms = int(loop_ts_ms)
        self.bar_count_ui = int(bar_count_ui)
        self.capture_ts_ms = int(capture_ts_ms) if capture_ts_ms is not None else None

    @classmethod
    def for_now(cls, market, bar_count_ui=None, loop_ts_ms=None, trade_date=None):
        market_up = str(market or "").upper()
        stamp = int(loop_ts_ms if loop_ts_ms is not None else now_ms())
        local_dt = datetime.fromtimestamp(stamp / 1000.0, tz=market_timezone(market_up))
        session = session_for_minutes(market_up, local_dt.hour * 60 + local_dt.minute)
        if session is None:
            session = "AM" if market_up == "HK" and local_dt.hour < 12 else (
                "PM" if market_up == "HK" else "REG"
            )
        return cls(
            market_up,
            trade_date if trade_date is not None else local_dt.date(),
            session,
            stamp,
            int(bar_count_ui if bar_count_ui is not None else CONFIG.KLINE_BAR_COUNT),
        )

    def to_dict(self):
        return {
            "market": self.market,
            "trade_date_local": self.trade_date_local.isoformat()
            if isinstance(self.trade_date_local, date)
            else str(self.trade_date_local),
            "session": self.session,
            "loop_ts_ms": self.loop_ts_ms,
            "bar_count_ui": self.bar_count_ui,
        }

    def __repr__(self):
        return f"CrawlContext({self.to_dict()})"


def make_canonical_bar(symbol, bar_start_utc_ms, open_ticks, high_ticks, low_ticks,
                       close_ticks, volume, amount_minor, is_final=False, revision=1):
    return {
        "symbol": symbol,
        "timeframe_sec": TIMEFRAME_SEC,
        "bar_start_utc_ms": int(bar_start_utc_ms),
        "open": int(open_ticks),
        "high": int(high_ticks),
        "low": int(low_ticks),
        "close": int(close_ticks),
        "volume": int(volume),
        "amount": int(amount_minor),
        "is_final": bool(is_final),
        "revision": int(revision),
    }


def normalize_bar(raw_symbol: str, raw_data: dict, crawl_ctx: CrawlContext):
    """raw {T,O,C,H,L,V,A} -> CanonicalBar dict, or None when the row is invalid.

    Never raises to the caller and never crashes the crawl loop: every rejection
    is counted and logged with a structured reason.
    """
    try:
        market = getattr(crawl_ctx, "market", "") or CONFIG.MARKET_MODE
        symbol = normalize_symbol(raw_symbol, market)
        data = raw_data or {}
        bar_start = derive_bar_start_utc_ms(symbol, data.get("T", ""), crawl_ctx)

        open_ticks = to_fixed_point_price(data.get("O", ""))
        high_ticks = to_fixed_point_price(data.get("H", ""))
        low_ticks = to_fixed_point_price(data.get("L", ""))
        close_ticks = to_fixed_point_price(data.get("C", ""))
        volume = to_integer_volume(data.get("V", "") or 0)
        amount_minor = to_fixed_point_amount(data.get("A", "") or 0)

        # 成交額缺失（App legend 有時無 A 欄）→ 用 C×V fallback（baseline server
        # 同款：amt=close*vol）。唔好送 0，否則 server 計 turnover 用低價股 close×vol
        # 令 ratio/burst 爆大（6056x 等）。
        if amount_minor == 0 and close_ticks > 0 and volume > 0:
            try:
                _c = float(data.get("C", "") or 0)
                _v = float(data.get("V", "") or 0)
                if _c > 0 and _v > 0:
                    amount_minor = to_fixed_point_amount(_c * _v)
                    NORMALIZE_STATS["amount_fallback_cxv"] += 1
            except Exception:
                pass

        if volume < 0 or amount_minor < 0:
            raise NormalizeReject("NEGATIVE_VOLUME_OR_AMOUNT", symbol=symbol)

        hi_expected = max(open_ticks, close_ticks, high_ticks, low_ticks)
        lo_expected = min(open_ticks, close_ticks, high_ticks, low_ticks)
        if high_ticks != hi_expected or low_ticks != lo_expected:
            # Repair (never drop real market data) and record the anomaly.
            NORMALIZE_STATS["ohlc_repaired"] += 1
            jlog(
                "NORMALIZE_OHLC_REPAIRED",
                symbol=symbol,
                bar_start_utc_ms=bar_start,
                high_in=high_ticks,
                low_in=low_ticks,
                high_out=hi_expected,
                low_out=lo_expected,
            )
            high_ticks, low_ticks = hi_expected, lo_expected

        NORMALIZE_STATS["accepted"] += 1
        return make_canonical_bar(
            symbol, bar_start, open_ticks, high_ticks, low_ticks, close_ticks,
            volume, amount_minor, is_final=False, revision=1,
        )
    except NormalizeReject as rej:
        NORMALIZE_STATS[f"rejected_{rej.reason.lower()}"] += 1
        NORMALIZE_STATS["rejected"] += 1
        # 精準修正：rej.context 可能已經有 symbol（例如 OUT_OF_SESSION 傳咗 symbol=str(symbol)），
        # 唔可以再顯式傳 symbol= 落 jlog（會 keyword 撞兩次）。
        # 合併 context 時若已有 symbol 就用 context 嘅，否則用 raw_symbol。
        ctx = dict(rej.context)
        if "symbol" not in ctx:
            ctx["symbol"] = str(raw_symbol)
        jlog("NORMALIZE_REJECT", reason=rej.reason, **ctx)
        return None
    except Exception as exc:  # defensive: normalization must never kill the loop
        NORMALIZE_STATS["rejected_internal"] += 1
        NORMALIZE_STATS["rejected"] += 1
        log_exception("NORMALIZE_INTERNAL_ERROR", exc, symbol=str(raw_symbol))
        return None


def normalize_round(raw_items, crawl_ctx: CrawlContext):
    """Normalize one crawl round.

    * de-duplicates (symbol, bar_start) inside the round, keeping the LATEST
      capture (raw_items must be in capture order),
    * marks is_final: the newest bar of each symbol this round is NOT final, all
      older bars of that symbol are final,
    * returns bars sorted ascending by bar_start_utc_ms (then symbol).
    """
    latest = {}
    order = 0
    for item in raw_items or []:
        raw_symbol = item.get("symbol") if isinstance(item, dict) else None
        raw_data = item.get("data") if isinstance(item, dict) else None
        bar = normalize_bar(raw_symbol, raw_data or {}, crawl_ctx)
        if bar is None:
            continue
        key = (bar["symbol"], bar["bar_start_utc_ms"])
        order += 1
        latest[key] = (order, bar)  # later capture overwrites earlier capture

    newest_by_symbol = {}
    for (symbol, bar_start) in latest.keys():
        prev = newest_by_symbol.get(symbol)
        if prev is None or bar_start > prev:
            newest_by_symbol[symbol] = bar_start

    bars = []
    for (symbol, bar_start), (_ord, bar) in latest.items():
        bar["is_final"] = bar_start < newest_by_symbol.get(symbol, bar_start)
        bars.append(bar)
    bars.sort(key=lambda b: (b["bar_start_utc_ms"], b["symbol"]))
    return bars


def bar_identity(bar) -> tuple:
    return (bar["symbol"], int(bar["timeframe_sec"]), int(bar["bar_start_utc_ms"]))


def bar_content_hash(bar) -> str:
    """Content hash EXCLUDING is_final/revision (they are state, not content)."""
    payload = [
        bar["symbol"],
        int(bar["timeframe_sec"]),
        int(bar["bar_start_utc_ms"]),
        int(bar["open"]),
        int(bar["high"]),
        int(bar["low"]),
        int(bar["close"]),
        int(bar["volume"]),
        int(bar["amount"]),
    ]
    return sha256_hex(json.dumps(payload, ensure_ascii=False, separators=(",", ":")))


def canonical_bar_row(bar) -> list:
    """Frozen wire row order: symbol, tf, start, o, h, l, c, v, amount, final, rev."""
    return [
        bar["symbol"],
        int(bar["timeframe_sec"]),
        int(bar["bar_start_utc_ms"]),
        int(bar["open"]),
        int(bar["high"]),
        int(bar["low"]),
        int(bar["close"]),
        int(bar["volume"]),
        int(bar["amount"]),
        bool(bar["is_final"]),
        int(bar["revision"]),
    ]


def build_canonical_payload(producer_id, batch_id, sequence, market, bars,
                            captured_at_utc_ms, watermark_utc_ms) -> dict:
    return {
        "schema_version": SCHEMA_VERSION,
        "producer_id": producer_id,
        "batch_id": batch_id,
        "sequence": int(sequence),
        "market": market,
        "captured_at_utc_ms": int(captured_at_utc_ms),
        "watermark_utc_ms": int(watermark_utc_ms),
        "bars": [canonical_bar_row(b) for b in bars],
    }


def should_finalise(prev_obs, cur_obs) -> bool:
    """True when THIS observation is the one allowed finalisation of an identity.

    prev_obs : stored bar_state ({revision, payload_hash, last_final_emitted}) or None
    cur_obs  : the freshly observed canonical bar ({is_final: bool, ...})
    Rule (AUTH-A <is_final_rules> #2 and #5): an identity may be finalised exactly
    once — only if it is now final and no final was emitted for it before.
    """
    if not cur_obs:
        return False
    cur_final = bool(cur_obs.get("is_final")) if isinstance(cur_obs, dict) else bool(
        getattr(cur_obs, "is_final", False)
    )
    if not cur_final:
        return False
    if not prev_obs:
        return True
    if isinstance(prev_obs, dict):
        already = bool(prev_obs.get("last_final_emitted"))
    else:
        already = bool(getattr(prev_obs, "last_final_emitted", False))
    return not already


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 6 — W2 OUTBOX: durable SQLite delivery queue + producer/bar state
#   PRAGMA journal_mode=WAL, synchronous=FULL, busy_timeout; every write inside
#   BEGIN IMMEDIATE so a watchdog kill / power loss can never corrupt the DB.
# ══════════════════════════════════════════════════════════════════════════════
OUTBOX_SCHEMA_VERSION = 1

_SCHEMA_STATEMENTS = (
    """
    CREATE TABLE IF NOT EXISTS outbox (
        sequence            INTEGER PRIMARY KEY,
        batch_id            TEXT    UNIQUE NOT NULL,
        payload             BLOB    NOT NULL,
        payload_sha256      TEXT    NOT NULL,
        created_at_ms       INTEGER NOT NULL,
        attempts            INTEGER NOT NULL DEFAULT 0,
        next_attempt_at_ms  INTEGER NOT NULL,
        committed_at_ms     INTEGER,
        last_error          TEXT,
        suspect             INTEGER NOT NULL DEFAULT 0
    )
    """,
    "CREATE INDEX IF NOT EXISTS idx_outbox_pending ON outbox(committed_at_ms, sequence)",
    "CREATE INDEX IF NOT EXISTS idx_outbox_pending_v2 ON outbox(committed_at_ms, attempts, sequence)",  # FIX K-07：cap 過濾用
    "CREATE INDEX IF NOT EXISTS idx_outbox_committed_at ON outbox(committed_at_ms)",
    """
    CREATE TABLE IF NOT EXISTS producer_state (
        key         TEXT PRIMARY KEY,
        value       TEXT NOT NULL,
        updated_at_ms INTEGER NOT NULL
    )
    """,
    """
    CREATE TABLE IF NOT EXISTS bar_state (
        symbol              TEXT    NOT NULL,
        timeframe_sec       INTEGER NOT NULL,
        bar_start_utc_ms    INTEGER NOT NULL,
        payload_hash        TEXT    NOT NULL,
        revision            INTEGER NOT NULL,
        last_final_emitted  INTEGER NOT NULL DEFAULT 0,
        updated_at_ms       INTEGER NOT NULL,
        PRIMARY KEY (symbol, timeframe_sec, bar_start_utc_ms)
    )
    """,
    "CREATE INDEX IF NOT EXISTS idx_bar_state_updated ON bar_state(updated_at_ms)",
)


class OutboxRow(object):
    """OutboxRow = {sequence, batch_id, payload(gzip bytes), payload_sha256,
    created_at_ms, attempts, next_attempt_at_ms, committed_at_ms, last_error}"""

    __slots__ = ("sequence", "batch_id", "payload", "payload_sha256", "created_at_ms",
                 "attempts", "next_attempt_at_ms", "committed_at_ms", "last_error")

    def __init__(self, sequence, batch_id, payload, payload_sha256, created_at_ms,
                 attempts, next_attempt_at_ms, committed_at_ms, last_error):
        self.sequence = int(sequence)
        self.batch_id = str(batch_id)
        self.payload = bytes(payload) if payload is not None else b""
        self.payload_sha256 = str(payload_sha256)
        self.created_at_ms = int(created_at_ms)
        self.attempts = int(attempts or 0)
        self.next_attempt_at_ms = int(next_attempt_at_ms or 0)
        self.committed_at_ms = int(committed_at_ms) if committed_at_ms is not None else None
        self.last_error = last_error

    @classmethod
    def from_sqlite(cls, row):
        return cls(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8])

    @property
    def is_committed(self) -> bool:
        return self.committed_at_ms is not None

    def meta(self) -> dict:
        """Loggable metadata only — the payload bytes are never logged."""
        return {
            "sequence": self.sequence,
            "batch_id": self.batch_id,
            "payload_bytes": len(self.payload),
            "payload_sha256": self.payload_sha256,
            "created_at_ms": self.created_at_ms,
            "attempts": self.attempts,
            "next_attempt_at_ms": self.next_attempt_at_ms,
            "committed_at_ms": self.committed_at_ms,
            "last_error": self.last_error,
        }

    def __repr__(self):
        return f"OutboxRow(seq={self.sequence}, batch_id={self.batch_id}, attempts={self.attempts})"


class Outbox(object):
    """Durable, crash-safe delivery queue. One instance per process."""

    def __init__(self, db_path=None, cfg=None, producer_id=None):
        self.cfg = cfg or CONFIG
        self.db_path = db_path or self.cfg.OUTBOX_DB_PATH
        self.producer_id = producer_id if producer_id is not None else self.cfg.PRODUCER_ID
        self._lock = threading.RLock()
        parent = os.path.dirname(os.path.abspath(self.db_path))
        if parent:
            os.makedirs(parent, exist_ok=True)
        self._conn = sqlite3.connect(self.db_path, timeout=max(1.0, self.cfg.OUTBOX_BUSY_TIMEOUT_MS / 1000.0),
                                     isolation_level=None, check_same_thread=False)
        self._configure_connection()
        self.migrate()

    # ── connection / schema ───────────────────────────────────────────────────
    def _configure_connection(self):
        cur = self._conn.cursor()
        cur.execute("PRAGMA journal_mode=WAL")
        cur.execute("PRAGMA synchronous=FULL")
        cur.execute(f"PRAGMA busy_timeout={int(self.cfg.OUTBOX_BUSY_TIMEOUT_MS)}")
        cur.execute("PRAGMA foreign_keys=ON")
        cur.close()

    def migrate(self):
        with self._lock:
            self._begin()
            try:
                for stmt in _SCHEMA_STATEMENTS:
                    self._conn.execute(stmt)
                # IS-HOTFIX-4 (DATA-LOSS-1 2026-08-19): idempotent migrate for
                # pre-existing DBs created before the suspect column existed.
                _cols = {r[1] for r in self._conn.execute("PRAGMA table_info(outbox)").fetchall()}
                if "suspect" not in _cols:
                    self._conn.execute("ALTER TABLE outbox ADD COLUMN suspect INTEGER NOT NULL DEFAULT 0")
                self._set_state_locked("schema_version", str(OUTBOX_SCHEMA_VERSION), overwrite=False)
                self._set_state_locked("next_sequence", "1", overwrite=False)
                self._set_state_locked("watermark_utc_ms", "0", overwrite=False)
                # FIX K-09：身份要 fail-closed——舊 DB 有貨兼屬於第二個 producer 就開機即停，
                # 唔准靜靜雞幫個簿改姓（要操作員清倉/歸檔，或者俾每機自己嘅 OUTBOX_DB_PATH）
                _stored_id = self._get_state_locked("producer_id", "")
                _row_count = self._conn.execute("SELECT COUNT(*) FROM outbox").fetchone()[0]
                _state_count = self._conn.execute("SELECT COUNT(*) FROM bar_state").fetchone()[0]
                if _stored_id and _stored_id != self.producer_id and (_row_count or _state_count):
                    raise RuntimeError(
                        f"outbox belongs to producer {_stored_id}; configured producer is {self.producer_id}"
                    )
                self._set_state_locked("producer_id", self.producer_id or "", overwrite=True)
                self._conn.execute("COMMIT")
            except Exception:
                self._safe_rollback()
                raise

    def _begin(self):
        self._conn.execute("BEGIN IMMEDIATE")

    def _safe_rollback(self):
        try:
            self._conn.execute("ROLLBACK")
        except Exception:
            pass

    # ── producer_state helpers ────────────────────────────────────────────────
    def _get_state_locked(self, key, default=None):
        cur = self._conn.execute("SELECT value FROM producer_state WHERE key=?", (key,))
        row = cur.fetchone()
        cur.close()
        return row[0] if row else default

    def _set_state_locked(self, key, value, overwrite=True):
        if overwrite:
            self._conn.execute(
                "INSERT INTO producer_state(key, value, updated_at_ms) VALUES(?,?,?) "
                "ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at_ms=excluded.updated_at_ms",
                (key, str(value), now_ms()),
            )
        else:
            self._conn.execute(
                "INSERT OR IGNORE INTO producer_state(key, value, updated_at_ms) VALUES(?,?,?)",
                (key, str(value), now_ms()),
            )

    def get_state(self, key, default=None):
        with self._lock:
            return self._get_state_locked(key, default)

    def set_state(self, key, value):
        with self._lock:
            self._begin()
            try:
                self._set_state_locked(key, value)
                self._conn.execute("COMMIT")
            except Exception:
                self._safe_rollback()
                raise

    def _allocate_sequence_locked(self) -> int:
        """Monotonic PER PRODUCER sequence, persisted across restarts."""
        raw = self._get_state_locked("next_sequence", "1")
        try:
            seq = int(raw)
        except (TypeError, ValueError):
            seq = 1
        cur = self._conn.execute("SELECT MAX(sequence) FROM outbox")
        row = cur.fetchone()
        cur.close()
        if row and row[0] is not None and int(row[0]) >= seq:
            seq = int(row[0]) + 1  # defensive: never reuse a sequence
        self._set_state_locked("next_sequence", str(seq + 1))
        return seq

    def peek_next_sequence(self) -> int:
        with self._lock:
            try:
                return int(self._get_state_locked("next_sequence", "1"))
            except (TypeError, ValueError):
                return 1

    # ── bar_state (is_final / revision state machine) ─────────────────────────
    def _load_bar_states_locked(self, identities):
        states = {}
        for identity in identities:
            cur = self._conn.execute(
                "SELECT payload_hash, revision, last_final_emitted FROM bar_state "
                "WHERE symbol=? AND timeframe_sec=? AND bar_start_utc_ms=?",
                identity,
            )
            row = cur.fetchone()
            cur.close()
            if row:
                states[identity] = {
                    "payload_hash": row[0],
                    "revision": int(row[1]),
                    "last_final_emitted": bool(row[2]),
                }
        return states

    def _apply_bar_state_locked(self, bars, stamp_ms):
        """Return (emit_bars, skipped, state_updates) per the is_final/revision rules."""
        identities = [bar_identity(b) for b in bars]
        prior = self._load_bar_states_locked(set(identities))
        emit, skipped, updates, seen = [], 0, [], set()

        for bar in bars:
            identity = bar_identity(bar)
            if identity in seen:
                skipped += 1  # rule 5: never the same identity twice in one batch
                continue
            content_hash = bar_content_hash(bar)
            prev = prior.get(identity)
            finalise_now = should_finalise(prev, bar)

            if prev is None:
                revision = 1
                emit_bar = dict(bar)
                emit_bar["revision"] = revision
                emit.append(emit_bar)
                updates.append((identity, content_hash, revision, bool(finalise_now)))
                seen.add(identity)
                continue

            content_changed = prev["payload_hash"] != content_hash
            if content_changed:
                revision = int(prev["revision"]) + 1
            elif finalise_now:
                revision = int(prev["revision"])  # finalise once: no revision bump
            else:
                skipped += 1  # identical payload, nothing to finalise -> no new row
                continue

            emit_bar = dict(bar)
            emit_bar["revision"] = revision
            if bool(bar.get("is_final")) and prev["last_final_emitted"] and not content_changed:
                skipped += 1
                continue
            if bool(bar.get("is_final")) and prev["last_final_emitted"] and content_changed:
                # A finalised identity that still changes: emit a revision update but
                # keep is_final=true (the server treats higher revision as winner).
                emit_bar["is_final"] = True
            emit.append(emit_bar)
            updates.append((
                identity,
                content_hash,
                revision,
                bool(prev["last_final_emitted"] or finalise_now),
            ))
            seen.add(identity)

        for identity, content_hash, revision, final_emitted in updates:
            self._conn.execute(
                "INSERT INTO bar_state(symbol, timeframe_sec, bar_start_utc_ms, payload_hash, "
                "revision, last_final_emitted, updated_at_ms) VALUES(?,?,?,?,?,?,?) "
                "ON CONFLICT(symbol, timeframe_sec, bar_start_utc_ms) DO UPDATE SET "
                "payload_hash=excluded.payload_hash, revision=excluded.revision, "
                "last_final_emitted=MAX(bar_state.last_final_emitted, excluded.last_final_emitted), "
                "updated_at_ms=excluded.updated_at_ms",
                (identity[0], identity[1], identity[2], content_hash, revision,
                 1 if final_emitted else 0, stamp_ms),
            )
        return emit, skipped

    def bar_state(self, symbol, timeframe_sec, bar_start_utc_ms):
        with self._lock:
            states = self._load_bar_states_locked([(symbol, int(timeframe_sec), int(bar_start_utc_ms))])
            return states.get((symbol, int(timeframe_sec), int(bar_start_utc_ms)))

    # ── enqueue ───────────────────────────────────────────────────────────────
    def enqueue_batch(self, bars, market=None, captured_at_utc_ms=None,
                      watermark_utc_ms=None, batch_id=None) -> str:
        """Apply the state machine, build the gzip payload and durably store it.

        Returns the batch_id, or "" when the state machine decided that nothing
        new must be delivered (identical payload, already finalised).
        The gzip bytes are produced BEFORE the insert and stored verbatim: what is
        stored is byte-for-byte what will be sent and what the HMAC covers.
        """
        if not bars:
            return ""
        market_up = str(market or self.cfg.MARKET_MODE or "").upper() or "UNKNOWN"
        stamp = int(captured_at_utc_ms if captured_at_utc_ms is not None else now_ms())

        with self._lock:
            self._begin()
            try:
                emit, skipped = self._apply_bar_state_locked(bars, stamp)
                if not emit:
                    self._conn.execute("COMMIT")
                    jlog("OUTBOX_ENQUEUE_SKIPPED", market=market_up, candidates=len(bars),
                         skipped=skipped)
                    return ""

                prev_watermark = int(self._get_state_locked("watermark_utc_ms", "0") or 0)
                computed = compute_watermark(emit, prev_watermark)
                if watermark_utc_ms is not None:
                    computed = max(int(watermark_utc_ms), prev_watermark)

                sequence = self._allocate_sequence_locked()
                bid = batch_id or str(uuid.uuid4())
                payload_obj = build_canonical_payload(
                    self.producer_id, bid, sequence, market_up, emit, stamp, computed
                )
                raw_json = canonical_json_text(payload_obj).encode("utf-8")
                gz = gzip_bytes(raw_json)
                digest = sha256_hex(gz)

                self._conn.execute(
                    "INSERT INTO outbox(sequence, batch_id, payload, payload_sha256, created_at_ms, "
                    "attempts, next_attempt_at_ms, committed_at_ms, last_error) "
                    "VALUES(?,?,?,?,?,?,?,?,?)",
                    (sequence, bid, sqlite3.Binary(gz), digest, stamp, 0, stamp, None, None),
                )
                self._set_state_locked("watermark_utc_ms", str(computed))
                self._set_state_locked("last_enqueued_sequence", str(sequence))
                self._conn.execute("COMMIT")
            except Exception:
                self._safe_rollback()
                raise

        jlog("OUTBOX_ENQUEUED", batch_id=bid, sequence=sequence, market=market_up,
             bars=len(emit), skipped=skipped, gzip_bytes=len(gz),
             payload_sha256=digest, watermark_utc_ms=computed)
        return bid

    # ── read side ─────────────────────────────────────────────────────────────
    def next_pending_batch(self, at_ms=None, respect_schedule=True):
        """Oldest SENDABLE pending row by ASCENDING sequence (strict head-of-line).

        Returns None when the head-of-line sendable row is not due yet
        (backoff), which preserves in-order delivery and therefore monotonic
        server sequences. Rows that hit a positive OUTBOX_MAX_ATTEMPTS cap are
        skipped (never deleted) so a poison row cannot block the queue forever.

        FIX K-07：cap 條件推落 SQL。舊版 LIMIT 64 先攞先入 Python 過濾——
        隊頭擺夠 64 個 parked 行就永遠回 None，producer 停哂送貨而 pending 繼續積。
        推入 SQL 之餘，每轉仲少讀最多 63 個用唔著嘅 payload BLOB。
        """
        stamp = int(at_ms if at_ms is not None else now_ms())
        cap = int(self.cfg.OUTBOX_MAX_ATTEMPTS)
        cap_active = 1 if cap > 0 else 0
        with self._lock:
            cur = self._conn.execute(
                "SELECT sequence, batch_id, payload, payload_sha256, created_at_ms, attempts, "
                "next_attempt_at_ms, committed_at_ms, last_error FROM outbox "
                "WHERE committed_at_ms IS NULL AND (? = 0 OR attempts < ?) "
                "ORDER BY sequence ASC LIMIT 1",
                (cap_active, cap if cap > 0 else 0),
            )
            raw = cur.fetchone()
            cur.close()
        if raw is None:
            return None
        row = OutboxRow.from_sqlite(raw)
        if respect_schedule and row.next_attempt_at_ms > stamp:
            return None
        return row

    def pending_rows(self, limit=1000):
        with self._lock:
            cur = self._conn.execute(
                "SELECT sequence, batch_id, payload, payload_sha256, created_at_ms, attempts, "
                "next_attempt_at_ms, committed_at_ms, last_error FROM outbox "
                "WHERE committed_at_ms IS NULL ORDER BY sequence ASC LIMIT ?",
                (int(limit),),
            )
            rows = cur.fetchall()
            cur.close()
        return [OutboxRow.from_sqlite(r) for r in rows]

    def get_row(self, batch_id):
        with self._lock:
            cur = self._conn.execute(
                "SELECT sequence, batch_id, payload, payload_sha256, created_at_ms, attempts, "
                "next_attempt_at_ms, committed_at_ms, last_error FROM outbox WHERE batch_id=?",
                (str(batch_id),),
            )
            row = cur.fetchone()
            cur.close()
        return OutboxRow.from_sqlite(row) if row else None

    # ── write side ────────────────────────────────────────────────────────────
    def mark_committed(self, batch_id: str, ack: dict) -> None:
        stamp = now_ms()
        ack = ack or {}
        # IS-HOTFIX-4 (DATA-LOSS-1 2026-08-19): an idempotent duplicate
        # (accepted==0) still commits (no re-send — correct for true
        # idempotent resends), but it is the path that can silently lose
        # bars when the server ledger is ahead of its shelf. Mark the row
        # suspect + CRITICAL log (no Telegram per ops decision).
        is_duplicate_ack = (ack.get("accepted") == 0)
        with self._lock:
            self._begin()
            try:
                self._conn.execute(
                    "UPDATE outbox SET committed_at_ms=?, last_error=NULL"
                    + (", suspect=1" if is_duplicate_ack else "")
                    + " WHERE batch_id=? AND committed_at_ms IS NULL",
                    (stamp, str(batch_id)),
                )
                cur = self._conn.execute("SELECT sequence FROM outbox WHERE batch_id=?", (str(batch_id),))
                row = cur.fetchone()
                cur.close()
                if row:
                    prev = int(self._get_state_locked("last_committed_sequence", "0") or 0)
                    self._set_state_locked("last_committed_sequence", str(max(prev, int(row[0]))))
                highest = ack.get("highest_sequence")
                if isinstance(highest, int):
                    self._set_state_locked("server_highest_sequence", str(highest))
                self._set_state_locked("last_ack_at_ms", str(stamp))
                self._conn.execute("COMMIT")
            except Exception:
                self._safe_rollback()
                raise
        jlog("OUTBOX_COMMITTED", batch_id=str(batch_id), accepted=ack.get("accepted"),
             duplicate=ack.get("duplicate"), rejected=ack.get("rejected"),
             highest_sequence=ack.get("highest_sequence"))
        if is_duplicate_ack:
            jlog("DUPLICATE_ACK_CRITICAL", batch_id=str(batch_id),
                 duplicate=ack.get("duplicate"),
                 highest_sequence=ack.get("highest_sequence"),
                 suspect=1,
                 note=("CRITICAL: committed via duplicate ACK (no re-send). If the server "
                       "ledger was ahead of its shelf, bars may be missing server-side — "
                       "verify (DATA-LOSS-1 guard, 2026-08-19). No Telegram per ops."))

    def mark_failed(self, batch_id: str, error: str, next_retry_at_ms: int) -> None:
        with self._lock:
            self._begin()
            try:
                self._conn.execute(
                    "UPDATE outbox SET attempts=attempts+1, next_attempt_at_ms=?, last_error=? "
                    "WHERE batch_id=? AND committed_at_ms IS NULL",
                    (int(next_retry_at_ms), CONFIG.redact(str(error))[:500], str(batch_id)),
                )
                self._conn.execute("COMMIT")
            except Exception:
                self._safe_rollback()
                raise

    def cleanup_expired_committed(self, at_ms=None) -> int:
        """Delete ONLY committed rows older than OUTBOX_RETENTION_HOURS. Pending rows
        are never deleted, regardless of age."""
        stamp = int(at_ms if at_ms is not None else now_ms())
        cutoff = stamp - int(self.cfg.OUTBOX_RETENTION_HOURS * 3600 * 1000)
        with self._lock:
            self._begin()
            try:
                cur = self._conn.execute(
                    "DELETE FROM outbox WHERE committed_at_ms IS NOT NULL AND committed_at_ms < ?",
                    (cutoff,),
                )
                deleted = cur.rowcount or 0
                self._conn.execute("COMMIT")
            except Exception:
                self._safe_rollback()
                raise
        if deleted:
            jlog("OUTBOX_CLEANUP", deleted=deleted, cutoff_ms=cutoff)
        return int(deleted)

    def prune_bar_state(self, older_than_ms) -> int:
        """Bounded memory: drop bar_state rows for trading days already delivered."""
        with self._lock:
            self._begin()
            try:
                cur = self._conn.execute("DELETE FROM bar_state WHERE updated_at_ms < ?",
                                         (int(older_than_ms),))
                deleted = cur.rowcount or 0
                self._conn.execute("COMMIT")
            except Exception:
                self._safe_rollback()
                raise
        return int(deleted)

    # ── observability ─────────────────────────────────────────────────────────
    def stats(self) -> dict:
        stamp = now_ms()
        with self._lock:
            cur = self._conn.execute(
                "SELECT COUNT(*), MIN(created_at_ms), MIN(sequence), MAX(sequence) FROM outbox "
                "WHERE committed_at_ms IS NULL"
            )
            pending_count, oldest_created, min_seq, max_seq = cur.fetchone()
            cur.close()
            cur = self._conn.execute("SELECT COUNT(*) FROM outbox WHERE committed_at_ms IS NOT NULL")
            committed_count = cur.fetchone()[0]
            cur.close()
            cur = self._conn.execute("SELECT COUNT(*) FROM bar_state")
            bar_states = cur.fetchone()[0]
            cur.close()
            last_committed = int(self._get_state_locked("last_committed_sequence", "0") or 0)
            server_high = int(self._get_state_locked("server_highest_sequence", "0") or 0)
            watermark = int(self._get_state_locked("watermark_utc_ms", "0") or 0)
            last_ack = int(self._get_state_locked("last_ack_at_ms", "0") or 0)
        return {
            "pending_count": int(pending_count or 0),
            "committed_count": int(committed_count or 0),
            "oldest_pending_age_ms": int(stamp - oldest_created) if oldest_created else 0,
            "oldest_pending_sequence": int(min_seq) if min_seq is not None else None,
            "newest_pending_sequence": int(max_seq) if max_seq is not None else None,
            "last_committed_sequence": last_committed,
            "server_highest_sequence": server_high,
            "watermark_utc_ms": watermark,
            "last_ack_at_ms": last_ack,
            "bar_state_rows": int(bar_states or 0),
            "db_path": self.db_path,
        }

    def integrity_check(self) -> str:
        with self._lock:
            cur = self._conn.execute("PRAGMA integrity_check")
            result = cur.fetchone()[0]
            cur.close()
        return str(result)

    def checkpoint(self):
        with self._lock:
            try:
                self._conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
            except Exception as exc:
                log_exception("OUTBOX_CHECKPOINT_FAILED", exc)

    def close(self):
        with self._lock:
            try:
                self.checkpoint()
            finally:
                try:
                    self._conn.close()
                except Exception as exc:
                    log_exception("OUTBOX_CLOSE_FAILED", exc)


def compute_watermark(bars, previous_watermark=0) -> int:
    """Producer-level completeness watermark (monotonic, never rewound).

    Definition: the largest bar_start for which EVERY symbol in this batch has a
    final (closed) bar, i.e. min over symbols of max(final bar_start). When the
    batch contains no final bar, the previous watermark is preserved.
    """
    per_symbol = {}
    for bar in bars or []:
        if not bar.get("is_final"):
            continue
        symbol = bar["symbol"]
        start = int(bar["bar_start_utc_ms"])
        if start > per_symbol.get(symbol, -1):
            per_symbol[symbol] = start
    if not per_symbol:
        return int(previous_watermark or 0)
    return max(int(previous_watermark or 0), min(per_symbol.values()))


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 7 — W3 TRANSPORT: requests.Session pooling, HMAC, ACK validation, retry
# ══════════════════════════════════════════════════════════════════════════════
class SendResult(object):
    """SendResult = {ok, committed, duplicate, status_or_error, next_retry_at_ms}"""

    __slots__ = ("ok", "committed", "duplicate", "status_or_error", "next_retry_at_ms",
                 "http_status", "ack")

    def __init__(self, ok, committed, duplicate, status_or_error, next_retry_at_ms,
                 http_status=None, ack=None):
        self.ok = bool(ok)
        self.committed = bool(committed)
        self.duplicate = bool(duplicate)
        self.status_or_error = status_or_error
        self.next_retry_at_ms = int(next_retry_at_ms or 0)
        self.http_status = http_status
        self.ack = ack or {}

    def to_dict(self):
        return {
            "ok": self.ok,
            "committed": self.committed,
            "duplicate": self.duplicate,
            "status_or_error": self.status_or_error,
            "next_retry_at_ms": self.next_retry_at_ms,
            "http_status": self.http_status,
        }

    def __repr__(self):
        return f"SendResult({self.to_dict()})"


class Transport(object):
    """HTTP delivery of one outbox row. Never disables TLS verification."""

    def __init__(self, cfg=None, outbox=None, url=None, secret=None, producer_id=None):
        self.cfg = cfg or CONFIG
        self.outbox = outbox
        self.url = url if url is not None else self.cfg.INGEST_URL
        self.secret = secret if secret is not None else self.cfg.INGEST_HMAC_SECRET
        self.producer_id = producer_id if producer_id is not None else self.cfg.PRODUCER_ID
        self.sent_ok = 0
        self.sent_failed = 0
        self.last_error = None
        self.last_status = None
        self._session = None
        self._session_lock = threading.Lock()

    # ── session ───────────────────────────────────────────────────────────────
    def session(self):
        if requests is None:
            raise RuntimeError(
                "python package 'requests' is required for delivery but is not importable: "
                + str(REQUESTS_IMPORT_ERROR)
            )
        with self._session_lock:
            if self._session is None:
                sess = requests.Session()
                pool = max(1, int(self.cfg.HTTP_POOL_SIZE))
                adapter = HTTPAdapter(pool_connections=pool, pool_maxsize=pool * 2, max_retries=0)
                sess.mount("http://", adapter)
                sess.mount("https://", adapter)
                sess.headers.update({
                    "User-Agent": f"futu-producer/{APP_VERSION} ({CONTRACT_ID})",
                    "Accept": "application/json",
                })
                self._session = sess
            return self._session

    def close(self):
        with self._session_lock:
            if self._session is not None:
                try:
                    self._session.close()
                except Exception as exc:
                    log_exception("TRANSPORT_SESSION_CLOSE_FAILED", exc)
                self._session = None

    # ── headers ───────────────────────────────────────────────────────────────
    def build_headers(self, batch_id, sequence, producer_id, payload_bytes=None) -> dict:
        """Frozen interface build_headers(batch_id, sequence, producer_id).

        `payload_bytes` is an OPTIONAL extension: when omitted the gzip bytes are
        loaded from the outbox row identified by batch_id, so the 3-argument form
        published in the interface contract stays fully functional.
        X-Signature is HMAC-SHA256 over the RAW GZIP BYTES that are sent.
        """
        payload = payload_bytes
        if payload is None:
            source = self.outbox or OUTBOX
            row = source.get_row(batch_id) if source is not None else None
            if row is None:
                raise ValueError(f"build_headers: unknown batch_id {batch_id} (payload unavailable)")
            payload = row.payload
        if not self.secret:
            raise RuntimeError("INGEST_HMAC_SECRET is empty; refusing to sign a batch")
        return {
            "Content-Type": "application/json",
            "Content-Encoding": "gzip",
            "X-Producer-Id": str(producer_id),
            "X-Batch-Id": str(batch_id),
            "X-Sequence": str(int(sequence)),
            "X-Signature": signature_header_value(self.secret, payload),
        }

    # ── retry schedule ────────────────────────────────────────────────────────
    def compute_next_retry_ms(self, attempts, batch_id, at_ms=None) -> int:
        stamp = int(at_ms if at_ms is not None else now_ms())
        attempt_no = max(1, int(attempts) + 1)
        base = max(0.05, float(self.cfg.OUTBOX_BACKOFF_BASE_SEC))
        cap = max(base, float(self.cfg.OUTBOX_BACKOFF_MAX_SEC))
        exponent = min(attempt_no - 1, 20)
        delay = min(cap, base * (2 ** exponent))
        jitter = deterministic_jitter(f"{batch_id}:{attempt_no}", delay * 0.25)
        return stamp + int((delay + jitter) * 1000)

    # ── ACK validation ────────────────────────────────────────────────────────
    def validate_ack(self, row, http_status, ack):
        """(committed, duplicate, reason). 回條唔係「有蓋章」就收：
        FIX K-08：件數要係非負整數（唔准 bool 扮 int）、accepted+duplicate+rejected
        要夾返寄出 bar 數、highest_sequence 唔准後退、accepted=0 時 duplicate 要 >0。"""
        if not (200 <= int(http_status) < 300):
            return False, False, f"http_{http_status}"
        if not isinstance(ack, dict):
            return False, False, "ack_not_object"
        if not constant_time_equals(str(ack.get("batch_id", "")), str(row.batch_id)):
            return False, False, "ack_batch_id_mismatch"
        if str(ack.get("status", "")) != ACK_STATUS_COMMITTED:
            return False, False, f"ack_status_{ack.get('status')}"
        missing = [f for f in ACK_REQUIRED_FIELDS if f not in ack]
        if missing:
            return False, False, "ack_missing_fields_" + ",".join(missing)

        # FIX K-08：counter 逐個驗——bool 係 int 嘅 subclass，要明確踢走
        for name in ("accepted", "duplicate", "rejected", "highest_sequence"):
            value = ack.get(name)
            if isinstance(value, bool) or not isinstance(value, int) or value < 0:
                return False, False, f"ack_bad_{name}"
        if ack["highest_sequence"] < row.sequence:
            return False, False, "ack_highest_sequence_regressed"

        try:
            payload = json.loads(gunzip_bytes(row.payload).decode("utf-8"))
            expected_bars = len(payload["bars"])
        except Exception:
            return False, False, "outbox_payload_unreadable"
        accounted = ack["accepted"] + ack["duplicate"] + ack["rejected"]
        if accounted != expected_bars:
            return False, False, "ack_counter_total_mismatch"
        is_duplicate = ack["accepted"] == 0
        if is_duplicate and ack["duplicate"] == 0:
            return False, False, "ack_zero_accept_without_duplicate"
        return True, is_duplicate, "committed"

    # ── send ──────────────────────────────────────────────────────────────────
    def send_batch(self, row) -> SendResult:
        """POST one outbox row. Failures are logged (never swallowed) and scheduled."""
        # FIX K-23：outbox 行俾人抽起／簿損要等價失敗收口，唔准 None.batch_id 炸線程
        if row is None:
            self.sent_failed += 1
            self.last_error = "outbox_row_not_found"
            jlog("DELIVERY_FAILED", producer_id=self.producer_id,
                 status_or_error=self.last_error)
            return SendResult(False, False, False, self.last_error, now_ms())
        if not self.url:
            error = "INGEST_URL_not_configured"
            jlog("DELIVERY_FAILED", producer_id=self.producer_id, batch_id=row.batch_id,
                 sequence=row.sequence, attempt=row.attempts + 1, status_or_error=error)
            return SendResult(False, False, False, error,
                              self.compute_next_retry_ms(row.attempts, row.batch_id))
        try:
            headers = self.build_headers(row.batch_id, row.sequence, self.producer_id, row.payload)
        except Exception as exc:
            log_exception("DELIVERY_SIGN_FAILED", exc, batch_id=row.batch_id, sequence=row.sequence)
            return SendResult(False, False, False, f"sign_error:{type(exc).__name__}",
                              self.compute_next_retry_ms(row.attempts, row.batch_id))

        started = time.perf_counter()
        try:
            response = self.session().post(
                self.url,
                data=row.payload,
                headers=headers,
                timeout=(float(self.cfg.HTTP_CONNECT_TIMEOUT_SEC), float(self.cfg.HTTP_READ_TIMEOUT_SEC)),
            )
        except Exception as exc:
            self.sent_failed += 1
            self.last_error = f"{type(exc).__name__}: {CONFIG.redact(str(exc))}"
            next_retry = self.compute_next_retry_ms(row.attempts, row.batch_id)
            jlog("DELIVERY_FAILED", producer_id=self.producer_id, batch_id=row.batch_id,
                 sequence=row.sequence, attempt=row.attempts + 1,
                 status_or_error=self.last_error, next_retry_at_ms=next_retry)
            return SendResult(False, False, False, self.last_error, next_retry)

        elapsed_ms = int((time.perf_counter() - started) * 1000)
        status = response.status_code
        self.last_status = status
        try:
            ack = response.json()
        except Exception:
            ack = None

        committed, duplicate, reason = self.validate_ack(row, status, ack)
        if committed:
            self.sent_ok += 1
            jlog("DELIVERY_OK", producer_id=self.producer_id, batch_id=row.batch_id,
                 sequence=row.sequence, attempt=row.attempts + 1, http_status=status,
                 duplicate=duplicate, accepted=(ack or {}).get("accepted"),
                 highest_sequence=(ack or {}).get("highest_sequence"), elapsed_ms=elapsed_ms)
            return SendResult(True, True, duplicate, "committed", 0, status, ack)

        self.sent_failed += 1
        self.last_error = reason
        next_retry = self.compute_next_retry_ms(row.attempts, row.batch_id)
        jlog("DELIVERY_FAILED", producer_id=self.producer_id, batch_id=row.batch_id,
             sequence=row.sequence, attempt=row.attempts + 1, http_status=status,
             status_or_error=reason, next_retry_at_ms=next_retry, elapsed_ms=elapsed_ms)
        return SendResult(False, False, False, reason, next_retry, status, ack)

    def stats(self):
        return {
            "sent_ok": self.sent_ok,
            "sent_failed": self.sent_failed,
            "last_status": self.last_status,
            "last_error": self.last_error,
            "ingest_url": self.url,
        }


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 8 — SENDER LOOP (independent of the UI crawl; survives watchdog rebuilds)
# ══════════════════════════════════════════════════════════════════════════════
class Sender(threading.Thread):
    """Drains the outbox in strict sequence order, forever, in its own thread.

    It is intentionally decoupled from the UI crawl loop: while the watchdog
    rebuilds Docker or the three-level recovery restarts uiautomator, delivery of
    already-captured batches continues.
    """

    def __init__(self, outbox, transport, cfg=None, name="outbox-sender"):
        super().__init__(name=name, daemon=True)
        self.outbox = outbox
        self.transport = transport
        self.cfg = cfg or CONFIG
        self._stop = threading.Event()
        self._wake = threading.Event()
        self.last_cleanup_ms = 0
        self.cycles = 0

    def stop(self):
        self._stop.set()
        self._wake.set()

    def wake(self):
        self._wake.set()

    def drain_once(self) -> int:
        """Send every currently-due pending row. Returns the committed count."""
        committed = 0
        while not self._stop.is_set():
            row = self.outbox.next_pending_batch()
            if row is None:
                break
            result = self.transport.send_batch(row)
            if result.committed:
                self.outbox.mark_committed(row.batch_id, result.ack)
                RUNTIME.set(last_ack_at_ms=now_ms(), last_error=None)
                committed += 1
            else:
                self.outbox.mark_failed(row.batch_id, str(result.status_or_error),
                                        result.next_retry_at_ms)
                RUNTIME.set(last_error=f"delivery:{result.status_or_error}")
                break  # strict head-of-line ordering: wait for the backoff
        return committed

    def replay_pending_blocking(self, timeout_sec=None) -> dict:
        """Startup replay: push pending batches BEFORE any new crawl begins."""
        deadline = time.time() + float(
            timeout_sec if timeout_sec is not None else self.cfg.STARTUP_REPLAY_TIMEOUT_SEC
        )
        pending_before = self.outbox.stats()["pending_count"]
        committed = 0
        while time.time() < deadline and not self._stop.is_set():
            row = self.outbox.next_pending_batch(respect_schedule=False)
            if row is None:
                break
            result = self.transport.send_batch(row)
            if result.committed:
                self.outbox.mark_committed(row.batch_id, result.ack)
                committed += 1
                continue
            self.outbox.mark_failed(row.batch_id, str(result.status_or_error),
                                    result.next_retry_at_ms)
            sleep_for = max(0.2, min(5.0, (result.next_retry_at_ms - now_ms()) / 1000.0))
            if time.time() + sleep_for > deadline:
                break
            time.sleep(sleep_for)
        remaining = self.outbox.stats()["pending_count"]
        report = {"pending_before": pending_before, "committed": committed, "pending_after": remaining}
        jlog("STARTUP_REPLAY", **report)
        return report

    def run(self):
        jlog("SENDER_START", producer_id=self.transport.producer_id, ingest_url=self.transport.url)
        while not self._stop.is_set():
            try:
                self.cycles += 1
                self.drain_once()
                stamp = now_ms()
                if stamp - self.last_cleanup_ms > 3600 * 1000:
                    self.last_cleanup_ms = stamp
                    self.outbox.cleanup_expired_committed(stamp)
                    retention_ms = int(self.cfg.OUTBOX_RETENTION_HOURS * 3600 * 1000)
                    self.outbox.prune_bar_state(stamp - max(retention_ms, 3 * 24 * 3600 * 1000))
            except Exception as exc:
                log_exception("SENDER_LOOP_ERROR", exc)
                time.sleep(1.0)
            self._wake.wait(max(0.05, float(self.cfg.SENDER_IDLE_SLEEP_SEC)))
            self._wake.clear()
        jlog("SENDER_STOP", cycles=self.cycles)


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 9 — W5 HEALTH + GRACEFUL SHUTDOWN
# ══════════════════════════════════════════════════════════════════════════════
class RuntimeState(object):
    """Thread-safe process state exposed through the health endpoint/file."""

    def __init__(self):
        self._lock = threading.Lock()
        self._data = {
            "started_at_ms": now_ms(),
            "market": MARKET_MODE,
            "loop_count": 0,
            "ui_recovery_state": "boot",
            "last_error": None,
            "last_loop_at_ms": 0,
            "last_ack_at_ms": 0,
            "last_batch_id": None,
            "bars_last_round": 0,
            "stale_rounds": 0,
            "watchdog_fires": 0,
            "docker_rebuilds": 0,
            "app_restarts": 0,
        }

    def set(self, **fields):
        with self._lock:
            for key, value in fields.items():
                self._data[key] = value

    def bump(self, key, delta=1):
        with self._lock:
            self._data[key] = int(self._data.get(key, 0)) + delta

    def snapshot(self):
        with self._lock:
            return dict(self._data)


RUNTIME = RuntimeState()
OUTBOX = None       # type: Outbox
TRANSPORT = None    # type: Transport
SENDER = None       # type: Sender
SHUTDOWN_EVENT = threading.Event()
_SHUTDOWN_COUNT = [0]


def health_snapshot() -> dict:
    """market, loop_count, pending_count, oldest_pending_age_ms,
    last_committed_sequence, last_ack_time, ui_recovery_state, last_error (+extras)."""
    state = RUNTIME.snapshot()
    snapshot = {
        "status": "shutting_down" if SHUTDOWN_EVENT.is_set() else "ok",
        "version": APP_VERSION,
        "contract_id": CONTRACT_ID,
        "contract_revision": CONTRACT_REVISION,
        "producer_id": CONFIG.PRODUCER_ID,
        "market": state.get("market"),
        "pid": os.getpid(),
        "uptime_ms": now_ms() - int(state.get("started_at_ms") or now_ms()),
        "loop_count": state.get("loop_count"),
        "last_loop_at_ms": state.get("last_loop_at_ms"),
        "bars_last_round": state.get("bars_last_round"),
        "stale_rounds": state.get("stale_rounds"),
        "ui_recovery_state": state.get("ui_recovery_state"),
        "watchdog_fires": state.get("watchdog_fires"),
        "docker_rebuilds": state.get("docker_rebuilds"),
        "app_restarts": state.get("app_restarts"),
        "last_error": state.get("last_error"),
        "last_batch_id": state.get("last_batch_id"),
        "pending_count": None,
        "oldest_pending_age_ms": None,
        "last_committed_sequence": None,
        "last_ack_time": None,
        "normalize_stats": dict(NORMALIZE_STATS),
    }
    if OUTBOX is not None:
        try:
            stats = OUTBOX.stats()
            snapshot.update({
                "pending_count": stats["pending_count"],
                "committed_count": stats["committed_count"],
                "oldest_pending_age_ms": stats["oldest_pending_age_ms"],
                "last_committed_sequence": stats["last_committed_sequence"],
                "server_highest_sequence": stats["server_highest_sequence"],
                "watermark_utc_ms": stats["watermark_utc_ms"],
                "bar_state_rows": stats["bar_state_rows"],
                "outbox_db_path": stats["db_path"],
            })
            ack_ms = stats["last_ack_at_ms"] or state.get("last_ack_at_ms") or 0
            snapshot["last_ack_time"] = (
                datetime.fromtimestamp(ack_ms / 1000.0, tz=UTC).isoformat().replace("+00:00", "Z")
                if ack_ms else None
            )
            snapshot["last_ack_at_ms"] = ack_ms
        except Exception as exc:
            snapshot["last_error"] = f"health_outbox_error:{type(exc).__name__}"
    if TRANSPORT is not None:
        snapshot["transport"] = TRANSPORT.stats()
    return snapshot


def write_health_file(path=None) -> bool:
    target = path or CONFIG.HEALTH_FILE_PATH
    if not target:
        return False
    try:
        parent = os.path.dirname(os.path.abspath(target))
        if parent:
            os.makedirs(parent, exist_ok=True)
        tmp = f"{target}.tmp.{os.getpid()}"
        with open(tmp, "w", encoding="utf-8") as fh:
            json.dump(health_snapshot(), fh, ensure_ascii=False, indent=2, default=str)
        os.replace(tmp, target)
        return True
    except Exception as exc:
        log_exception("HEALTH_FILE_WRITE_FAILED", exc, path=target)
        return False


class _HealthHandler(BaseHTTPRequestHandler):
    server_version = f"futu-health/{APP_VERSION}"

    def do_GET(self):  # noqa: N802 (http.server API)
        path = (self.path or "/").split("?")[0].rstrip("/") or "/"
        if path in ("/", "/health", "/healthz", "/readyz", "/status"):
            body = json.dumps(health_snapshot(), ensure_ascii=False, default=str).encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        self.send_response(404)
        self.send_header("Content-Type", "application/json")
        body = b'{"error":"not_found"}'
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, fmt, *args):  # silence per-request stderr noise
        return


class HealthServer(object):
    def __init__(self, host=None, port=None):
        self.host = host if host is not None else CONFIG.HEALTH_BIND_HOST
        self.port = int(port if port is not None else CONFIG.HEALTH_PORT)
        self._httpd = None
        self._thread = None

    def start(self) -> bool:
        try:
            self._httpd = ThreadingHTTPServer((self.host, self.port), _HealthHandler)
            self._httpd.daemon_threads = True
            self._thread = threading.Thread(target=self._httpd.serve_forever,
                                            kwargs={"poll_interval": 0.5},
                                            name="health-http", daemon=True)
            self._thread.start()
            jlog("HEALTH_SERVER_START", bind=f"{self.host}:{self.port}")
            return True
        except Exception as exc:
            # A busy port must never stop data production; the health FILE remains.
            log_exception("HEALTH_SERVER_START_FAILED", exc, bind=f"{self.host}:{self.port}")
            self._httpd = None
            return False

    @property
    def actual_port(self):
        if self._httpd is None:
            return None
        return self._httpd.server_address[1]

    def stop(self):
        if self._httpd is not None:
            try:
                self._httpd.shutdown()
                self._httpd.server_close()
            except Exception as exc:
                log_exception("HEALTH_SERVER_STOP_FAILED", exc)
            self._httpd = None


class HealthFileWriter(threading.Thread):
    def __init__(self, interval_sec=None):
        super().__init__(name="health-file", daemon=True)
        self.interval = float(interval_sec if interval_sec is not None else CONFIG.HEALTH_FILE_INTERVAL_SEC)
        self._stop = threading.Event()

    def stop(self):
        self._stop.set()

    def run(self):
        while not self._stop.is_set():
            write_health_file()
            self._stop.wait(max(1.0, self.interval))
        write_health_file()


def is_shutting_down() -> bool:
    return SHUTDOWN_EVENT.is_set()


def shutdown_handler(signum, frame) -> None:
    """Graceful SIGINT/SIGTERM: stop new work, let the current transaction finish,
    keep every un-ACKed batch. A second signal escalates to an immediate exit."""
    _SHUTDOWN_COUNT[0] += 1
    try:
        name = signal.Signals(signum).name
    except Exception:
        name = str(signum)
    if _SHUTDOWN_COUNT[0] > 1:
        lp(f"🛑 [SHUTDOWN] second {name} received — exiting immediately")
        try:
            write_health_file()
        except Exception:
            pass
        os._exit(1)
    lp(f"🛑 [SHUTDOWN] {name} received — draining and closing safely...")
    log_important("SHUTDOWN_SIGNAL", f"signal={name}")
    SHUTDOWN_EVENT.set()
    RUNTIME.set(ui_recovery_state="shutting_down")
    try:
        if SENDER is not None:
            SENDER.stop()
    except Exception as exc:
        log_exception("SHUTDOWN_SENDER_STOP_FAILED", exc)


def install_signal_handlers():
    for sig in (signal.SIGINT, signal.SIGTERM):
        try:
            signal.signal(sig, shutdown_handler)
        except (ValueError, OSError) as exc:  # non-main thread / unsupported platform
            log_exception("SIGNAL_INSTALL_FAILED", exc, signal=str(sig))


def graceful_close(timeout_sec=None):
    """Idempotent, safe teardown: stop sender, checkpoint WAL, close DB/session."""
    limit = float(timeout_sec if timeout_sec is not None else CONFIG.SHUTDOWN_GRACE_SEC)
    deadline = time.time() + limit
    try:
        if SENDER is not None:
            SENDER.stop()
            if SENDER.is_alive():
                SENDER.join(timeout=max(0.5, deadline - time.time()))
    except Exception as exc:
        log_exception("SHUTDOWN_SENDER_JOIN_FAILED", exc)
    try:
        if TRANSPORT is not None:
            TRANSPORT.close()
    except Exception as exc:
        log_exception("SHUTDOWN_TRANSPORT_CLOSE_FAILED", exc)
    pending = None
    try:
        if OUTBOX is not None:
            pending = OUTBOX.stats()["pending_count"]
            OUTBOX.close()
    except Exception as exc:
        log_exception("SHUTDOWN_OUTBOX_CLOSE_FAILED", exc)
    try:
        write_health_file()
    except Exception as exc:
        log_exception("SHUTDOWN_HEALTH_WRITE_FAILED", exc)
    log_important("SHUTDOWN_COMPLETE", f"pending_retained={pending}")


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 10 — GLOBAL WIRING (module-level frozen interfaces delegate here)
# ══════════════════════════════════════════════════════════════════════════════
def init_delivery_stack(cfg=None, db_path=None, url=None, secret=None, producer_id=None):
    """Create the process-wide outbox + transport + sender singletons."""
    global OUTBOX, TRANSPORT, SENDER
    cfg = cfg or CONFIG
    OUTBOX = Outbox(db_path=db_path or cfg.OUTBOX_DB_PATH, cfg=cfg,
                    producer_id=producer_id if producer_id is not None else cfg.PRODUCER_ID)
    TRANSPORT = Transport(cfg=cfg, outbox=OUTBOX, url=url, secret=secret, producer_id=producer_id)
    SENDER = Sender(OUTBOX, TRANSPORT, cfg=cfg)
    return OUTBOX, TRANSPORT, SENDER


def require_outbox() -> Outbox:
    if OUTBOX is None:
        raise RuntimeError("outbox is not initialised; call init_delivery_stack() first")
    return OUTBOX


def require_transport() -> Transport:
    if TRANSPORT is None:
        raise RuntimeError("transport is not initialised; call init_delivery_stack() first")
    return TRANSPORT


# ── frozen module-level interfaces (W2/W3) ───────────────────────────────────
def enqueue_batch(bars) -> str:
    """W2 frozen interface: enqueue_batch(bars: list[CanonicalBar]) -> batch_id."""
    return require_outbox().enqueue_batch(bars, market=MARKET_MODE)


def next_pending_batch():
    """W2 frozen interface: oldest pending row by ascending sequence, else None."""
    return require_outbox().next_pending_batch()


def mark_committed(batch_id: str, ack: dict) -> None:
    require_outbox().mark_committed(batch_id, ack)


def mark_failed(batch_id: str, error: str, next_retry_at_ms: int) -> None:
    require_outbox().mark_failed(batch_id, error, next_retry_at_ms)


def cleanup_expired_committed(at_ms=None) -> int:
    return require_outbox().cleanup_expired_committed(at_ms)


def build_headers(batch_id, sequence, producer_id) -> dict:
    """W3 frozen interface (payload resolved from the outbox by batch_id)."""
    return require_transport().build_headers(batch_id, sequence, producer_id)


def send_batch(row) -> SendResult:
    """W3 frozen interface."""
    return require_transport().send_batch(row)


def enqueue_canonical_bars(bars, market=None, captured_at_utc_ms=None) -> list:
    """Chunk a round into contract-sized batches; returns the created batch ids."""
    outbox = require_outbox()
    limit = max(1, int(CONFIG.BATCH_MAX_BARS))
    batch_ids = []
    for start in range(0, len(bars), limit):
        chunk = bars[start:start + limit]
        batch_id = outbox.enqueue_batch(chunk, market=market,
                                        captured_at_utc_ms=captured_at_utc_ms)
        if batch_id:
            batch_ids.append(batch_id)
    if batch_ids:
        RUNTIME.set(last_batch_id=batch_ids[-1])
        if SENDER is not None:
            SENDER.wake()
    return batch_ids


def legacy_webhook_notify(filepath):
    """Opt-in legacy callback. Fire-and-forget on its own thread; failures are
    logged (never swallowed) and can never affect outbox delivery correctness."""
    url = CONFIG.LEGACY_WEBHOOK_URL
    if not url:
        return False
    if requests is None:
        jlog("LEGACY_WEBHOOK_SKIPPED", reason="requests_unavailable")
        return False

    def _worker():
        try:
            resp = requests.post(url, json={"filepath": filepath}, timeout=3)
            jlog("LEGACY_WEBHOOK_SENT", status=resp.status_code, filepath=str(filepath))
        except Exception as exc:
            log_exception("LEGACY_WEBHOOK_FAILED", exc, filepath=str(filepath))

    threading.Thread(target=_worker, name="legacy-webhook", daemon=True).start()
    return True


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 11 — BASELINE INFRASTRUCTURE (PROTECTED: preserved or enhanced only)
#   Redroid / adb / uiautomator2 / popup guard / watchdog / three-level recovery
#   All AUTH-B semantics are kept; only configuration sourcing, structured
#   logging and health counters were added.
# ══════════════════════════════════════════════════════════════════════════════
WATCHDOG_TIMEOUT = CONFIG.WATCHDOG_TIMEOUT_SEC
_watchdog_timer = None
_watchdog_lock = threading.Lock()
_watchdog_triggered = threading.Event()
# BUG A fix：連續觸發計數——連續 2 次觸發（彈窗 delay）就加長檢測時間
_watchdog_consecutive = 0
WATCHDOG_ESCALATION_FACTOR = 1.6   # 連續觸發後 timeout × 1.6
WATCHDOG_MAX_TIMEOUT = 120.0       # 上限 120s
WATCHDOG_STRIKES_REQUIRED = 2      # FIX K-18：連續兩次超時先郁手重建（第一次只記錄＋再餵狗）


def _effective_watchdog_timeout():
    """連續觸發時加長 timeout（彈窗有 delay），最多 WATCHDOG_MAX_TIMEOUT。"""
    if _watchdog_consecutive >= 2:
        return min(WATCHDOG_TIMEOUT * (WATCHDOG_ESCALATION_FACTOR ** (_watchdog_consecutive - 1)), WATCHDOG_MAX_TIMEOUT)
    return WATCHDOG_TIMEOUT


def _watchdog_fire(reason: str):
    """Watchdog callback: rebuild Docker in a background thread, notify main loop."""
    global _watchdog_consecutive
    _watchdog_consecutive += 1
    lp(f"\n🚨 [WATCHDOG] 超過 {_effective_watchdog_timeout()}s 未完成！原因: {reason}（連續第 {_watchdog_consecutive} 次）")
    # FIX K-18：網絡抖動/慢 POST（HTTP_READ 90s）以前一 over 就拆機重装——
    # 殺死嗰條其實會成功嘅請求，重試又中行慢路，變咗「零 commit＋無限重開」。
    if _watchdog_consecutive < WATCHDOG_STRIKES_REQUIRED:
        append_log("WATCHDOG_WARN", f"strike {_watchdog_consecutive}/{WATCHDOG_STRIKES_REQUIRED} reason={reason}")
        lp(f"🐕 [WATCHDOG] 第 {_watchdog_consecutive} 次逾時——暫時觀察唔郁手（連續 {WATCHDOG_STRIKES_REQUIRED} 次先重建），重新餵狗...")
        watchdog_reset(reason)
        return
    lp("🚨 [WATCHDOG] 立即執行 Docker 重建...")
    append_log("WATCHDOG_FIRE", f"Timeout {WATCHDOG_TIMEOUT}s reason={reason}")
    RUNTIME.bump("watchdog_fires")
    RUNTIME.set(ui_recovery_state="watchdog_rebuild")
    _watchdog_triggered.set()
    try:
        docker_recovery()
        if wait_device_ready(timeout=120, check_interval=2):
            lp("✅ [WATCHDOG] Docker 重建完成，主迴圈將重連並繼續。")
        else:
            lp("❌ [WATCHDOG] Docker 重建後設備未就緒，主迴圈將自行處理。")
    except Exception as exc:
        log_exception("WATCHDOG_REBUILD_ERROR", exc)


def watchdog_reset(reason: str = ""):
    """Feed the dog: cancel the previous timer and arm a fresh one."""
    global _watchdog_timer
    with _watchdog_lock:
        if _watchdog_timer is not None:
            _watchdog_timer.cancel()
            _watchdog_timer = None
        timer = threading.Timer(_effective_watchdog_timeout(), _watchdog_fire, args=(reason,))
        timer.daemon = True
        timer.start()
        _watchdog_timer = timer


def watchdog_stop():
    """Stop the dog. NOTE (v8.10 fix, preserved): never clear _watchdog_triggered
    here — only _reconnect_after_watchdog() may clear it after a full reconnect."""
    global _watchdog_timer, _watchdog_consecutive
    with _watchdog_lock:
        if _watchdog_timer is not None:
            _watchdog_timer.cancel()
            _watchdog_timer = None
        if not _watchdog_triggered.is_set():
            _watchdog_consecutive = 0   # 正常完成 → reset 連續計數


class WatchdogTriggered(Exception):
    """Raised so blocking UI operations abort once the watchdog rebuilt Docker."""


def _check_watchdog_triggered():
    if _watchdog_triggered.is_set():
        raise WatchdogTriggered("Watchdog 已觸發，Docker 重建中/已完成")


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 12 — ROUND0 CACHE STRATEGY (PROTECTED file names/format, unchanged)
# ══════════════════════════════════════════════════════════════════════════════
def get_round0_cache_file(market=None):
    mkt = (market or MARKET_MODE or "").upper()
    if mkt == "HK":
        return CONFIG.ROUND0_CACHE_HK_FILE
    if mkt == "US":
        return CONFIG.ROUND0_CACHE_US_FILE
    return os.path.join(CONFIG.PUBLIC_DIR, f"combined_stocks_{mkt.lower()}.json")


def _round0_sort_tabs(tabs):
    def _key(value):
        value = str(value).strip()
        m = re.match(r"^([A-Za-z]+)(\d+)$", value)
        if m:
            return (m.group(1).lower(), int(m.group(2)))
        return (value.lower(), 0)

    return sorted({str(t).strip() for t in tabs if str(t).strip()}, key=_key)


def _atomic_write_json(filepath, data):
    tmp = f"{filepath}.tmp.{os.getpid()}"
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump(data, fh, ensure_ascii=False, indent=2)
    os.replace(tmp, filepath)


def refresh_round0_public_file():
    """Merge HK + US caches into the public combined_stocks.json (format frozen)."""
    merged_tabs = set()
    merged_rows = {}
    source_files = []

    for mkt in ("HK", "US"):
        cache_file = get_round0_cache_file(mkt)
        if not os.path.exists(cache_file):
            continue
        try:
            with open(cache_file, "r", encoding="utf-8") as fh:
                cache = json.load(fh)
            if cache.get("market") != mkt:
                continue
            source_files.append(os.path.basename(cache_file))
            merged_tabs.update(cache.get("tabs", []))
            for row in cache.get("data", []):
                if not row or len(row) < 2:
                    continue
                code = str(row[0]).strip()
                if not code:
                    continue
                fixed = list(row)
                while len(fixed) < 4:
                    fixed.append("")
                merged_rows[code] = fixed
        except Exception as exc:
            log_exception("ROUND0_MERGE_FAILED", exc, cache_file=cache_file)

    public_data = {
        "market": "BOTH",
        "tabs": _round0_sort_tabs(merged_tabs),
        "data": list(merged_rows.values()),
    }
    _atomic_write_json(CONFIG.ROUND0_FILE, public_data)
    _atomic_write_json(CONFIG.ROUND0_CACHE_META_FILE, {
        "updated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "public_file": os.path.basename(CONFIG.ROUND0_FILE),
        "cache_files": source_files,
        "count": len(public_data["data"]),
    })
    return public_data


def ensure_round0_cache_from_legacy(market):
    cache_file = get_round0_cache_file(market)
    if os.path.exists(cache_file):
        return cache_file
    if os.path.exists(CONFIG.ROUND0_CACHE_META_FILE):
        return cache_file
    if not os.path.exists(CONFIG.ROUND0_FILE):
        return cache_file
    try:
        with open(CONFIG.ROUND0_FILE, "r", encoding="utf-8") as fh:
            legacy = json.load(fh)
        if legacy.get("market") == market and legacy.get("tabs") and legacy.get("data"):
            _atomic_write_json(cache_file, legacy)
            lp(f"   ♻️ 已將舊版 combined_stocks.json 遷移為 {os.path.basename(cache_file)}")
    except Exception as exc:
        log_exception("ROUND0_LEGACY_MIGRATE_FAILED", exc, market=market)
    return cache_file


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 13 — MARKET MODE + BASELINE TEXT PARSERS (unchanged semantics)
# ══════════════════════════════════════════════════════════════════════════════
# F-TIME:SWITCH-CONST — 切市固定推遲常數（用戶拍板）：
#   港→美 = 美股開市第一支收K HHMM − 15 秒；美→港 = 美股最後收K HHMM + 15 分 45 秒
#   HHMM 值由 GD sessions JSON US_STOCK windows 讀（唔寫死）；推遲係固定常數。
SWITCH_US_OPEN_LEAD_SEC = int(os.environ.get("SWITCH_US_OPEN_LEAD_SEC", "15") or "15")
SWITCH_US_CLOSE_TRAIL_SEC = int(os.environ.get("SWITCH_US_CLOSE_TRAIL_SEC", str(15 * 60 + 45)) or str(15 * 60 + 45))


def get_market_mode():
    # R107:CYCLE — 市場切換循環統一：星期一至星期日都用同一個循環（R90 移除 IDLE 一刀切後，
    # 星期六日都照一至五咁切換：ET 04:01-20:08 → US，其餘 → HK）。
    # F-TIME:SWITCH — 切市時間由 GD sessions 計（R107 升級）：
    #   轉美 = US_STOCK dayStart（美股開市第一支收K）− 15 秒；轉港 = US_STOCK dayEnd（美股最後收K）+ 15 分 45 秒。
    #   收唔收由 normalize 窗口/週末閘口決定（_weekday_session_ok 由 GD 計算）。
    if FORCE_MARKET in ("HK", "US"):
        return FORCE_MARKET
    # FIX K-17：兩邊都係週末先算真放假（HK 曆六/日 兼 紐約曆六/日）——
    # 以前呢個函數永遠回唔到 IDLE，週末照巡倉；下面 boot/loop 已有「休市等 60s」處理。
    # 注意：HKT 星期六凌晨 = ET 星期五（美股仲開緊）→ 唔好一刀切。
    _hk_now_idle = datetime.now(HK_TZ)
    _et_now_idle = datetime.now(US_TZ)
    if _hk_now_idle.weekday() >= 5 and _et_now_idle.weekday() >= 5:
        # FIX K-17b（24×7 週末照爬）：名單有 24/7 品種（crypto，E=1440）就唔准 IDLE——
        # BTC/ETH 冇週末，星期六日照一至五循環爬；HK/US 股期貨照舊由
        # _weekday_session_ok（R107:WEEKEND）閘走，唔會產假 bar。
        # 淨係「名單冇 24/7 品種」先維持原 K-17 放假。
        _c247 = CRYPTO_SYMBOLS if CRYPTO_SYMBOLS is not None else {s for s, e in SYMBOL_E.items() if e == 1440}
        # 慣例同 L661 一致：None=GD 未載入→用內建 SYMBOL_E 兜底；空 set=真係冇 24/7 品種。
        if not _c247:
            return "IDLE"
        # 有 24/7 → 唔攞 IDLE，落下面照平日 US/HK 時間切市（R107:CYCLE 語義週末一致）
    _ws = ((SESSIONS_CFG or {}).get("US_STOCK") or {}).get("windows")
    if _ws:
        _day_start = min(s for (s, e, _c) in _ws if s > 0)
        _day_end = max(e for (s, e, _c) in _ws if e < 1440)
    else:
        _day_start, _day_end = 241, 1200  # LAST_RESORT 兜底（GD 未載入）
    ny_time = datetime.now(US_TZ)
    ny_sec = ny_time.hour * 3600 + ny_time.minute * 60 + ny_time.second
    _start_sec = _day_start * 60 - SWITCH_US_OPEN_LEAD_SEC
    _end_sec = _day_end * 60 + SWITCH_US_CLOSE_TRAIL_SEC
    if _start_sec <= ny_sec < _end_sec:
        return "US"
    return "HK"


def cn(v, is_t=False):
    """Chinese numeric suffix expansion (兆/億/千萬/百萬/萬/千/百) -> plain string."""
    if not v:
        return ""
    val_str = v.replace(",", "").strip()
    multiplier = 1.0

    if "兆" in val_str:
        multiplier = 1000000000000.0
        val_str = val_str.replace("兆", "")
    elif "億" in val_str:
        multiplier = 100000000.0
        val_str = val_str.replace("億", "")
    elif "千萬" in val_str:
        multiplier = 10000000.0
        val_str = val_str.replace("千萬", "")
    elif "百萬" in val_str:
        multiplier = 1000000.0
        val_str = val_str.replace("百萬", "")
    elif "萬" in val_str:
        multiplier = 10000.0
        val_str = val_str.replace("萬", "")
    elif "千" in val_str:
        multiplier = 1000.0
        val_str = val_str.replace("千", "")
    elif "百" in val_str:
        multiplier = 100.0
        val_str = val_str.replace("百", "")

    try:
        num = float(val_str) * multiplier
        if is_t:
            num = round(num, 4)
            if num.is_integer():
                return str(int(num))
            return f"{num:.4f}".rstrip("0").rstrip(".")
        num = round(num, 3)
        if num.is_integer():
            return str(int(num))
        return f"{num:.3f}".rstrip("0").rstrip(".")
    except ValueError:
        return val_str


def parse_futu_t(t_raw):
    """futu legend T1 值 -> HHMM 字串（保留前導零）。
    R83:T-PARSE 支援：0036 / 0936 / 935 / 845.00 / 2,358.00 / 2358.00 / 9:35 / 36 / 16。
    唔可以用 cn(is_t=True)：float 轉換會剝走前導零（"0036"->"36"->HHMM_OUT_OF_RANGE 元兇）。
    """
    if not t_raw:
        return ""
    s = str(t_raw).strip()
    for _k in ("兆", "億", "千萬", "百萬", "萬", "千", "百"):
        s = s.replace(_k, "")
    s = s.replace(",", "")  # 千分位 2,358.00 -> 2358.00
    if ":" in s:  # 9:35 / 09:35
        _p = s.split(":")
        _h = _p[0].strip()
        _m = _p[1].strip() if len(_p) > 1 else "0"
        _m = _m.split(".")[0]
        if _h.isdigit() and _m.isdigit():
            return f"{int(_h):02d}{int(_m):02d}"
        return ""
    if "." in s:  # 2358.00 -> 2358（保留前導零）
        s = s.split(".")[0]
    if not s.isdigit():
        return ""
    if len(s) <= 2:  # 16 -> 1600；36 -> 0036（futu 剝零版凌晨 00:36）
        _n = int(s)
        return f"{_n:02d}00" if _n <= 23 else f"00{_n:02d}"
    _s4 = s.zfill(4)  # 935 -> 0935；0036 保持
    _hh, _mm = int(_s4[:2]), int(_s4[2:])
    if _hh > 23 or _mm > 59:
        return ""
    return _s4


def is_valid_tab(text):
    return bool(TAB_VALID_PAT.match(text.strip()))


def extract_code_and_name(raw_name: str):
    clean = re.sub(r"\s*[(（](?:期貨)?主連 [^)）]*[)）]", "", raw_name).strip()
    parts = clean.split(None, 1)
    code = parts[0] if parts else clean
    name_only = parts[1].strip() if len(parts) > 1 else ""
    name_only = re.sub(r"\s*期貨主連\s*$", "", name_only).strip()
    name_only = re.sub(r"\s*主連\s*$", "", name_only).strip()
    name_only = re.sub(r"main\s*$", "", name_only, flags=re.IGNORECASE).strip()
    return code, name_only


def clean_stock_name(name: str) -> str:
    name = re.sub(r"\s*[(（]\d{3,5}[)）]\s*", " ", name).strip()
    name = re.sub(r"\s*期貨主連\s*$", "", name).strip()
    name = re.sub(r"\s*主連\s*$", "", name).strip()
    name = re.sub(r"\s*main\s*$", "", name, flags=re.IGNORECASE).strip()
    return name


def parse_legend_new(legend: str):
    """Parse the futu chart legend text (G1 ... T1/O1/C1/H1/L1/V1/A1 ...)."""
    if not legend or "G1" not in legend:
        return None
    bars = []
    i = 1
    while True:
        t_m = re.search(rf"T{i}:([0-9:,\.]+[百千萬億兆]*)", legend)  # P1-02: 收冒號（T1:09:30 唔好只食到 09）
        if not t_m:
            break
        o_m = re.search(rf"O{i}:([-\d,\.]+[百千萬億兆]*)", legend)
        c_m = re.search(rf"C{i}:([-\d,\.]+[百千萬億兆]*)", legend)
        h_m = re.search(rf"H{i}:([-\d,\.]+[百千萬億兆]*)", legend)
        l_m = re.search(rf"L{i}:([-\d,\.]+[百千萬億兆]*)", legend)
        v_m = re.search(rf"V{i}:([-\d,\.]+[百千萬億兆]*)", legend)
        a_m = re.search(rf"A{i}:([-\d,\.]+[百千萬億兆]*)", legend)
        bars.append({
            "T": parse_futu_t(t_m.group(1)),  # R83:T-USE
            "O": cn(o_m.group(1)) if o_m else "",
            "C": cn(c_m.group(1)) if c_m else "",
            "H": cn(h_m.group(1)) if h_m else "",
            "L": cn(l_m.group(1)) if l_m else "",
            "V": cn(v_m.group(1)) if v_m else "",
            "A": cn(a_m.group(1)) if a_m else "",
        })
        i += 1
    return {"bars": bars}


def parse_klines_from_xml_new(xml, name_to_symbol):
    """Baseline XML -> raw bar items [{symbol, data:{T,O,C,H,L,V,A}}] (unchanged)."""
    results, seen = [], set()
    try:
        root = ET.fromstring(xml)
        for item in root.findall(f".//node[@resource-id='{RID_RV_ROOT}']"):
            name_el = item.find(f".//node[@resource-id='{RID_STOCK_NAME}']")
            name_raw = name_el.attrib.get("text", "").strip() if name_el is not None else ""
            if not name_raw:
                continue
            legend_el = item.find(f".//node[@resource-id='{RID_INDEX}']")
            if legend_el is None:
                continue
            legend = legend_el.attrib.get("text", "")
            if not legend or "G1" not in legend:
                continue
            parsed = parse_legend_new(legend)
            if not parsed:
                continue

            code, _ = extract_code_and_name(name_raw)
            clean_full = re.sub(r"\s*[(（](?:期貨)?主連 [^)）]*[)）]", "", name_raw).strip()
            cleaned_name = clean_stock_name(name_raw)
            symbol = (
                name_to_symbol.get(clean_full)
                or name_to_symbol.get(cleaned_name)
                or name_to_symbol.get(name_raw)
                or name_to_symbol.get(code)
                or code
            )
            if not symbol:
                continue

            bars = parsed.get("bars", [])
            bars.reverse()  # chronological order
            for bar in bars:
                t_val = bar.get("T", "")
                if (symbol, t_val) in seen:
                    continue
                seen.add((symbol, t_val))
                results.append({
                    "symbol": symbol,
                    "data": {
                        "T": t_val,
                        "O": bar.get("O", ""),
                        "C": bar.get("C", ""),
                        "H": bar.get("H", ""),
                        "L": bar.get("L", ""),
                        "V": bar.get("V", ""),
                        "A": bar.get("A", ""),
                    },
                })
    except Exception as exc:
        log_exception("XML_KLINE_PARSE_FAILED", exc)
    return results


def get_mid_y(bounds_str):
    try:
        m = re.match(r"\[-?\d+,(-?\d+)\]\[-?\d+,(-?\d+)\]", bounds_str)
        if m:
            return (int(m.group(1)) + int(m.group(2))) / 2
    except Exception:
        pass
    return -1


def parse_list_page_from_xml(xml):
    stocks = {}
    try:
        root = ET.fromstring(xml)
        code_nodes = root.findall(".//node[@resource-id='cn.futu.trader:id/stockCodeText']")
        name_nodes = root.findall(".//node[@resource-id='cn.futu.trader:id/stockNameText']")

        f_nodes = []
        for node in root.iter("node"):
            text = node.attrib.get("text", "").strip()
            if re.search(r"[百千萬億兆]$", text) and node.attrib.get("class") == "android.widget.TextView":
                f_nodes.append(node)

        for code_node in code_nodes:
            code = code_node.attrib.get("text", "").strip()
            if not code:
                continue
            c_mid_y = get_mid_y(code_node.attrib.get("bounds", ""))
            if c_mid_y < 0:
                continue
            name = ""
            for name_node in name_nodes:
                if abs(get_mid_y(name_node.attrib.get("bounds", "")) - c_mid_y) < 35:
                    name = clean_stock_name(name_node.attrib.get("text", "").strip())
                    break
            f_val = ""
            for f_node in f_nodes:
                if abs(get_mid_y(f_node.attrib.get("bounds", "")) - c_mid_y) < 35:
                    f_val = cn(f_node.attrib.get("text", "").strip())
                    break
            stocks[code] = {"name": name if name else code, "F": f_val}
    except Exception as exc:
        log_exception("XML_LIST_PARSE_FAILED", exc)
    return stocks


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 14 — DOCKER / ADB / DEVICE LIFECYCLE (baseline, preserved)
# ══════════════════════════════════════════════════════════════════════════════
def is_docker_running():
    try:
        result = subprocess.run(
            f"docker inspect -f '{{{{.State.Running}}}}' {CONFIG.DOCKER_NAME} 2>/dev/null",
            shell=True, capture_output=True, text=True, timeout=5)
        return result.stdout.strip() == "true"
    except Exception:
        return False


def is_device_responding():
    try:
        result = subprocess.run(
            f"adb -s {CONFIG.DEVICE_ID} shell getprop ro.build.version.release",
            shell=True, capture_output=True, text=True, timeout=3)
        return result.returncode == 0 and bool(result.stdout.strip())
    except Exception:
        return False


def find_pid():
    try:
        result = subprocess.run(f"adb -s {CONFIG.DEVICE_ID} shell pidof {APP_PACKAGE}",
                                shell=True, capture_output=True, text=True, timeout=3)
        pid_str = result.stdout.strip()
        if pid_str:
            parts = pid_str.split()
            if parts:
                return int(parts[0])
    except Exception:
        pass
    return None


def docker_recovery():
    """Rebuild the Redroid container from the market seed directory (baseline)."""
    try:
        stop_futu_update_popup_guard()
    except Exception:
        pass
    # FIX E-09：{n}／{market} 雙佔位用 replace（唔 .format，免其它花括號滋擾）；
    # 缺 {market} 或解完仲有花括號→ fail-loud（唔准再整出 /root/redroid_1{market} 字面目錄）
    _seed_tmpl = CONFIG.DOCKER_SEED_DIR_TEMPLATE
    if "{market}" not in _seed_tmpl:
        raise RuntimeError("DOCKER_SEED_DIR_TEMPLATE 缺 {market} 佔位符（E-09 合約）: " + _seed_tmpl)
    target_data_dir = _seed_tmpl.replace("{n}", str(CONFIG.MACHINE_NUM)).replace("{market}", MARKET_MODE.lower())
    if "{" in target_data_dir or "}" in target_data_dir:
        raise RuntimeError("DOCKER_SEED_DIR_TEMPLATE 解出嚟仲有未替換佔位符: " + target_data_dir)

    lp(f"\n🚨 [環境重建] 重建容器 {CONFIG.DOCKER_NAME} (來源種子: {target_data_dir})...")
    append_log("DOCKER_REBUILD", f"Target seed: {target_data_dir}")
    RUNTIME.bump("docker_rebuilds")
    ram_dir = f"/dev/shm/{CONFIG.DOCKER_NAME}_ram"

    subprocess.run(f"docker rm -f {CONFIG.DOCKER_NAME} 2>/dev/null", shell=True, timeout=20)
    subprocess.run(f"fuser -k {CONFIG.DOCKER_PORT}/tcp 2>/dev/null", shell=True, timeout=5)
    subprocess.run("pkill -f 'adb' 2>/dev/null", shell=True, timeout=5)

    os.makedirs(CONFIG.DOCKER_SHM, exist_ok=True)
    if os.path.isdir(ram_dir):
        subprocess.run(f"rm -rf {ram_dir}", shell=True, timeout=20)
    os.makedirs(ram_dir, exist_ok=True)
    os.chmod(ram_dir, 0o777)

    if os.path.isdir(target_data_dir):
        lp(f"📁 複製數據中 ({target_data_dir} -> {ram_dir})...")
        subprocess.run(
            f"cp --reflink=auto -a {target_data_dir}/. {ram_dir}/ 2>/dev/null || "
            f"cp -a {target_data_dir}/. {ram_dir}/ 2>/dev/null || true",
            shell=True, timeout=60)
    else:
        lp(f"⚠️ 找不到目錄 {target_data_dir}，建立空目錄！")
        os.makedirs(target_data_dir, exist_ok=True)

    lp("🐳 啟動 Docker 容器 (90x1024, 15fps, 72dpi, 綁定Core0, 0.9核)...")
    docker_run_cmd = (
        f"docker run -itd --privileged "
        f"--name {CONFIG.DOCKER_NAME} "
        f"-p {CONFIG.DOCKER_PORT}:5555 "
        f"--dns 1.1.1.1 --dns 8.8.8.8 "
        f"--shm-size=2g --memory=4.5g --memory-swap=4.5g --cpuset-cpus=0 --cpus=0.9 "
        f"--log-opt max-size=50m --log-opt max-file=3 "
        f"-v {CONFIG.DOCKER_SHM}:/data/local/tmp "
        f"-v {ram_dir}:/data "
        f"{CONFIG.DOCKER_IMAGE} "
        f"androidboot.redroid_width=90 androidboot.redroid_height=1024 "
        f"androidboot.redroid_dpi=72 "
        f"androidboot.redroid_fps=15 androidboot.redroid_gpu_mode=guest "
        f"androidboot.use_memfd=true "
        f"persist.sys.timezone=Asia/Hong_Kong persist.sys.locale=zh-HK "
        f"debug.sf.nobootanimation=1 "
        f"ro.sys.fw.bg_apps_limit=10 dalvik.vm.heapstartsize=256m "
        f"dalvik.vm.heapgrowthlimit=2048m "
        f"dalvik.vm.heapsize=4096m dalvik.vm.dex2oat-filter=speed "
        f"dalvik.vm.image-dex2oat-filter=speed "
        f"dalvik.vm.dex2oat-threads=1"
    )

    result = subprocess.run(docker_run_cmd, shell=True, capture_output=True, text=True, timeout=15)
    if "Error" in (result.stderr or "") or result.returncode != 0:
        lp(f"⚠️ Docker 啟動異常: {(result.stderr or '').strip()[:100]}")
        time.sleep(2)
        subprocess.run(f"docker rm -f {CONFIG.DOCKER_NAME} 2>/dev/null", shell=True, timeout=15)
        subprocess.run(docker_run_cmd, shell=True, timeout=15)

    subprocess.run("adb start-server > /dev/null 2>&1", shell=True, timeout=5)

    def connect_adb_bg():
        for _ in range(15):
            res = subprocess.run(f"adb connect {CONFIG.DEVICE_ID}", shell=True,
                                 capture_output=True, text=True, timeout=5)
            if "connected" in res.stdout or "already connected" in res.stdout:
                break
            time.sleep(1)

    threading.Thread(target=connect_adb_bg, daemon=True).start()
    lp("✅ Docker & ADB 啟動中\n")
    return True


def wait_device_ready(timeout=60, check_interval=2):
    lp(f"⏳ 檢測設備就緒... (最多 {timeout}s)")
    start_time = time.time()
    check_count = 0
    last_check_time = 0

    while time.time() - start_time < timeout:
        current_time = time.time()
        if current_time - last_check_time < check_interval:
            time.sleep(0.1)
            continue
        last_check_time = current_time
        check_count += 1
        elapsed = int(current_time - start_time)

        if not is_docker_running() or not is_device_responding():
            if check_count % 3 == 1:
                lp(f"   [{elapsed}s] ⏳ Docker/設備未就緒...")
            time.sleep(0.5)
            continue

        try:
            boot_result = subprocess.run(
                f"adb -s {CONFIG.DEVICE_ID} shell getprop sys.boot_completed",
                shell=True, capture_output=True, text=True, timeout=3)
            if "1" in boot_result.stdout:
                lp(f"✅ 設備已就緒！({elapsed}s)")
                subprocess.run(f'adb -s {CONFIG.DEVICE_ID} shell "stop logd;"',
                               shell=True, capture_output=True, timeout=5)
                return True
        except Exception:
            pass

    lp(f"❌ 設備超時未就緒 ({timeout}s)")
    return False


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 15 — FUTU UPDATE POPUP GUARD (baseline, preserved)
# ══════════════════════════════════════════════════════════════════════════════
UPDATE_POPUP_GUARD_INTERVAL = 0.20
_update_popup_guard_lock = threading.Lock()
_update_popup_guard_stop = None
_update_popup_guard_epoch = 0


def _click_futu_update_later_once(d):
    try:
        later_btn = d(resourceId=RID_UPDATE_NEGATIVE, text=UPDATE_LATER_TEXT)
        if not later_btn.exists(timeout=0.0):
            return False
        later_btn.click()
        lp("   ✅ [更新彈窗守衛] 已精準點擊「以後再說」")
        append_log("UPDATE_DIALOG_DISMISSED", "guard clicked negative_btn text=以後再說")
        return True
    except Exception:
        return False


def start_futu_update_popup_guard(d):
    global _update_popup_guard_stop, _update_popup_guard_epoch
    new_stop = threading.Event()
    with _update_popup_guard_lock:
        old_stop = _update_popup_guard_stop
        _update_popup_guard_stop = new_stop
        _update_popup_guard_epoch += 1
        my_epoch = _update_popup_guard_epoch

    if old_stop is not None:
        old_stop.set()

    def _guard_worker():
        while not new_stop.is_set():
            with _update_popup_guard_lock:
                if (my_epoch != _update_popup_guard_epoch
                        or _update_popup_guard_stop is not new_stop):
                    return
            clicked = _click_futu_update_later_once(d)
            new_stop.wait(0.35 if clicked else UPDATE_POPUP_GUARD_INTERVAL)

    threading.Thread(target=_guard_worker, name="futu-update-popup-guard", daemon=True).start()


def stop_futu_update_popup_guard():
    global _update_popup_guard_stop
    with _update_popup_guard_lock:
        stop_event = _update_popup_guard_stop
        _update_popup_guard_stop = None
    if stop_event is not None:
        stop_event.set()
        return True
    return False


# BUG B fix：偵測「登入」畫面 → 自動按「下一步」；密碼頁自動輸入密碼（env 讀取，唔硬編碼）
_RID_TXT_METHOD = "cn.futu.trader:id/txt_method"
_RID_MAIN_BTN = "cn.futu.trader:id/main_btn"          # 首頁「登入」大按鈕（新偵測）
_RID_SECONDARY_BTN = "cn.futu.trader:id/secondary_btn"  # 首頁「註冊」
_RID_INPUT_EMAIL = "cn.futu.trader:id/input_email"
_RID_PASSWORD_EDIT = "cn.futu.trader:id/password_edit_text"
_RID_REAL_EDIT = "cn.futu.trader:id/uikit_real_edit_text"
_RID_CONTINUE_BTN = "cn.futu.trader:id/continue_button"
_RID_BTN_TEXT = "cn.futu.trader:id/btn_text"
_RID_TAB_TITLE = "cn.futu.trader:id/tab_title"


def _type_password_reliably(d, pw_field, pw):
    """輸入密碼：淨用 adb shell input text（用戶實測 confirm 呢個方法寫入到）。

    重點：**唔靠 get_text() 驗證**——用戶實測密碼寫入咗但 get_text() 讀返係空，
    所以唔可以用讀返嚟判斷。click field → adb input → 當成功（screen 上真係入咗）。
    """
    import subprocess as _sp
    try:
        pw_field.click()
        time.sleep(0.5)
        # adb shell input text 專用轉義（唔好用 urllib.quote——實測 @ 會變 %40 寫入）
        # 規則：空格 -> %s；shell 字元 &|;()<> 前加 \；@ ! - _ . 等直接原樣
        esc = ""
        for ch in pw:
            if ch == " ":
                esc += "%s"
            elif ch in "&|;()<>\"'`$*?[]{}":
                esc += "\\" + ch
            else:
                esc += ch
        _sp.run(f"adb -s {CONFIG.DEVICE_ID} shell input text {esc}", shell=True, timeout=15)
        time.sleep(0.8)
        lp("      [登入處理] 密碼已用 adb input 寫入（adb 專用轉義，@ 原樣）")
        append_log("LOGIN_PASSWORD_ENTERED", "method=adb_input_esc")
        return True
    except Exception as exc:
        lp(f"      [登入處理] adb input 異常: {exc}")
        return False


# 驗證碼頁面特徵（text：验证码 / 常規驗證 / 刷新驗證）
_CAPTCHA_TEXTS = ("验证码", "驗證碼", "常規驗證", "常規驗證", "刷新驗證")


def _detect_captcha(xml: str) -> bool:
    """偵測驗證碼頁面（無 resource-id 嘅 验证码/常規驗證/刷新驗證 text）。"""
    if not xml:
        return False
    hits = [t for t in _CAPTCHA_TEXTS if t in xml]
    return len(hits) >= 2   # 至少要 2 個特徵先算（避免誤判）


# 自動偵測本機對外 IP（MY_IP 留空時用）——cache 一次，唔會每次 call 外部
_AUTO_IP_CACHE = {"val": None}


def _auto_detect_ip() -> str:
    """偵測本機對外 IP：
       1) 試外部服務 api.ipify.org / ifconfig.me（timeout 短）
       2) 失敗 → 本機網卡 IP（socket 連外部攞本機出口 IP；再 fallback hostname）
       cache 一次，唔重複 call。
    """
    if _AUTO_IP_CACHE["val"]:
        return _AUTO_IP_CACHE["val"]
    ip = ""
    # 方法 1: 外部 IP 服務
    for svc in ("https://api.ipify.org", "https://ifconfig.me", "http://ip-api.com/line/?fields=query"):
        try:
            import requests as _rq
            r = _rq.get(svc, timeout=3)
            txt = (r.text or "").strip()
            if txt and txt.replace(".", "").isdigit():
                ip = txt
                break
        except Exception:
            continue
    # 方法 2: socket 連外部攞本機出口 IP（唔使出真流量，只係 connect）
    if not ip:
        try:
            import socket as _sk
            sck = _sk.socket(_sk.AF_INET, _sk.SOCK_DGRAM)
            sck.connect(("8.8.8.8", 80))
            ip = sck.getsockname()[0]
            sck.close()
        except Exception:
            ip = ""
    # 方法 3: hostname
    if not ip:
        try:
            import socket as _sk
            ip = _sk.gethostbyname(_sk.gethostname())
        except Exception:
            ip = "(unknown)"
    _AUTO_IP_CACHE["val"] = ip or "(unknown)"
    lp(f"      [IP] 自動偵測本機對外 IP: {_AUTO_IP_CACHE['val']}")
    return _AUTO_IP_CACHE["val"]


def _notify_login_needed():
    """發 Telegram：'(<本機ip>)要登入'。由 .env 讀 token/chat/ip，唔硬編碼。"""
    token = CONFIG.TELEGRAM_BOT_TOKEN
    chat = CONFIG.TELEGRAM_CHAT_ID
    if not token or not chat:
        lp("⚠️ [TG] TELEGRAM_BOT_TOKEN/TELEGRAM_CHAT_ID 未設定——唔發通知")
        append_log("TG_NOT_CONFIGURED", "telegram not configured")
        return
    ip = CONFIG.MY_IP or _auto_detect_ip()
    text = f"({ip})要登入"
    try:
        import requests as _rq
        _rq.post(
            f"https://api.telegram.org/bot{token}/sendMessage",
            json={"chat_id": chat, "text": text},
            timeout=10,
        )
        lp(f"      [TG] 已發送通知：{text}")
        append_log("TG_SENT", text)
    except Exception as exc:
        lp(f"      [TG] 發送通知異常: {exc}")


def _handle_captcha_stop():
    """偵測到驗證碼 → 立即停止 futu.py + 發 TG 通知。"""
    lp("\n🚨 [驗證碼] 偵測到驗證碼頁面——需要人手登入，停止運作！")
    append_log("CAPTCHA_DETECTED", "captcha page, stopping")
    _notify_login_needed()
    time.sleep(2.0)   # 等 TG 送出
    os._exit(1)       # 停止（pm2 會睇 restart policy）


def _handle_login_screen(d, max_steps=6):
    """偵測並處理富途登入流程：
       1) 登入頁（txt_method=登入 / input_email 存在）→ 按「下一步」
       2) 密碼頁（password_edit_text / uikit_real_edit_text=輸入密碼）→ 輸入密碼 → 按「下一步」
       密碼由 CONFIG.FUTU_LOGIN_PASSWORD（.env）讀取；未設定就 log warning 唔嘗試輸入。
       每次最多 max_steps 步，避免無限 loop。
    """
    try:
        for _step in range(max_steps):
            xml = d.dump_hierarchy(compressed=False)
            if not xml:
                return False
            # 驗證碼頁面：立即停止 + TG 通知
            if _detect_captcha(xml):
                _handle_captcha_stop()
                return False

            # 判定目前係邊種畫面
            has_main_login = (_RID_MAIN_BTN in xml and "登入" in xml) and (_RID_SECONDARY_BTN in xml)
            has_login = (_RID_TXT_METHOD in xml and "登入" in xml) or (_RID_INPUT_EMAIL in xml)
            has_pw = (_RID_PASSWORD_EDIT in xml) or ("輸入密碼" in xml and _RID_REAL_EDIT in xml)
            has_next = (_RID_CONTINUE_BTN in xml) or ("下一步" in xml and _RID_BTN_TEXT in xml)

            # ── 密碼頁：淨係輸入密碼一次，唔好亂按「下一步」 ──
            if has_pw:
                pw = CONFIG.FUTU_LOGIN_PASSWORD
                if not pw:
                    lp("⚠️ [登入處理] 偵測到密碼頁，但 FUTU_LOGIN_PASSWORD 未設定——唔嘗試輸入")
                    append_log("LOGIN_NO_PASSWORD", "password page but FUTU_LOGIN_PASSWORD not set")
                    return True
                pw_field = None
                pe = d(resourceId=_RID_PASSWORD_EDIT)
                if pe.exists(timeout=0.3):
                    pw_field = pe
                else:
                    re_ = d(resourceId=_RID_REAL_EDIT)
                    if re_.exists(timeout=0.3):
                        txt = ""
                        try:
                            txt = str(re_.get_text() or "")
                        except Exception:
                            txt = ""
                        if "密碼" in txt or "password" in txt.lower():
                            pw_field = re_
                if pw_field is not None:
                    ok = _type_password_reliably(d, pw_field, pw)
                    if ok:
                        handled = True
                        # 用完密碼直接按「下一步」（用戶要求：用完按下一步）
                        nt = d(resourceId=_RID_BTN_TEXT, text="下一步")
                        if nt.exists(timeout=0.6):
                            nt.click()
                            lp("      [登入處理] 密碼已輸入，已按「下一步」")
                            append_log("LOGIN_PASSWORD_NEXT", "password entered + clicked 下一步")
                        else:
                            cb = d(resourceId=_RID_CONTINUE_BTN)
                            if cb.exists(timeout=0.6):
                                cb.click()
                                lp("      [登入處理] 密碼已輸入，已按 continue_button")
                        time.sleep(1.2)
                        return True
                    lp("      [登入處理] adb input 寫入密碼失敗——唔再試")
                    append_log("LOGIN_PASSWORD_FAILED", "adb_input failed")
                    return True

            # ── 首頁登入入口（main_btn=登入 + secondary_btn=註冊）──
            if has_main_login and not has_login:
                mb = d(resourceId=_RID_MAIN_BTN, text="登入")
                if mb.exists(timeout=0.5):
                    mb.click()
                    lp("      [登入處理] 首頁偵測到「登入」，已按「登入」")
                    append_log("LOGIN_STEP", "clicked main_btn 登入")
                    time.sleep(1.5)
                    continue

            # ── 登入頁（未到密碼）：按「下一步」 ──
            if has_login and has_next:
                btn = None
                cb = d(resourceId=_RID_CONTINUE_BTN)
                if cb.exists(timeout=0.4):
                    btn = cb
                else:
                    nt = d(resourceId=_RID_BTN_TEXT, text="下一步")
                    if nt.exists(timeout=0.4):
                        btn = nt
                if btn is not None:
                    btn.click()
                    lp("      [登入處理] 已按「下一步」")
                    append_log("LOGIN_STEP", "clicked 下一步")
                    time.sleep(1.2)
                    continue

            # 密碼頁但搵唔到 input field → 試按下一步
            if has_pw and has_next and not has_login:
                nt = d(resourceId=_RID_BTN_TEXT, text="下一步")
                if nt.exists(timeout=0.4):
                    nt.click()
                    lp("      [登入處理] 已按「下一步」（密碼頁）")
                    time.sleep(1.2)
                    continue

            # ── 「下一步嗰頁」：有下一步按鈕 + 唔係 K線/自選頁 → 按下一步 ──
            #    （用戶情況：彈窗/返回令登入流程退後，可能停喺「下一步嗰頁」而冇 login/pw 特徵）
            is_market_page = (
                "cn.futu.trader:id/filter_entrance_optional_group" in xml
                or "stockCodeText" in xml
                or "tab_title" in xml
                or ("自選" in xml and "全部" in xml)
            )
            if has_next and not has_login and not has_pw and not has_main_login and not is_market_page:
                nt = d(resourceId=_RID_BTN_TEXT, text="下一步")
                if nt.exists(timeout=0.4):
                    nt.click()
                    lp("      [登入處理] 偵測到「下一步嗰頁」，已按「下一步」（繼續登入流程）")
                    append_log("LOGIN_STEP", "clicked 下一步 (next-page)")
                    time.sleep(1.2)
                    continue

            return True   # 冇登入/密碼畫面 → 正常
        return True
    except Exception as exc:
        lp(f"      [登入處理異常] {exc}")
        return False


def _dismiss_popups(d, timeout=5.0):
    lp("   → 快速檢查並關閉彈窗...")
    t_start = time.time()
    while time.time() - t_start < timeout:
        try:
            xml = d.dump_hierarchy(compressed=False)
            if not xml:
                break
            popped = False

            for text_val in ["以後再說", "我知道了", "跳過", "暫不", "關閉", "不要了"]:
                if text_val in xml:
                    node = d(text=text_val)
                    if node.exists(timeout=0.5):
                        node.click()
                        lp(f"      [自動清理] 已點擊文字: {text_val}")
                        popped = True
                        break
            if popped:
                time.sleep(0.5)
                continue

            for cid in ["cn.futu.trader:id/popup_ad_close", "cn.futu.trader:id/iv_close",
                        "cn.futu.trader:id/btn_close", "cn.futu.trader:id/close_btn",
                        "cn.futu.trader:id/tv_close", "cn.futu.trader:id/close_image",
                        "cn.futu.trader:id/btn_cancel", "cn.futu.trader:id/iv_cancel",
                        "cn.futu.trader:id/cancel"]:
                if cid in xml:
                    node = d(resourceId=cid)
                    if node.exists(timeout=0.5):
                        node.click()
                        lp(f"      [自動清理] 已點擊 ID: {cid}")
                        popped = True
                        break
            if popped:
                time.sleep(0.5)
                continue

            for desc in ["關閉", "close", "dismiss", "cancel"]:
                node = d(description=desc)
                if node.exists(timeout=0.5):
                    node.click()
                    lp(f"      [自動清理] 已點擊描述: {desc}")
                    popped = True
                    break
            if popped:
                time.sleep(0.5)
                continue
            break
        except Exception as exc:
            lp(f"      [自動清理異常]: {exc}")
            break


def ensure_app_running(d, force_restart=False):
    if force_restart:
        lp("   🔄 強制關閉 App...")
        subprocess.run(f"adb -s {CONFIG.DEVICE_ID} shell am force-stop --user 0 {APP_PACKAGE}",
                       shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        time.sleep(1.0)

    pid = find_pid()
    start_cmd = f"adb -s {CONFIG.DEVICE_ID} shell am start --user 0 -n {APP_ACTIVITY}"

    if pid and not force_restart:
        lp(f"✅ 富途 App 運行中 (PID: {pid})")
        subprocess.run(start_cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        start_futu_update_popup_guard(d)
        d.app_wait(APP_PACKAGE, front=True, timeout=3.0)
    else:
        lp(f"⚡ 啟動富途 App ({MARKET_MODE})...")
        subprocess.run(start_cmd, shell=True)
        start_futu_update_popup_guard(d)
        app_ready = d(resourceId=RID_TAB_TITLE).wait(timeout=8.0)
        opt_ready = d(resourceId=RID_OPTIONAL_GROUP).wait(timeout=3.0)
        if not app_ready and not opt_ready:
            _handle_login_screen(d)
            _dismiss_popups(d, timeout=3.0)


def restart_app_and_enter_list(d):
    lp("   🚨 [極速修復] 強制重啟富途並進入 K 線頁...")
    append_log("APP_RESTART", "Triggered app restart")
    RUNTIME.bump("app_restarts")
    RUNTIME.set(ui_recovery_state="app_restart")

    subprocess.run(f"adb -s {CONFIG.DEVICE_ID} shell am force-stop --user 0 {APP_PACKAGE}", shell=True)
    time.sleep(1.0)
    subprocess.run(f"adb -s {CONFIG.DEVICE_ID} shell am start --user 0 -n {APP_ACTIVITY}", shell=True)
    start_futu_update_popup_guard(d)

    tab = d(resourceId=RID_TAB_TITLE, text="自選")
    if not tab.wait(timeout=10.0):
        _dismiss_popups(d, timeout=3.0)
        tab.wait(timeout=2.0)

    for _ in range(3):
        try:
            if tab.exists:
                tab.click()
                btn = d(resourceId=RID_HDR_LIST)
                if btn.wait(timeout=3.0):
                    btn.click()
                    opt = d(resourceId=RID_OPTIONAL_GROUP)
                    if opt.wait(timeout=3.0):
                        stop_futu_update_popup_guard()
                        break
        except Exception:
            d.press("back")
            time.sleep(0.5)
    RUNTIME.set(ui_recovery_state="running")
    lp("   ✅ 極速重啟完畢 (已進入 K 線頁)")


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 16 — UIA HEALTH MONITOR + THREE-LEVEL RECOVERY (baseline v8.10)
# ══════════════════════════════════════════════════════════════════════════════
_switch_latency_history = []
_SWITCH_HISTORY_SIZE = 20
_SWITCH_DEGRADED_RATIO = 1.8
_SWITCH_MIN_SAMPLES = 5
_JSONRPC_HEALTH_THRESHOLD = 1.0

# ── 劣化偵測精準化（防止單次慢切換誤觸發重啟，2026-08-30）──────────────────
#   原理：單次切換慢（App 一時 busy）唔等於 jsonrpc hang。要用「持續劣化」先出手。
_SWITCH_DEGRADED_ABS_FLOOR_SEC = 8.0    # 切換 < 8s 一律唔當劣化（唔係 hang）
_SWITCH_DEGRADED_CONSECUTIVE = 3        # 要連續 3 次超標先真係觸發修復
_JSONRPC_HEALTH_WARMUP_CHECKS = 2       # uiautomator/App 重啟後要連續 2 次健康先算 OK
_RECOVERY_COOLDOWN_SEC = 300.0          # 兩次三級修復之間最少 5 分鐘（防重啟循環）
_switch_degraded_streak = 0
_last_recovery_at_ms = 0


def record_switch_latency(sw_time: float):
    _switch_latency_history.append(sw_time)
    if len(_switch_latency_history) > _SWITCH_HISTORY_SIZE:
        _switch_latency_history.pop(0)


def is_switch_degraded(sw_time: float):
    """精準化：單次慢切換（App 一時 busy）唔觸發；要「持續劣化」先觸發。

    1) 絕對下限：sw < _SWITCH_DEGRADED_ABS_FLOOR_SEC 直接當正常（7.2s 呢類唔算）。
    2) 用中位數（唔係平均數）做 baseline——單次 spike 唔會拉高基準。
    3) 要連續 _SWITCH_DEGRADED_CONSECUTIVE 次超標先回傳 True。
    """
    global _switch_degraded_streak
    if sw_time < _SWITCH_DEGRADED_ABS_FLOOR_SEC:
        _switch_degraded_streak = 0
        return False, sw_time, 0.0
    if len(_switch_latency_history) < _SWITCH_MIN_SAMPLES:
        return False, sw_time, 0.0
    samples = sorted(_switch_latency_history)
    n = len(samples)
    median = samples[n // 2] if n % 2 else (samples[n // 2 - 1] + samples[n // 2]) / 2.0
    if sw_time > median * _SWITCH_DEGRADED_RATIO:
        _switch_degraded_streak += 1
    else:
        _switch_degraded_streak = 0
    return _switch_degraded_streak >= _SWITCH_DEGRADED_CONSECUTIVE, sw_time, median


def check_jsonrpc_latency(d, label=""):
    try:
        t0 = time.perf_counter()
        d.window_size()
        return time.perf_counter() - t0
    except Exception as exc:
        lp(f"      [jsonrpc] {label} 異常: {exc}")
        return -1.0


def _is_jsonrpc_healthy(d) -> bool:
    lat = check_jsonrpc_latency(d, "healthcheck")
    if lat >= 0:
        lp(f"      [jsonrpc] healthcheck = {lat*1000:.0f}ms (閾值 {_JSONRPC_HEALTH_THRESHOLD*1000:.0f}ms)")
    return 0 <= lat < _JSONRPC_HEALTH_THRESHOLD


def _wait_jsonrpc_healthy(d, checks=None, timeout=20.0):
    """重啟 uiautomator/App 之後，要「連續 N 次」healthcheck 都快先算健康。

    避免重啟後第一次 call 一定慢（atx-agent / accessibility bridge 重新建立）而被
    誤判做失敗——呢個就係 log 入面 healthcheck=16996ms 之後即刻 126ms 嘅元兇。
    """
    need = int(checks if checks is not None else _JSONRPC_HEALTH_WARMUP_CHECKS)
    deadline = time.time() + float(timeout)
    ok = 0
    while time.time() < deadline:
        if _is_jsonrpc_healthy(d):
            ok += 1
            if ok >= need:
                return True
        else:
            ok = 0
        time.sleep(1.0)
    return False


def three_level_recovery(d, d_ref, reason=""):
    """L1 restart uiautomator -> L2 restart App -> L3 rebuild Docker (baseline)."""
    global _switch_degraded_streak
    lp(f"\n🔧 [三級修復] 啟動，原因: {reason}")
    append_log("THREE_LEVEL_RECOVERY_START", reason)
    RUNTIME.set(ui_recovery_state="three_level_recovery")

    lp("   🔧 [L1] 重啟 uiautomator (App 保持運行)...")
    l1_ok = False
    try:
        def _l1_restart():
            try:
                d.uiautomator.stop()
                time.sleep(0.5)
                d.uiautomator.start()
            except Exception as inner:
                lp(f"      [L1] stop/start 異常: {inner}")

        thread = threading.Thread(target=_l1_restart, daemon=True)
        thread.start()
        thread.join(timeout=15)

        if thread.is_alive():
            lp("   ❌ [L1] stop/start 超過 15s 未返回，視為失敗")
        else:
            # 精準化：重啟後要連續 2 次健康先算 OK（第一次 call 一定慢，會誤判）
            if _wait_jsonrpc_healthy(d, timeout=20.0):
                l1_ok = True
                lp("   ✅ [L1] uiautomator 重啟成功，jsonrpc 恢復正常")
                append_log("THREE_LEVEL_RECOVERY", "L1 OK")
    except Exception as exc:
        log_exception("THREE_LEVEL_RECOVERY_L1_FAILED", exc)

    if l1_ok:
        _switch_latency_history.clear()
        _switch_degraded_streak = 0
        RUNTIME.set(ui_recovery_state="running")
        return d

    try:
        stop_futu_update_popup_guard()
        lp("   🛑 [Patch3] L1 失敗，已停止 popup guard 避免爭奪連線")
    except Exception:
        pass

    if not _is_jsonrpc_healthy(d):
        lp("   ⚡ [Patch1] L1 後 jsonrpc 仍不健康，跳過 L2 直奔 L3")
        append_log("THREE_LEVEL_RECOVERY", "L1→L3 SKIP_L2 jsonrpc_unhealthy")
    else:
        lp("   🔧 [L2] jsonrpc 健康，嘗試重啟 App...")
        l2_ok = False
        try:
            restart_app_and_enter_list(d)
            if _wait_jsonrpc_healthy(d, timeout=15.0):
                l2_ok = True
                lp("   ✅ [L2] App 重啟成功，jsonrpc 正常")
                append_log("THREE_LEVEL_RECOVERY", "L2 OK")
            else:
                lp("   ❌ [L2] App 重啟後 jsonrpc 仍不正常，跳至 L3")
                append_log("THREE_LEVEL_RECOVERY", "L2 FAIL jsonrpc_unhealthy_after_restart")
        except Exception as exc:
            log_exception("THREE_LEVEL_RECOVERY_L2_FAILED", exc)

        if l2_ok:
            _switch_latency_history.clear()
            _switch_degraded_streak = 0
            RUNTIME.set(ui_recovery_state="running")
            return d

    lp("   🔧 [L3] Docker 重建...")
    append_log("THREE_LEVEL_RECOVERY", "L3 docker_recovery")
    try:
        docker_recovery()
        if wait_device_ready(timeout=120, check_interval=2):
            new_d = connect_device()
            d_ref[0] = new_d
            lp("   ✅ [L3] Docker 重建並重連成功")
            append_log("THREE_LEVEL_RECOVERY", "L3 OK")
            _switch_latency_history.clear()
            try:
                restart_app_and_enter_list(new_d)
            except Exception as exc:
                log_exception("THREE_LEVEL_RECOVERY_L3_APP_FAILED", exc)
            RUNTIME.set(ui_recovery_state="running")
            return new_d
        lp("   ❌ [L3] 設備超時未就緒")
    except Exception as exc:
        log_exception("THREE_LEVEL_RECOVERY_L3_FAILED", exc)
    return d_ref[0]


def connect_device():
    """uiautomator2 connection with the baseline configurator tuning."""
    if u2 is None:
        raise RuntimeError(
            "uiautomator2 is required for crawl mode but is not importable: " + str(U2_IMPORT_ERROR)
        )
    device = u2.connect(CONFIG.DEVICE_ID)
    device.implicitly_wait(10.0)
    try:
        device.jsonrpc.setConfigurator({"waitForIdleTimeout": 0, "waitForSelectorTimeout": 0})
    except Exception as exc:
        log_exception("UIA_CONFIGURATOR_FAILED", exc)
    return device


def switch_tab(d, tab_name):
    """Baseline tab switching with crash detection and escalating retries."""
    t0 = time.perf_counter()

    def _one_attempt(attempt_no, total):
        try:
            opt = d(resourceId=RID_OPTIONAL_GROUP)
            if not opt.exists(timeout=2.0):
                # 阻擋修正：撳返回前，先 check 登入/驗證碼/下一步頁面——
                # 唔可以喺登入流程撳返回（會由「下一步嗰頁」退返去「登入按鈕版面」）
                try:
                    cur_xml = d.dump_hierarchy(compressed=False)
                except Exception:
                    cur_xml = ""
                if cur_xml:
                    if _detect_captcha(cur_xml):
                        _handle_captcha_stop()
                        return False
                    is_loginish = (
                        (_RID_TXT_METHOD in cur_xml and "登入" in cur_xml)
                        or (_RID_INPUT_EMAIL in cur_xml)
                        or "輸入密碼" in cur_xml
                        or (_RID_MAIN_BTN in cur_xml and "登入" in cur_xml)
                        or ("下一步" in cur_xml and _RID_BTN_TEXT in cur_xml)
                    )
                    if is_loginish:
                        lp(f"   🔐 [_one_attempt] 偵測到登入/下一步頁面（attempt {attempt_no}），改行登入處理，唔撳返回")
                        _handle_login_screen(d)
                        if d(resourceId=RID_OPTIONAL_GROUP).exists(timeout=3.0):
                            opt = d(resourceId=RID_OPTIONAL_GROUP)
                        else:
                            return False
                    else:
                        d.press("back")
                else:
                    d.press("back")
                btn = d(resourceId=RID_HDR_LIST)
                if btn.wait(timeout=1.5):
                    btn.click()
                if not opt.wait(timeout=2.0):
                    return False
            if _update_popup_guard_stop is not None:
                stop_futu_update_popup_guard()
            opt.click()
            target = d(text=tab_name)
            if not target.wait(timeout=2.0):
                try:
                    opt.click()
                except Exception:
                    pass
                return False
            target.click()
            title_node = d(resourceId=RID_FILTER_TITLE, text=tab_name)
            title_node.wait(timeout=2.0)
            return True
        except Exception:
            return False

    if not find_pid():
        lp("   🚨 [快速偵測] App 已崩潰 (PID 不存在)，立即 kill 重啟並繼續本 tab...")
        restart_app_and_enter_list(d)
        for i in range(1, 6):
            if _one_attempt(i, 5):
                return time.perf_counter() - t0
            time.sleep(0.5)

    for i in range(1, 4):
        if _one_attempt(i, 3):
            return time.perf_counter() - t0
        if not find_pid():
            lp("   🚨 [快速偵測] 嘗試中發現 App 已崩潰，立即 kill 重啟並繼續本 tab...")
            restart_app_and_enter_list(d)
            for j in range(1, 6):
                if _one_attempt(j, 5):
                    return time.perf_counter() - t0
                time.sleep(0.5)

    lp("   ❌ 3 次均失敗，開始診斷...")
    # BUG A+B fix：先查登入畫面 + 彈窗，處理後再試；無先強制重啟
    if find_pid():
        lp("   🔍 [診斷] 先檢查登入畫面/彈窗（BUG A+B）...")
        _handle_login_screen(d)
        _dismiss_popups(d, timeout=3.0)
        time.sleep(1.0)
        for i in range(1, 4):
            if _one_attempt(i, 5):
                return time.perf_counter() - t0
            time.sleep(0.5)
        lp("   🔍 [診斷] 登入/彈窗處理後仍失敗，檢查 PID...")
    if not find_pid():
        lp("   🚨 PID 不存在，App 崩潰，執行重啟...")
        restart_app_and_enter_list(d)
    else:
        for _ in range(3):
            d.press("back")
            time.sleep(1.0)
            if d(resourceId=RID_OPTIONAL_GROUP).exists(timeout=1.5):
                break
        if not d(resourceId=RID_OPTIONAL_GROUP).exists(timeout=1.0):
            btn = d(resourceId=RID_HDR_LIST)
            if btn.exists(timeout=2.0):
                btn.click()
                time.sleep(2.0)

    for i in range(1, 6):
        if _one_attempt(i, 5):
            return time.perf_counter() - t0
        time.sleep(0.8)

    restart_app_and_enter_list(d)
    for i in range(1, 6):
        if _one_attempt(i, 5):
            return time.perf_counter() - t0
        time.sleep(0.8)

    raise RuntimeError(f"switch_tab({tab_name}) 徹底失敗")


def do_dump(d, label=""):
    for attempt in range(1, 5):
        try:
            xml = d.dump_hierarchy(compressed=False)
            length = len(xml) if xml else 0
            lp(f"      dump[{label}] attempt={attempt} len={length}")
            if xml and length > 200:
                # 驗證碼頁面：立即停止 + TG 通知
                if _detect_captcha(xml):
                    _handle_captcha_stop()
                    return ""
                # BUG B fix：登入畫面優先處理（登入頁冇 tab_title / kline）
                if (_RID_TXT_METHOD in xml and "登入" in xml) or (_RID_INPUT_EMAIL in xml) or "輸入密碼" in xml or (_RID_MAIN_BTN in xml and "登入" in xml):
                    lp("      🔐 在 dump 中發現登入畫面（含 main_btn 登入），觸發登入處理...")
                    _handle_login_screen(d)
                    time.sleep(0.5)
                    continue
                ad_keywords = ["popup_ad_close", "以後再說", "iv_close", "我知道了", "跳過", "close_btn"]
                if any(kw in xml for kw in ad_keywords):
                    lp("      ⚠️ 在 dump 中發現疑似廣告彈窗，觸發清理...")
                    _dismiss_popups(d, timeout=3.0)
                    time.sleep(0.5)
                    continue
                return xml
        except Exception as exc:
            lp(f"      dump[{label}] attempt={attempt} ERR: {type(exc).__name__}: {exc}")
        time.sleep(1.0)
    return ""


def switch_tab_watched(d, tab_name):
    watchdog_reset(f"switch_tab:{tab_name}")
    try:
        _check_watchdog_triggered()
        result = switch_tab(d, tab_name)
        _check_watchdog_triggered()
        return result
    finally:
        watchdog_stop()


def do_dump_watched(d, label=""):
    watchdog_reset(f"do_dump:{label}")
    try:
        _check_watchdog_triggered()
        result = do_dump(d, label=label)
        _check_watchdog_triggered()
        return result
    finally:
        watchdog_stop()


def get_all_tab_names(d):
    try:
        tabs = []
        tab_objs = d(resourceId=RID_TAB_TITLE)
        for i in range(tab_objs.count):
            try:
                text = tab_objs[i].get_text()
                if text and text.strip():
                    tabs.append(text.strip())
            except Exception:
                pass
        return tabs
    except Exception:
        return []


def swipe_up(d):
    try:
        w, h = d.window_size()
        d.swipe(w // 2, h * 3 // 4, w // 2, h // 4, duration=0.3)
    except Exception as exc:
        log_exception("SWIPE_FAILED", exc)


def switch_to_tab_simple(d, tab_name, max_attempts=3):
    lp(f"   🔀 切換到 {tab_name}...")
    for _attempt in range(max_attempts):
        try:
            tab_obj = d(resourceId=RID_TAB_TITLE, text=tab_name)
            if tab_obj.exists(timeout=3.0):
                tab_obj.click()
                time.sleep(1.5)
                lp(f"   ✅ 已點擊 {tab_name}")
                return True
        except Exception:
            time.sleep(1)
    return False


def webhook_notify_mapping(filepath):
    """Round0 mapping callback (baseline behaviour, legacy/compatibility only)."""
    url = CONFIG.LEGACY_MAPPING_WEBHOOK_URL
    if not url or requests is None:
        return False
    try:
        with open(filepath, "r", encoding="utf-8") as fh:
            data = json.load(fh)
        headers = {"Content-Type": "application/json", "Content-Encoding": "gzip"}
        if getattr(CONFIG, "MAPPING_WEBHOOK_ADMIN_TOKEN", ""):
            headers["X-Admin-Token"] = CONFIG.MAPPING_WEBHOOK_ADMIN_TOKEN
        # gzip 壓縮：combined_stocks.json 可達幾 MB，raw 上傳會撞 nginx
        # client_body_timeout(60s) → 504。壓縮後細幾十倍，秒上傳。
        body = gzip.compress(json.dumps(data, ensure_ascii=False).encode("utf-8"))
        resp = requests.post(url, data=body, headers=headers, timeout=10)
        jlog("MAPPING_WEBHOOK_SENT", status=resp.status_code, count=len(data.get("data", [])))
        return True
    except Exception as exc:
        log_exception("MAPPING_WEBHOOK_FAILED", exc)
        return False


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 17 — ROUND 0: name/code/F mapping crawl (PROTECTED output format)
# ══════════════════════════════════════════════════════════════════════════════
def round0_collect_name_code_mapping(d):
    lp("=" * 60)
    lp("🔍 ROUND 0：爬取 name-code-F 對照表")
    lp("=" * 60)
    append_log("R0_START", "Starting ROUND 0")

    tabs = []
    for _attempt in range(3):
        raw_tabs = get_all_tab_names(d)
        tabs = [t.strip() for t in raw_tabs if is_valid_tab(t.strip())]
        tabs.sort(key=lambda x: (x[:2].lower(), int(x[2:])))
        if tabs:
            break
        d.press("back")
        time.sleep(2)

    if not tabs:
        lp("   ❌ 找不到有效 tab，啟動修復...")
        restart_app_and_enter_list(d)
        for _ in range(2):
            d.press("back")
            time.sleep(1)
        raw_tabs = get_all_tab_names(d)
        tabs = [t.strip() for t in raw_tabs if is_valid_tab(t.strip())]
        tabs.sort(key=lambda x: (x[:2].lower(), int(x[2:])))
        if not tabs:
            return [], {}, {}

    all_stocks, done_tabs, pending_tabs = {}, set(), list(tabs)
    default_e = "390" if MARKET_MODE == "US" else "330"

    while pending_tabs:
        tab_name = pending_tabs.pop(0)
        if tab_name in done_tabs:
            continue
        lp(f"\n📂 Tab: {tab_name}  (剩餘: {pending_tabs})")

        if not switch_to_tab_simple(d, tab_name):
            done_tabs.add(tab_name)
            continue

        done_tabs.add(tab_name)
        time.sleep(0.5)

        try:
            current_tabs = [t.strip() for t in get_all_tab_names(d) if is_valid_tab(t.strip())]
            for new_t in current_tabs:
                if new_t not in done_tabs and new_t not in pending_tabs:
                    pending_tabs.append(new_t)
        except Exception:
            pass

        tab_stocks, seen_fp, no_new_count = {}, set(), 0

        for page in range(120):
            xml = do_dump(d, label=f"{tab_name}_p{page+1}")
            if not xml:
                break

            page_stocks = parse_list_page_from_xml(xml)
            page_new = 0
            for code, info in page_stocks.items():
                if code not in tab_stocks:
                    tab_stocks[code] = info["name"]
                    page_new += 1
                if code not in all_stocks:
                    all_stocks[code] = {"name": info["name"], "F": info["F"], "E": default_e}

            codes = list(page_stocks.keys())
            fingerprint = "|".join(codes[:3] + ["---"] + codes[-3:]) if codes else ""
            append_log("R0_PAGE", f"tab={tab_name} page={page+1} new={page_new} total={len(tab_stocks)}")

            if fingerprint and fingerprint in seen_fp and page_new == 0:
                no_new_count += 1
                if no_new_count >= 3:
                    break
            else:
                no_new_count = 0
            if fingerprint:
                seen_fp.add(fingerprint)

            swipe_up(d)
            time.sleep(0.35)

        lp(f"   📦 {tab_name}: {len(tab_stocks)} 支 (累計 {len(all_stocks)})")
        try:
            current_tabs = [t.strip() for t in get_all_tab_names(d) if is_valid_tab(t.strip())]
            for new_t in current_tabs:
                if new_t not in done_tabs and new_t not in pending_tabs:
                    pending_tabs.append(new_t)
        except Exception:
            pass

    lp(f"\n📊 所有 tab 完畢（共 {len(done_tabs)} 個）")
    sorted_tabs = sorted(done_tabs, key=lambda x: (x[:2].lower(), int(x[2:])))

    lp(f"   📂 嘗試從主腦下載中央設定 {CONFIG.OW_REMOTE_URL} ...")
    if requests is not None and CONFIG.OW_REMOTE_URL:
        try:
            resp = requests.get(CONFIG.OW_REMOTE_URL, timeout=5)
            if resp.status_code == 200:
                ow_data = resp.json()
                overwrite_count = 0
                for code, info in all_stocks.items():
                    if code in ow_data:
                        if "F" in ow_data[code]:
                            info["F"] = str(ow_data[code]["F"])
                        if "E" in ow_data[code]:
                            info["E"] = str(ow_data[code]["E"])
                        overwrite_count += 1
                lp(f"   ✅ 已套用主腦 {overwrite_count} 筆自訂設定。")
            else:
                lp(f"   ⚠️ 無法讀取主腦 ow.json (HTTP Code: {resp.status_code})")
        except Exception as exc:
            log_exception("OW_FETCH_FAILED", exc)

    data_list = [[code, info["name"], info["F"], info["E"]] for code, info in all_stocks.items()]
    market_cache_data = {"market": MARKET_MODE, "tabs": sorted_tabs, "data": data_list}

    cache_file = get_round0_cache_file(MARKET_MODE)
    _atomic_write_json(cache_file, market_cache_data)
    lp(f"💾 ROUND 0 市場快取已存: {cache_file} ({len(all_stocks)} 股票)")

    public_data = refresh_round0_public_file()
    lp(f"📦 對外 combined_stocks.json 已合併去重: {CONFIG.ROUND0_FILE} "
       f"({len(public_data.get('data', []))} 股票)")

    webhook_notify_mapping(CONFIG.ROUND0_FILE)
    append_log("R0_END", f"Collected {len(all_stocks)} stocks; cache={os.path.basename(cache_file)}")

    name_to_symbol, symbol_order = {}, {}
    for idx, (code, info) in enumerate(all_stocks.items()):
        name = info["name"]
        try:
            # FIX K-26：emoji／全形怪字符唔准攬住成個名冊死——壞就 fallback 原名
            cleaned = re.sub(r"\s*[(（](?:期貨)?主連 [^)）]*[^)）]*[)）]", "", str(name), flags=re.UNICODE).strip()
        except Exception:
            cleaned = str(name).strip()
        name_to_symbol[cleaned] = code
        name_to_symbol[name] = code
        symbol_order[code] = idx

    return sorted_tabs, name_to_symbol, symbol_order


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 18 — W4 CRAWLER LOGIC: scrape -> normalize -> enqueue -> send
# ══════════════════════════════════════════════════════════════════════════════
def compute_round_fingerprint(market, trade_date_value, bars, watermark_utc_ms,
                              coverage_symbols=None, coverage_tabs=None):
    """Canonical stale fingerprint.

    Deliberately NOT `(symbol, T)` only. It mixes:
      * market + trading date (so a new day can never look stale),
      * the content hash of every bar (so a current-minute OHLCVA change makes
        the round different -> no false stale),
      * coverage (symbol count / bar count / tab count),
      * the producer watermark and the newest bar_start.
    """
    digest = hashlib.sha256()
    for bar in sorted(bars or [], key=lambda b: (b["bar_start_utc_ms"], b["symbol"])):
        digest.update(bar_content_hash(bar).encode("ascii"))
        digest.update(b"|")
    payload_hash = digest.hexdigest()
    max_bar_start = max([int(b["bar_start_utc_ms"]) for b in bars], default=0)
    envelope = {
        "market": str(market or "").upper(),
        "trade_date": trade_date_value.isoformat() if isinstance(trade_date_value, date) else str(trade_date_value),
        "coverage_symbols": int(coverage_symbols if coverage_symbols is not None
                                else len({b["symbol"] for b in bars or []})),
        "coverage_bars": len(bars or []),
        "coverage_tabs": int(coverage_tabs or 0),
        "watermark_utc_ms": int(watermark_utc_ms or 0),
        "max_bar_start_utc_ms": max_bar_start,
        "payload_hash": payload_hash,
    }
    return sha256_hex(json.dumps(envelope, ensure_ascii=False, separators=(",", ":"))), envelope


class CrawlResult(dict):
    """CrawlResult = {bars_collected, enqueued_batches, stale, recovered} (+detail)."""

    def __init__(self, bars_collected=0, enqueued_batches=None, stale=False, recovered=False, **extra):
        super().__init__(
            bars_collected=int(bars_collected),
            enqueued_batches=list(enqueued_batches or []),
            stale=bool(stale),
            recovered=bool(recovered),
            **extra,
        )

    def __getattr__(self, item):
        try:
            return self[item]
        except KeyError as exc:
            raise AttributeError(item) from exc


_ACTIVE_CRAWLER = None


class Crawler(object):
    """One UI round == one CrawlResult. Delivery is handled by the Sender thread."""

    def __init__(self, d_ref, tabs, name_to_symbol, symbol_order, outbox=None,
                 sender=None, cfg=None):
        self.d_ref = d_ref
        self.tabs = list(tabs or [])
        if cfg is None:
            cfg = CONFIG
        self.cfg = cfg
        if cfg.TAB_WHITELIST:
            allowed = {t.lower() for t in cfg.TAB_WHITELIST}
            filtered = [t for t in self.tabs if t.lower() in allowed]
            if filtered:
                lp(f"   🎛️ TAB_WHITELIST 生效: {filtered}")
                self.tabs = filtered
            else:
                lp(f"   ⚠️ TAB_WHITELIST {list(cfg.TAB_WHITELIST)} 未命中任何 tab，改用全部 tab")
        self.name_to_symbol = dict(name_to_symbol or {})
        self.symbol_order = dict(symbol_order or {})
        self.outbox = outbox if outbox is not None else OUTBOX
        self.sender = sender if sender is not None else SENDER
        self.loop_count = 0
        self.stale_count = 0
        self.last_fingerprint = None
        self.resume_from_tab = None
        self.pending_market_switch = None
        self.tab_history = defaultdict(list)
        self.all_symbol_latest = {}
        self._recovery_in_progress = False

    # ── helpers ───────────────────────────────────────────────────────────────
    @property
    def device(self):
        return self.d_ref[0]

    def _do_market_switch(self, new_mode):
        global MARKET_MODE
        lp(f"🔄 [市場切換] {MARKET_MODE} -> {new_mode}，pm2 restart 交由啟動期以時間重新判定")
        append_log("MARKET_SWITCH", f"{MARKET_MODE} -> {new_mode} via pm2 restart")
        watchdog_stop()
        try:
            graceful_close(timeout_sec=10.0)  # never lose an un-ACKed batch on switch
        except Exception as exc:
            log_exception("MARKET_SWITCH_CLOSE_FAILED", exc)
        # FIX P1-12：restart 前照妖鏡——pm2 認唔認得個名？唔認得即刻大聲報（唔再靜靜雞當做完）；
        # 無論點都照 exit：pm2 autorestart policy 會用佢註冊嘅真名拉起本進程。
        _pm2_app = os.environ.get("PM2_APP_NAME") or "futu"
        try:
            _d = subprocess.run("pm2 describe %s" % _pm2_app, shell=True,
                                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10)
            if _d.returncode != 0:
                lp(f"❌ [市場切換] pm2 describe {_pm2_app} 失敗（rc={_d.returncode}）——PM2_APP_NAME 可能打錯，爬蟲可能起唔返！")
                append_log("PM2_APP_NAME_UNKNOWN", f"app={_pm2_app} rc={_d.returncode}")
        except Exception as exc:
            log_exception("PM2_DESCRIBE_FAILED", exc)
        try:
            subprocess.Popen("pm2 restart %s" % _pm2_app, shell=True)
            time.sleep(0.2)
        except Exception as exc:
            log_exception("PM2_RESTART_FAILED", exc)
        os._exit(0)

    def _reconnect_after_watchdog(self):
        lp("🔄 [Watchdog後重連] 等待設備就緒...")
        RUNTIME.set(ui_recovery_state="watchdog_reconnect")
        if not wait_device_ready(timeout=120, check_interval=2):
            lp("❌ [Watchdog後重連] 設備超時，pm2 restart")
            self._do_market_switch(MARKET_MODE)
        lp("🔄 [Watchdog後重連] 重新連接 uiautomator2...")
        try:
            new_d = connect_device()
            self.d_ref[0] = new_d
        except Exception as exc:
            log_exception("WATCHDOG_RECONNECT_FAILED", exc)
            self._do_market_switch(MARKET_MODE)
        lp("🔄 [Watchdog後重連] 啟動 App 並進入 K 線頁...")
        try:
            restart_app_and_enter_list(self.d_ref[0])
        except Exception as exc:
            log_exception("WATCHDOG_RECONNECT_APP_FAILED", exc)
        _watchdog_triggered.clear()
        RUNTIME.set(ui_recovery_state="running")
        lp("✅ [Watchdog後重連] 完成，從卡住的 tab 繼續。")

    def _write_legacy_files(self, raw_items):
        """Optional legacy diagnostics — NEVER the delivery truth (AUTH-A R4)."""
        if not self.cfg.LEGACY_FILE_OUTPUT:
            return
        try:
            unique_round = {}
            for item in raw_items:
                key = f"{item['symbol']}_{item['data'].get('T', '')}"
                if key not in unique_round:
                    unique_round[key] = item
            new_klines = sorted(unique_round.values(),
                                key=lambda x: self.symbol_order.get(x["symbol"], 999999))
            for item in raw_items:
                symbol = item["symbol"]
                t_val = item["data"].get("T", "")
                current = self.all_symbol_latest.get(symbol)
                if current is None:
                    self.all_symbol_latest[symbol] = item
                    continue
                try:
                    if int(t_val or 0) >= int(current["data"].get("T", "0") or "0"):
                        self.all_symbol_latest[symbol] = item
                except (TypeError, ValueError):
                    self.all_symbol_latest[symbol] = item
            renew_list = sorted(self.all_symbol_latest.values(),
                                key=lambda x: self.symbol_order.get(x["symbol"], 999999))
            # FIX K-15：先寫新紙、fsync、一 take 過換
            atomic_write_json(self.cfg.ROUND2_FILE, json.dumps(new_klines, ensure_ascii=False, indent=2))
            atomic_write_json(self.cfg.ROUND2_ALL_FILE, json.dumps(renew_list, ensure_ascii=False, indent=2))
            legacy_webhook_notify(self.cfg.ROUND2_FILE)
        except Exception as exc:
            log_exception("LEGACY_FILE_WRITE_FAILED", exc)

    # ── one round ─────────────────────────────────────────────────────────────
    def crawl_once(self) -> CrawlResult:
        """Scrape every tab once, normalize, enqueue canonical batches.

        Raises WatchdogTriggered when the watchdog rebuilt Docker mid-round; the
        caller (run_forever) reconnects and resumes from `self.resume_from_tab`.
        """
        self.loop_count += 1
        global _last_recovery_at_ms
        RUNTIME.set(loop_count=self.loop_count, market=MARKET_MODE, last_loop_at_ms=now_ms())
        crawl_ctx = CrawlContext.for_now(MARKET_MODE, bar_count_ui=self.cfg.KLINE_BAR_COUNT)
        raw_items = []
        tabs_done = 0
        recovered = False
        tab_fail_count = 0

        start_idx = 0
        if self.resume_from_tab and self.resume_from_tab in self.tabs:
            start_idx = self.tabs.index(self.resume_from_tab)
            lp(f"   ↩️ [Watchdog恢復] 從 tab={self.resume_from_tab} (idx={start_idx}) 繼續")
        self.resume_from_tab = None

        for tab_idx, tab_name in enumerate(self.tabs):
            if tab_idx < start_idx:
                continue
            if is_shutting_down():
                lp("   🛑 [SHUTDOWN] 停止接收新工作，提早結束本輪 tab 收集")
                break

            mid_check = get_market_mode()
            if mid_check != MARKET_MODE and FORCE_MARKET == "AUTO":
                lp(f"   ⏰ 偵測到市場切換 ({MARKET_MODE} -> {mid_check})，立即 pm2 restart")
                self._do_market_switch(mid_check)
            if mid_check == "IDLE":
                lp("   ⏰ 檢測到休市時間，提早結束本輪 tab 收集並保存數據...")
                self.pending_market_switch = "IDLE"
                break

            lp(f"\n── Tab: {tab_name} ──")
            append_log("TAB_START", f"Tab: {tab_name}")

            try:
                sw_time = switch_tab_watched(self.device, tab_name)
                lp(f"   ✅ 切換耗時: {sw_time:.2f}s")
                tab_fail_count = 0
            except WatchdogTriggered:
                lp(f"   🚨 [Watchdog] switch_tab:{tab_name} 觸發 Docker 重建，重連後從此 tab 繼續...")
                append_log("WATCHDOG_RESUME", f"Resuming from tab={tab_name} after switch_tab")
                self.resume_from_tab = tab_name
                raise
            except RuntimeError as exc:
                if _watchdog_triggered.is_set():
                    lp("   🚨 [Watchdog漏判修正] switch_tab 失敗實為 Docker 已重建，走重連流程...")
                    append_log("WATCHDOG_RESUME", f"RuntimeError converted, tab={tab_name}")
                    self.resume_from_tab = tab_name
                    raise WatchdogTriggered(str(exc))
                lp(f"   ❌ {tab_name} 切換失敗: {exc}")
                tab_fail_count += 1
                RUNTIME.set(last_error=f"switch_tab:{tab_name}")
                if tab_fail_count >= max(1, len(self.tabs) // 2):
                    fm = get_market_mode()
                    if fm != MARKET_MODE and FORCE_MARKET == "AUTO":
                        lp(f"   ⏰ 失敗超過半數，且檢測到市場切換 ({MARKET_MODE} -> {fm})，提早結束本輪...")
                        self.pending_market_switch = fm
                        break
                    raise RuntimeError("too_many_tab_failures")
                if not find_pid():
                    raise RuntimeError("switch_fail_no_pid")
                continue

            degraded, sw_now, sw_avg = is_switch_degraded(sw_time)
            if degraded and not self._recovery_in_progress:
                # 精準化 Patch-A：觸發前先確認 jsonrpc 真係慢。
                #   jsonrpc 健康 → 純粹 App 一時 busy（切換慢但連線冇事），唔值得重啟。
                #   呢個就係 us4 7.21s 誤觸發嘅根因。
                if _is_jsonrpc_healthy(self.device):
                    lp(f"   ℹ️ [劣化偵測] switch {sw_now:.2f}s 但 jsonrpc 健康，判定 App 一時繁忙，略過修復")
                    append_log("DEGRADATION_SKIPPED", f"sw={sw_now:.2f}s jsonrpc=healthy tab={tab_name}")
                    record_switch_latency(sw_time)
                elif now_ms() - _last_recovery_at_ms < _RECOVERY_COOLDOWN_SEC * 1000:
                    # 精準化 Patch-B：修復冷卻期，防止重啟循環（thrash）。
                    lp(f"   ℹ️ [劣化偵測] 修復冷卻期內，略過（上次修復距今 {(now_ms() - _last_recovery_at_ms) / 1000:.0f}s）")
                    append_log("DEGRADATION_COOLDOWN", f"sw={sw_now:.2f}s tab={tab_name}")
                    record_switch_latency(sw_time)
                else:
                    lp(f"   ⚠️ [劣化偵測] switch {sw_now:.2f}s > median {sw_avg:.2f}s "
                       f"×{_SWITCH_DEGRADED_RATIO} 且 jsonrpc 不健康，觸發三級修復")
                    append_log("DEGRADATION_DETECTED", f"sw={sw_now:.2f}s avg={sw_avg:.2f}s tab={tab_name}")
                    self._recovery_in_progress = True
                    try:
                        three_level_recovery(self.device, self.d_ref,
                                             reason=f"switch_degraded tab={tab_name} "
                                                    f"sw={sw_now:.2f}s avg={sw_avg:.2f}s")
                        _last_recovery_at_ms = now_ms()
                    finally:
                        self._recovery_in_progress = False
                    recovered = True
                    try:
                        sw_time2 = switch_tab_watched(self.device, tab_name)
                        lp(f"   🔄 [修復後重切] {tab_name} 耗時: {sw_time2:.2f}s")
                        record_switch_latency(sw_time2)
                    except WatchdogTriggered:
                        lp("   🚨 [Patch2] 修復後重切觸發 watchdog，從此 tab 繼續...")
                        append_log("WATCHDOG_RESUME", f"Post-recovery retry tab={tab_name}")
                        self.resume_from_tab = tab_name
                        raise
                    except Exception as exc:
                        log_exception("POST_RECOVERY_SWITCH_FAILED", exc, tab=tab_name)
                        continue
            else:
                record_switch_latency(sw_time)

            t_dump_start = time.time()
            try:
                xml = do_dump_watched(self.device, label=tab_name)
            except WatchdogTriggered:
                lp(f"   🚨 [Watchdog] do_dump:{tab_name} 觸發 Docker 重建，重連後從此 tab 繼續...")
                append_log("WATCHDOG_RESUME", f"Resuming from tab={tab_name} after do_dump")
                self.resume_from_tab = tab_name
                raise
            dump_cost = time.time() - t_dump_start
            if not xml:
                continue

            history = self.tab_history[tab_name]
            history.append(dump_cost)
            if len(history) > 30:
                history.pop(0)

            tab_items = parse_klines_from_xml_new(xml, self.name_to_symbol)
            raw_items.extend(tab_items)
            tabs_done += 1
            append_log("TAB_SUMMARY", f"tab={tab_name} items={len(tab_items)} dump={dump_cost:.2f}s")
            append_log("TAB_END", f"Tab: {tab_name}, Cost: {dump_cost:.2f}s, Items: {len(tab_items)}")

        # ── normalize -> enqueue ─────────────────────────────────────────────
        crawl_ctx.capture_ts_ms = now_ms()  # FIX-MIDNIGHT — 真實 capture 時刻（round 完結；跨午夜判定用）
        bars = normalize_round(raw_items, crawl_ctx)
        prev_watermark = 0
        if self.outbox is not None:
            try:
                prev_watermark = int(self.outbox.get_state("watermark_utc_ms", "0") or 0)
            except Exception as exc:
                log_exception("WATERMARK_READ_FAILED", exc)
        watermark = compute_watermark(bars, prev_watermark)
        fingerprint, envelope = compute_round_fingerprint(
            MARKET_MODE, crawl_ctx.trade_date_local, bars, watermark,
            coverage_tabs=tabs_done,
        )

        stale = bool(self.last_fingerprint) and fingerprint == self.last_fingerprint
        if stale:
            self.stale_count += 1
            lp(f"   ⚠️ [停滯] {self.stale_count}/{self.cfg.MAX_STALE_ROUNDS} fingerprint={fingerprint[:12]}")
            append_log("STALE_ALERT", f"Stale: {self.stale_count}/{self.cfg.MAX_STALE_ROUNDS}")
        else:
            self.stale_count = 0
        self.last_fingerprint = fingerprint
        RUNTIME.set(stale_rounds=self.stale_count, bars_last_round=len(bars))

        batch_ids = []
        if bars and self.outbox is not None:
            batch_ids = enqueue_canonical_bars(bars, market=MARKET_MODE,
                                               captured_at_utc_ms=crawl_ctx.loop_ts_ms)
        self._write_legacy_files(raw_items)

        lp(f"✅ Loop #{self.loop_count} 完成  raw={len(raw_items)}  canonical={len(bars)}  "
           f"batches={len(batch_ids)}  watermark={watermark}")
        log_important("LOOP_END",
                      f"Loop #{self.loop_count} raw={len(raw_items)} canonical={len(bars)} "
                      f"batches={len(batch_ids)} stale={stale}", print_to_pm2=False)

        return CrawlResult(
            bars_collected=len(bars),
            enqueued_batches=batch_ids,
            stale=stale,
            recovered=recovered,
            raw_items=len(raw_items),
            tabs_done=tabs_done,
            fingerprint=fingerprint,
            watermark_utc_ms=watermark,
            coverage=envelope,
        )

    # ── infinite loop (baseline round2_loop semantics preserved) ─────────────
    def run_forever(self):
        lp("\n" + "=" * 60)
        lp(f"💉 ROUND 2：無限迴圈 (canonical push, {WATCHDOG_TIMEOUT}s Watchdog)")
        lp("=" * 60)
        if not self.tabs:
            lp("❌ 無可用 tab，結束")
            return

        rebuild_count = 0
        max_rebuilds_per_cycle = 1

        while not is_shutting_down():
            current_mode = get_market_mode()
            if current_mode == "IDLE":
                self.pending_market_switch = None
                lp("🛑 休市，等待 60s...")
                for _ in range(60):
                    if is_shutting_down():
                        return
                    time.sleep(1)
                continue

            if current_mode != MARKET_MODE and FORCE_MARKET == "AUTO":
                self._do_market_switch(current_mode)
                continue
            if self.pending_market_switch and self.pending_market_switch != MARKET_MODE:
                self._do_market_switch(self.pending_market_switch)
                continue

            lp(f"\n{'='*60}\n🔄 Loop #{self.loop_count + 1}  "
               f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}  市場={MARKET_MODE}\n{'='*60}")
            log_important("LOOP_START",
                          f"Loop #{self.loop_count + 1} "
                          f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} market={MARKET_MODE}",
                          print_to_pm2=False)

            try:
                result = self.crawl_once()
                rebuild_count = 0
                gc.collect()

                if result["stale"] and self.stale_count >= self.cfg.MAX_STALE_ROUNDS:
                    self.stale_count = 0
                    self.last_fingerprint = None
                    self.all_symbol_latest = {}
                    raise RuntimeError("stale_detection")

                if result["stale"]:
                    restart_app_and_enter_list(self.device)

                end_mode = get_market_mode()
                if end_mode == "IDLE":
                    lp("🛑 [輪結束] 休市")
                    self.pending_market_switch = "IDLE"
                elif end_mode != MARKET_MODE and FORCE_MARKET == "AUTO":
                    if not self.pending_market_switch:
                        self.pending_market_switch = end_mode
                lp("\n   ✅ 本輪順暢，同 Session 繼續下一輪\n")
                continue

            except WatchdogTriggered:
                lp("   🚨 [Watchdog] Docker 已重建，重連後從卡住的 tab 繼續...")
                append_log("WATCHDOG_RESUME", f"tab={self.resume_from_tab}")
                self._reconnect_after_watchdog()
                continue
            except Exception as exc:
                err_msg = str(exc)
                log_exception("LOOP_ERROR", exc, loop=self.loop_count)
                RUNTIME.set(last_error=f"loop:{type(exc).__name__}")

                if _watchdog_triggered.is_set():
                    lp("   🚨 [Watchdog漏判防護] 異常期間偵測到 Docker 已重建，強制重連...")
                    self._reconnect_after_watchdog()
                    continue

                mid_check = get_market_mode()
                if mid_check != MARKET_MODE and FORCE_MARKET == "AUTO":
                    lp(f"⚠️ 修復時發現市場已變 ({MARKET_MODE} -> {mid_check})，pm2 restart 換場")
                    self._do_market_switch(mid_check)

                rebuild_count += 1
                lp(f"⚠️ 失敗: {rebuild_count}/{max_rebuilds_per_cycle} ({err_msg[:120]})")
                if rebuild_count > max_rebuilds_per_cycle:
                    lp("⚠️ 連續失敗超過上限，pm2 restart 重開")
                    self._do_market_switch(MARKET_MODE)
                try:
                    self.stale_count = 0
                    self.last_fingerprint = None
                    self.all_symbol_latest = {}
                    self.resume_from_tab = None
                    restart_app_and_enter_list(self.device)
                    continue
                except Exception as inner:
                    log_exception("RECOVERY_RESTART_FAILED", inner)
                    self._do_market_switch(MARKET_MODE)

        lp("🛑 [SHUTDOWN] 主迴圈已停止接收新工作")


def crawl_once() -> CrawlResult:
    """W4 frozen interface — delegates to the active Crawler instance."""
    if _ACTIVE_CRAWLER is None:
        raise RuntimeError("crawler is not initialised; call setup_and_run() first")
    return _ACTIVE_CRAWLER.crawl_once()


def round2_loop(d_ref, tabs_list, name_to_symbol, symbol_order):
    """Baseline entry point, now backed by the Crawler class."""
    global _ACTIVE_CRAWLER
    _ACTIVE_CRAWLER = Crawler(d_ref, tabs_list, name_to_symbol, symbol_order,
                              outbox=OUTBOX, sender=SENDER, cfg=CONFIG)
    _ACTIVE_CRAWLER.run_forever()


def bootstrap_startup(sender, first_crawl_callable=None, replay_timeout_sec=None):
    """Ordering guarantee (test gate J): replay every pending batch BEFORE the
    first new crawl round starts. Returns (replay_report, crawl_result|None)."""
    report = sender.replay_pending_blocking(timeout_sec=replay_timeout_sec)
    result = None
    if first_crawl_callable is not None:
        result = first_crawl_callable()
    return report, result


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 19 — W6 SELF-TEST: local mock ingest server + gates A..M
#   `python3 futu.py --self-test` runs entirely offline: temporary SQLite,
#   temporary directories, a local mock HTTP server. No Futu / Oracle / Docker.
# ══════════════════════════════════════════════════════════════════════════════
import shutil      # self-test only (temporary directory cleanup)
import tempfile    # self-test only (temporary SQLite + fixtures)


class _MockIngestHandler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def do_POST(self):  # noqa: N802
        app = self.server.app
        try:
            length = int(self.headers.get("Content-Length") or 0)
        except (TypeError, ValueError):
            length = 0
        body = self.rfile.read(length) if length else b""
        status, ack = app.handle(self.path, dict(self.headers), body)
        payload = json.dumps(ack, ensure_ascii=False).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    def log_message(self, fmt, *args):
        return


class MockIngestServer(object):
    """Behaviour-programmable stand-in for the real /v1/ingest/batches endpoint."""

    def __init__(self, secret=FIXTURE_TEST_SECRET, path=INGEST_PATH):
        self.secret = secret
        self.path = path
        self.requests = []
        self.fail_next = 0
        self.force_status = None
        self.ack_override = None
        self.on_request = None
        self.committed = {}
        self.highest_sequence = 0
        self._httpd = None
        self._thread = None
        self._lock = threading.Lock()

    # ── lifecycle ─────────────────────────────────────────────────────────────
    def start(self):
        self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), _MockIngestHandler)
        self._httpd.app = self
        self._httpd.daemon_threads = True
        self._thread = threading.Thread(target=self._httpd.serve_forever,
                                        kwargs={"poll_interval": 0.1},
                                        name="mock-ingest", daemon=True)
        self._thread.start()
        return self.url

    def stop(self):
        if self._httpd is not None:
            self._httpd.shutdown()
            self._httpd.server_close()
            self._httpd = None

    @property
    def port(self):
        return self._httpd.server_address[1] if self._httpd else None

    @property
    def url(self):
        return f"http://127.0.0.1:{self.port}{self.path}"

    def reset(self):
        with self._lock:
            self.requests = []
            self.fail_next = 0
            self.force_status = None
            self.ack_override = None
            self.committed = {}
            self.highest_sequence = 0

    # ── request handling ──────────────────────────────────────────────────────
    def handle(self, path, headers, body):
        record = {
            "path": path,
            "headers": {k: v for k, v in headers.items()},
            "body_sha256": sha256_hex(body),
            "body_len": len(body),
            "received_at_ms": now_ms(),
            "payload": None,
        }
        with self._lock:
            self.requests.append(record)
        if callable(self.on_request):
            try:
                self.on_request(record)
            except Exception:
                pass

        if self.force_status is not None:
            return int(self.force_status), {"error": "forced_status"}
        if self.fail_next > 0:
            with self._lock:
                self.fail_next -= 1
            return 503, {"error": "service_unavailable"}

        expected_sig = signature_header_value(self.secret, body)
        got_sig = headers.get("X-Signature") or headers.get("x-signature") or ""
        if not constant_time_equals(got_sig, expected_sig):
            return 401, {"error": "bad_signature"}

        try:
            payload = json.loads(gunzip_bytes(body).decode("utf-8"))
        except Exception as exc:
            return 400, {"error": f"bad_gzip_or_json:{type(exc).__name__}"}
        record["payload"] = payload

        missing = [f for f in PAYLOAD_FIELDS if f not in payload]
        if missing:
            return 400, {"error": "missing_fields", "fields": missing}
        bars = payload.get("bars") or []
        for row in bars:
            if not isinstance(row, list) or len(row) != len(BAR_ROW_FIELDS):
                return 400, {"error": "bad_bar_row_shape"}

        batch_id = payload["batch_id"]
        sequence = int(payload["sequence"])
        with self._lock:
            duplicate = batch_id in self.committed
            if not duplicate:
                self.committed[batch_id] = sequence
                self.highest_sequence = max(self.highest_sequence, sequence)
            ack = {
                "batch_id": batch_id,
                "status": ACK_STATUS_COMMITTED,
                "accepted": 0 if duplicate else len(bars),
                "duplicate": len(bars) if duplicate else 0,
                "rejected": 0,
                "highest_sequence": self.highest_sequence,
            }
        if callable(self.ack_override):
            ack = self.ack_override(dict(ack))
        return 200, ack

    # ── assertions helpers ────────────────────────────────────────────────────
    def last_request(self):
        with self._lock:
            return self.requests[-1] if self.requests else None

    def sequences_received(self):
        with self._lock:
            return [r["payload"]["sequence"] for r in self.requests if r.get("payload")]


class SelfTestFailure(AssertionError):
    pass


def _expect(condition, message):
    if not condition:
        raise SelfTestFailure(message)
    return True


def _test_config(tmpdir, url, secret, db_path, **overrides):
    base = {
        "FUTU_ENV": "test",
        "PRODUCER_ID": "self-test-01",
        "MARKET_MODE": "HK",
        "INGEST_URL": url,
        "INGEST_HMAC_SECRET": secret,
        "OUTBOX_DB_PATH": db_path,
        "PUBLIC_DIR": tmpdir,
        "HEALTH_FILE_PATH": os.path.join(tmpdir, "health.json"),
        "PRICE_SCALE": "10000",
        "AMOUNT_SCALE": "100",
        "HTTP_CONNECT_TIMEOUT_SEC": "3",
        "HTTP_READ_TIMEOUT_SEC": "10",
        "OUTBOX_MAX_ATTEMPTS": "0",
        "OUTBOX_BACKOFF_BASE_SEC": "0.05",
        "OUTBOX_BACKOFF_MAX_SEC": "0.2",
        "OUTBOX_RETENTION_HOURS": "168",
        "LEGACY_FILE_OUTPUT": "false",
        "LEGACY_WEBHOOK_URL": "",
        "TAB_WHITELIST": "",
        "STRICT_SESSION_FILTER": "true",
        "BAR_TIME_DISPLAY": "MARKET",  # R69: gates A-M verify legacy market-local semantics
    }
    base.update({k: str(v) for k, v in overrides.items()})
    return Config(env_file=os.path.join(tmpdir, "__no_such_env__"), overrides=base)


class _Env(object):
    """One isolated outbox+transport pair on a fresh temporary SQLite file."""

    def __init__(self, tmpdir, mock, name, secret=None, **cfg_overrides):
        self.name = name
        self.db_path = os.path.join(tmpdir, f"{name}.sqlite3")
        self.cfg = _test_config(tmpdir, mock.url, FIXTURE_TEST_SECRET, self.db_path, **cfg_overrides)
        self.outbox = Outbox(db_path=self.db_path, cfg=self.cfg, producer_id=self.cfg.PRODUCER_ID)
        self.transport = Transport(cfg=self.cfg, outbox=self.outbox, url=mock.url,
                                   secret=secret if secret is not None else FIXTURE_TEST_SECRET,
                                   producer_id=self.cfg.PRODUCER_ID)
        self.sender = Sender(self.outbox, self.transport, cfg=self.cfg)

    def close(self):
        try:
            self.transport.close()
        finally:
            self.outbox.close()

    def payload_of(self, batch_id):
        row = self.outbox.get_row(batch_id)
        if row is None:
            return None
        return json.loads(gunzip_bytes(row.payload).decode("utf-8"))

    def send_now(self, batch_id):
        row = self.outbox.get_row(batch_id)
        result = self.transport.send_batch(row)
        if result.committed:
            self.outbox.mark_committed(row.batch_id, result.ack)
        else:
            self.outbox.mark_failed(row.batch_id, str(result.status_or_error),
                                    result.next_retry_at_ms)
        return result


def _raw(symbol, hhmm, o, c, h, l, v, a):
    return {"symbol": symbol, "data": {"T": str(hhmm), "O": str(o), "C": str(c),
                                       "H": str(h), "L": str(l), "V": str(v), "A": str(a)}}


def _ctx(market, iso_date, hhmm="0935"):
    day = date.fromisoformat(iso_date)
    minutes = parse_hhmm_to_minutes(hhmm)
    tz = market_timezone(market)
    stamp = int(datetime(day.year, day.month, day.day, minutes // 60, minutes % 60,
                         tzinfo=tz).timestamp() * 1000)
    return CrawlContext(market, day, session_for_minutes(market, minutes) or "REG", stamp, 5)


# ── individual gates ──────────────────────────────────────────────────────────
def _gate_a(tmpdir, mock):
    """A. batch is in SQLite before HTTP; committed only on a valid ACK."""
    env = _Env(tmpdir, mock, "gate_a")
    try:
        ctx = _ctx("HK", "2026-07-24")
        bars = normalize_round([
            _raw("700", "0930", "385.2", "385.6", "385.8", "385.0", "12500", "4815000"),
            _raw("700", "0931", "385.6", "386.0", "386.2", "385.4", "9800", "3780000"),
        ], ctx)
        _expect(len(bars) == 2, f"expected 2 normalized bars, got {len(bars)}")
        _expect(bars[0]["symbol"] == "00700", f"HK symbol padding failed: {bars[0]['symbol']}")

        requests_before = len(mock.requests)
        batch_id = env.outbox.enqueue_batch(bars, market="HK", captured_at_utc_ms=ctx.loop_ts_ms)
        _expect(bool(batch_id), "enqueue_batch returned no batch_id")

        row = env.outbox.get_row(batch_id)
        _expect(row is not None, "row missing from SQLite after enqueue")
        _expect(row.committed_at_ms is None, "row must NOT be committed before HTTP")
        _expect(len(mock.requests) == requests_before, "HTTP happened before the DB insert")
        _expect(row.payload_sha256 == sha256_hex(row.payload), "payload_sha256 mismatch")
        _expect(gunzip_bytes(row.payload), "stored payload is not valid gzip")

        result = env.send_now(batch_id)
        _expect(result.committed, f"valid ACK must commit, got {result.status_or_error}")
        _expect(env.outbox.get_row(batch_id).committed_at_ms is not None, "row not marked committed")
        return (f"enqueue->db(seq={row.sequence}, {len(row.payload)}B gzip)->POST->ACK committed; "
                f"pending={env.outbox.stats()['pending_count']}")
    finally:
        env.close()


def _gate_b(tmpdir, mock):
    """B. first POST fails, the row is retained, a later retry succeeds."""
    env = _Env(tmpdir, mock, "gate_b")
    try:
        ctx = _ctx("HK", "2026-07-24")
        bars = normalize_round([_raw("5", "0930", "62.1", "62.3", "62.4", "62.0", "3000", "186600")], ctx)
        batch_id = env.outbox.enqueue_batch(bars, market="HK", captured_at_utc_ms=ctx.loop_ts_ms)

        mock.fail_next = 1
        result1 = env.send_now(batch_id)
        _expect(not result1.committed, "503 must not commit")
        row = env.outbox.get_row(batch_id)
        _expect(row.committed_at_ms is None, "row lost its pending state after a failure")
        _expect(row.attempts == 1, f"attempts should be 1, got {row.attempts}")
        _expect(row.next_attempt_at_ms > row.created_at_ms, "backoff did not move next_attempt_at_ms")
        _expect("503" in str(result1.status_or_error), f"unexpected error {result1.status_or_error}")

        time.sleep(max(0.0, (row.next_attempt_at_ms - now_ms()) / 1000.0))
        result2 = env.send_now(batch_id)
        _expect(result2.committed, f"retry must commit, got {result2.status_or_error}")
        return (f"attempt1=503 retained(attempts=1, backoff={row.next_attempt_at_ms - row.created_at_ms}ms), "
                f"attempt2=committed")
    finally:
        env.close()


def _gate_c(tmpdir, mock):
    """C. after a restart, pending rows are replayed in ascending sequence order."""
    env = _Env(tmpdir, mock, "gate_c")
    ctx = _ctx("US", "2026-01-15")
    try:
        ids = []
        for idx, symbol in enumerate(("AAPL", "MSFT", "NVDA")):
            bars = normalize_round([_raw(symbol, "0930", "231.21", f"231.{50 + idx}", "231.80",
                                         "230.90", "125000", "28900000")], ctx)
            ids.append(env.outbox.enqueue_batch(bars, market="US", captured_at_utc_ms=ctx.loop_ts_ms))
        _expect(all(ids), "not every batch was enqueued")
        _expect(env.outbox.stats()["pending_count"] == 3, "expected 3 pending rows")
    finally:
        env.close()  # simulate process exit / crash

    mock.reset()
    reopened = _Env(tmpdir, mock, "gate_c")  # same db file == restart
    try:
        report = reopened.sender.replay_pending_blocking(timeout_sec=20)
        _expect(report["committed"] == 3, f"replay committed {report['committed']}/3")
        _expect(report["pending_after"] == 0, "pending rows left after replay")
        seqs = mock.sequences_received()
        _expect(seqs == sorted(seqs), f"replay order not ascending: {seqs}")
        return f"restart replayed sequences {seqs} in ascending order, pending_after=0"
    finally:
        reopened.close()


def _gate_d(tmpdir, mock):
    """D. the same HHMM on different trading dates produces distinct bars."""
    env = _Env(tmpdir, mock, "gate_d")
    try:
        ctx1 = _ctx("US", "2026-01-15")
        ctx2 = _ctx("US", "2026-01-16")
        start1 = derive_bar_start_utc_ms("AAPL", "0930", ctx1)
        start2 = derive_bar_start_utc_ms("AAPL", "0930", ctx2)
        _expect(start1 != start2, "cross-day identity collision on the same HHMM")
        _expect(start2 - start1 == 86400000, f"expected exactly 24h apart, got {start2 - start1}ms")

        # contract examples (<bar_start_formula>) verified literally
        hk_example = derive_bar_start_utc_ms("00700", "0930", _ctx("HK", "2026-07-24"))
        us_est = derive_bar_start_utc_ms("AAPL", "0930", _ctx("US", "2026-01-15"))
        us_edt = derive_bar_start_utc_ms("AAPL", "0930", _ctx("US", "2026-07-15"))
        _expect(datetime.fromtimestamp(hk_example / 1000, UTC).isoformat() == "2026-07-24T01:30:00+00:00",
                "HK example mismatch")
        _expect(datetime.fromtimestamp(us_est / 1000, UTC).isoformat() == "2026-01-15T14:30:00+00:00",
                "US EST example mismatch")
        _expect(datetime.fromtimestamp(us_edt / 1000, UTC).isoformat() == "2026-07-15T13:30:00+00:00",
                "US EDT example mismatch")

        b1 = normalize_round([_raw("AAPL", "0930", "231.21", "231.50", "231.80", "230.90",
                                   "125000", "28900000")], ctx1)
        b2 = normalize_round([_raw("AAPL", "0930", "232.21", "232.50", "232.80", "231.90",
                                   "135000", "29900000")], ctx2)
        id1 = env.outbox.enqueue_batch(b1, market="US", captured_at_utc_ms=ctx1.loop_ts_ms)
        id2 = env.outbox.enqueue_batch(b2, market="US", captured_at_utc_ms=ctx2.loop_ts_ms)
        _expect(id1 and id2, "cross-day bars were not both enqueued")
        rows1 = env.payload_of(id1)["bars"]
        rows2 = env.payload_of(id2)["bars"]
        _expect(rows1[0][2] != rows2[0][2], "cross-day bar_start collision in the payload")
        _expect(rows2[0][10] == 1, "cross-day bar must start at revision 1, not be a revision bump")
        return (f"day1={rows1[0][2]} day2={rows2[0][2]} delta=86400000ms; "
                f"contract examples HK/EST/EDT verified")
    finally:
        env.close()


def _gate_e(tmpdir, mock):
    """E. changed OHLC -> revision+1; identical payload -> no new row (+fixed point)."""
    env = _Env(tmpdir, mock, "gate_e")
    try:
        _expect(to_fixed_point_price("1.00005") == 10001, "round-half-up failed for 1.00005")
        _expect(to_fixed_point_price("1.00004") == 10000, "round-down failed for 1.00004")
        _expect(to_fixed_point_price("385.2") == 3852000, "price scaling failed for 385.2")
        _expect(to_fixed_point_price(0.1) == 1000, "float price scaling failed for 0.1")
        _expect(to_fixed_point_price("231.21") == 2312100, "contract example price mismatch")
        _expect(to_fixed_point_amount("2.345") == 235, "amount round-half-up failed for 2.345")
        _expect(to_fixed_point_amount("2.344") == 234, "amount round-down failed for 2.344")
        _expect(to_fixed_point_amount("28900000") == 2890000000, "contract example amount mismatch")
        _expect(to_integer_volume("125000.4") == 125000, "volume rounding failed")
        overflowed = False
        try:
            to_fixed_point_price("999999999999999")
        except NormalizeReject as rej:
            overflowed = rej.reason == "VALUE_EXCEEDS_SAFE_INTEGER"
        _expect(overflowed, "no safe-integer overflow rejection")

        ctx = _ctx("US", "2026-01-15")
        v1 = normalize_round([_raw("AAPL", "0930", "231.21", "231.50", "231.80", "230.90",
                                   "125000", "28900000")], ctx)
        id1 = env.outbox.enqueue_batch(v1, market="US", captured_at_utc_ms=ctx.loop_ts_ms)
        _expect(env.payload_of(id1)["bars"][0][10] == 1, "first emission must be revision 1")

        v2 = normalize_round([_raw("AAPL", "0930", "231.21", "231.77", "231.90", "230.90",
                                   "131000", "30300000")], ctx)
        id2 = env.outbox.enqueue_batch(v2, market="US", captured_at_utc_ms=ctx.loop_ts_ms + 60000)
        _expect(bool(id2), "changed OHLC must create a new batch")
        _expect(env.payload_of(id2)["bars"][0][10] == 2, "changed OHLC must bump the revision to 2")

        id3 = env.outbox.enqueue_batch(v2, market="US", captured_at_utc_ms=ctx.loop_ts_ms + 120000)
        _expect(id3 == "", "identical payload must NOT create a new outbox row")
        state = env.outbox.bar_state("AAPL", 60, v2[0]["bar_start_utc_ms"])
        _expect(state["revision"] == 2, f"bar_state revision should stay 2, got {state}")
        return "fixed-point half-up verified; rev1 -> rev2 on change; identical payload skipped"
    finally:
        env.close()


def _gate_f(tmpdir, mock):
    """F. the newest bar is non-final; a later crawl finalises it exactly once."""
    env = _Env(tmpdir, mock, "gate_f")
    try:
        ctx = _ctx("HK", "2026-07-24")
        round1 = normalize_round([
            _raw("700", "0930", "385.2", "385.6", "385.8", "385.0", "12500", "4815000"),
            _raw("700", "0931", "385.6", "386.0", "386.2", "385.4", "9800", "3780000"),
        ], ctx)
        _expect(round1[0]["is_final"] is True, "the older bar must be final")
        _expect(round1[1]["is_final"] is False, "the newest bar must NOT be final")
        id1 = env.outbox.enqueue_batch(round1, market="HK", captured_at_utc_ms=ctx.loop_ts_ms)

        round2 = normalize_round([
            _raw("700", "0931", "385.6", "386.0", "386.2", "385.4", "9800", "3780000"),
            _raw("700", "0932", "386.0", "386.4", "386.6", "385.8", "10100", "3900000"),
        ], ctx)
        id2 = env.outbox.enqueue_batch(round2, market="HK", captured_at_utc_ms=ctx.loop_ts_ms + 60000)
        _expect(bool(id2), "the finalisation round must produce a batch")

        round3 = normalize_round([
            _raw("700", "0931", "385.6", "386.0", "386.2", "385.4", "9800", "3780000"),
            _raw("700", "0932", "386.0", "386.4", "386.6", "385.8", "10100", "3900000"),
        ], ctx)
        id3 = env.outbox.enqueue_batch(round3, market="HK", captured_at_utc_ms=ctx.loop_ts_ms + 120000)
        _expect(id3 == "", "a repeated identical round must not re-emit anything")

        target = round1[1]["bar_start_utc_ms"]  # the 09:31 identity
        finals, revisions = 0, []
        for batch_id in (id1, id2):
            for row in env.payload_of(batch_id)["bars"]:
                if row[0] == "00700" and row[2] == target:
                    revisions.append((row[9], row[10]))
                    if row[9] is True:
                        finals += 1
        _expect(finals == 1, f"identity must be finalised exactly once, got {finals} ({revisions})")
        _expect(revisions == [(False, 1), (True, 1)],
                f"finalise-once must not bump the revision, got {revisions}")
        state = env.outbox.bar_state("00700", 60, target)
        _expect(state["last_final_emitted"] is True, "bar_state.last_final_emitted not set")
        return f"09:31 identity emitted (is_final,revision) sequence {revisions}; third round skipped"
    finally:
        env.close()


def _gate_g(tmpdir, mock):
    """G. a changed current minute must NOT be reported as stale."""
    ctx = _ctx("US", "2026-01-15")
    base = normalize_round([
        _raw("AAPL", "0930", "231.21", "231.50", "231.80", "230.90", "125000", "28900000"),
        _raw("AAPL", "0931", "231.50", "231.62", "231.70", "231.40", "42000", "9700000"),
    ], ctx)
    changed = normalize_round([
        _raw("AAPL", "0930", "231.21", "231.50", "231.80", "230.90", "125000", "28900000"),
        _raw("AAPL", "0931", "231.50", "231.88", "231.95", "231.40", "51000", "11800000"),
    ], ctx)
    fp_base, env_base = compute_round_fingerprint("US", ctx.trade_date_local, base,
                                                  compute_watermark(base, 0), coverage_tabs=2)
    fp_same, _ = compute_round_fingerprint("US", ctx.trade_date_local, base,
                                           compute_watermark(base, 0), coverage_tabs=2)
    fp_changed, _ = compute_round_fingerprint("US", ctx.trade_date_local, changed,
                                              compute_watermark(changed, 0), coverage_tabs=2)
    fp_nextday, _ = compute_round_fingerprint("US", date(2026, 1, 16), base,
                                              compute_watermark(base, 0), coverage_tabs=2)
    _expect(fp_base == fp_same, "identical rounds must produce an identical fingerprint")
    _expect(fp_base != fp_changed, "a current-minute OHLC change caused a FALSE stale")
    _expect(fp_base != fp_nextday, "different trading dates must not share a fingerprint")
    _expect("payload_hash" in env_base and "watermark_utc_ms" in env_base
            and "coverage_bars" in env_base and "trade_date" in env_base,
            "fingerprint envelope missing required dimensions")
    return ("fingerprint dimensions=" + ",".join(sorted(env_base.keys()))
            + "; changed-minute -> different fingerprint (no false stale)")


def _gate_h(tmpdir, mock):
    """H. a bad signature or a malformed ACK can never commit a row."""
    env_bad = _Env(tmpdir, mock, "gate_h_bad", secret="wrong-secret-value")
    try:
        ctx = _ctx("US", "2026-01-15")
        bars = normalize_round([_raw("TSLA", "0930", "402.10", "403.00", "403.40", "401.80",
                                     "88000", "35400000")], ctx)
        bad_id = env_bad.outbox.enqueue_batch(bars, market="US", captured_at_utc_ms=ctx.loop_ts_ms)
        result = env_bad.send_now(bad_id)
        _expect(not result.committed, "a bad HMAC must never commit")
        _expect(result.http_status == 401, f"expected 401, got {result.http_status}")
        _expect(env_bad.outbox.get_row(bad_id).committed_at_ms is None, "row committed despite 401")
    finally:
        env_bad.close()

    env = _Env(tmpdir, mock, "gate_h_ack")
    try:
        ctx = _ctx("US", "2026-01-15")
        bars = normalize_round([_raw("TSLA", "0931", "403.00", "403.40", "403.90", "402.80",
                                     "77000", "31000000")], ctx)
        batch_id = env.outbox.enqueue_batch(bars, market="US", captured_at_utc_ms=ctx.loop_ts_ms)

        mock.ack_override = lambda ack: dict(ack, batch_id="00000000-0000-0000-0000-000000000000")
        r1 = env.send_now(batch_id)
        _expect(not r1.committed and r1.status_or_error == "ack_batch_id_mismatch",
                f"mismatched ACK id must not commit ({r1.status_or_error})")

        mock.ack_override = lambda ack: dict(ack, status="pending")
        r2 = env.send_now(batch_id)
        _expect(not r2.committed and r2.status_or_error.startswith("ack_status_"),
                f"non-committed ACK status must not commit ({r2.status_or_error})")

        mock.ack_override = lambda ack: {k: v for k, v in ack.items() if k != "highest_sequence"}
        r3 = env.send_now(batch_id)
        _expect(not r3.committed and r3.status_or_error.startswith("ack_missing_fields"),
                f"incomplete ACK must not commit ({r3.status_or_error})")

        mock.ack_override = None
        r4 = env.send_now(batch_id)
        _expect(r4.committed, f"a valid ACK must commit ({r4.status_or_error})")
        _expect(r4.duplicate, "the server already stored this batch, so it is an idempotent duplicate")
        return ("401 bad signature, ack id mismatch, ack status!=committed and incomplete ack all "
                "rejected; idempotent duplicate (accepted=0) accepted as committed")
    finally:
        mock.ack_override = None
        env.close()


def _gate_i(tmpdir, mock):
    """I. the fixture/manifest artifacts conform exactly to the integration lock."""
    out_dir = os.path.join(tmpdir, "integration")
    generate_fixture(out_dir)
    fixture_path = os.path.join(out_dir, "canonical-batch-v1.fixture.json")
    manifest_path = os.path.join(out_dir, "contract-manifest.json")
    readme_path = os.path.join(out_dir, "README.md")
    for path in (fixture_path, manifest_path, readme_path):
        _expect(os.path.exists(path), f"missing artifact {os.path.basename(path)}")

    with open(fixture_path, "r", encoding="utf-8") as fh:
        fixture = json.load(fh)
    with open(manifest_path, "r", encoding="utf-8") as fh:
        manifest = json.load(fh)

    _expect(fixture["contract_id"] == CONTRACT_ID, "fixture contract_id mismatch")
    _expect(fixture["contract_revision"] == CONTRACT_REVISION, "fixture contract_revision mismatch")
    _expect(manifest["contract_id"] == CONTRACT_ID, "manifest contract_id mismatch")
    _expect(manifest["contract_revision"] == CONTRACT_REVISION, "manifest revision mismatch")
    _expect(manifest["price_scale"] == 10000 and manifest["amount_scale"] == 100,
            "manifest scales do not match the contract")
    _expect([f["name"] for f in manifest["bar_row_order"]] == list(BAR_ROW_FIELDS),
            "manifest bar row order mismatch")
    _expect(manifest["ack_required_fields"] == list(ACK_REQUIRED_FIELDS),
            "manifest ACK fields mismatch")
    _expect("raw gzip bytes" in manifest["hmac"]["input"], "manifest HMAC rule mismatch")

    markets, has_duplicate, has_revision2, has_cross_day, has_transition = set(), False, False, False, False
    for case in fixture["cases"]:
        payload = case["canonical_payload"]
        _expect(list(payload.keys()) == list(PAYLOAD_FIELDS),
                f"payload key order broken in case {case['case']}")
        for row in payload["bars"]:
            _expect(len(row) == len(BAR_ROW_FIELDS), f"bar row arity in {case['case']}")
            _expect(isinstance(row[0], str) and isinstance(row[1], int) and isinstance(row[2], int),
                    f"bar row types in {case['case']}")
            _expect(all(isinstance(row[i], int) for i in (3, 4, 5, 6, 7, 8)),
                    f"fixed point fields must be integers in {case['case']}")
            _expect(isinstance(row[9], bool) and isinstance(row[10], int) and row[10] >= 1,
                    f"is_final/revision typing in {case['case']}")
            _expect(row[1] == TIMEFRAME_SEC, f"timeframe must be 60 in {case['case']}")
            if row[10] >= 2:
                has_revision2 = True
        markets.add(payload["market"])
        if case.get("expected_ack", {}).get("accepted") == 0:
            has_duplicate = True
        if case["case"] == "us_cross_day":
            starts = [r[2] for r in payload["bars"]]
            _expect(len(set(starts)) == len(starts), "cross-day case has colliding bar_start")
            has_cross_day = True
        if case["case"] == "us_finalise_transition":
            has_transition = any(r[9] is True for r in payload["bars"])

        text = canonical_json_text(payload)
        _expect(text == case["canonical_json_text"], f"canonical text mismatch in {case['case']}")
        gz = bytes.fromhex(case["gzip_hex"])
        _expect(sha256_hex(gz) == case["gzip_sha256"], f"gzip sha mismatch in {case['case']}")
        _expect(gunzip_bytes(gz).decode("utf-8") == text, f"gzip payload mismatch in {case['case']}")
        recomputed = hmac_sha256_hex(fixture["hmac"]["test_secret"], gz)
        _expect(recomputed == case["hmac_sha256_hex"], f"HMAC mismatch in {case['case']}")
        _expect(case["headers"]["X-Signature"] == "sha256=" + recomputed,
                f"X-Signature header mismatch in {case['case']}")
        _expect(case["headers"]["X-Batch-Id"] == payload["batch_id"], "X-Batch-Id mismatch")
        _expect(case["headers"]["X-Sequence"] == str(payload["sequence"]), "X-Sequence mismatch")
        _expect(case["headers"]["Content-Encoding"] == "gzip", "Content-Encoding must be gzip")

    _expect({"HK", "US"} <= markets, f"fixture must contain HK and US groups, got {markets}")
    _expect(has_duplicate, "fixture must contain a duplicate case")
    _expect(has_revision2, "fixture must contain a revision=2 supersede case")
    _expect(has_cross_day, "fixture must contain cross-day bars")
    _expect(has_transition, "fixture must contain an is_final false->true transition")
    _expect(fixture["hmac"]["test_secret"] == FIXTURE_TEST_SECRET, "fixture must record the test secret")
    _expect(fixture["hmac"]["gzip"]["mtime"] == 0, "fixture must record the deterministic gzip method")
    return (f"{len(fixture['cases'])} cases verified byte-exactly (canonical text, gzip sha256, "
            f"HMAC, headers) against the integration lock")


def _gate_j(tmpdir, mock):
    """J. the startup replay of pending rows happens BEFORE any new crawl."""
    env = _Env(tmpdir, mock, "gate_j")
    events = []
    try:
        ctx = _ctx("HK", "2026-07-24")
        for idx in range(2):
            bars = normalize_round([_raw("700", "093%d" % idx, "385.2", "385.6", "385.8",
                                         "385.0", str(1000 + idx), "400000")], ctx)
            env.outbox.enqueue_batch(bars, market="HK", captured_at_utc_ms=ctx.loop_ts_ms)
        _expect(env.outbox.stats()["pending_count"] == 2, "expected 2 pending rows before startup")

        mock.on_request = lambda rec: events.append("replay")
        report, crawl_value = bootstrap_startup(env.sender,
                                                lambda: (events.append("crawl"), "crawled")[1],
                                                replay_timeout_sec=20)
        _expect(crawl_value == "crawled", "the crawl callback did not run")
        _expect(events == ["replay", "replay", "crawl"], f"ordering violated: {events}")
        _expect(report["pending_after"] == 0, "pending rows were left behind")
        return f"events={events} replay_report={report}"
    finally:
        mock.on_request = None
        env.close()


def _gate_k(tmpdir, mock):
    """K. cleanup removes only expired committed rows; pending is never deleted."""
    env = _Env(tmpdir, mock, "gate_k")
    try:
        ctx = _ctx("US", "2026-01-15")
        ids = []
        for idx, symbol in enumerate(("AAPL", "MSFT", "NVDA")):
            bars = normalize_round([_raw(symbol, "0930", "231.21", f"231.{40 + idx}", "231.80",
                                         "230.90", "125000", "28900000")], ctx)
            ids.append(env.outbox.enqueue_batch(bars, market="US", captured_at_utc_ms=ctx.loop_ts_ms))
        old_id, fresh_id, pending_id = ids

        env.send_now(old_id)
        env.send_now(fresh_id)
        stamp = now_ms()
        old_committed_at = stamp - int(200 * 3600 * 1000)  # 200h > 168h retention
        with env.outbox._lock:  # test-only direct fixture of the committed timestamp
            env.outbox._begin()
            env.outbox._conn.execute("UPDATE outbox SET committed_at_ms=? WHERE batch_id=?",
                                     (old_committed_at, old_id))
            env.outbox._conn.execute("COMMIT")

        deleted = env.outbox.cleanup_expired_committed(stamp)
        _expect(deleted == 1, f"cleanup should delete exactly 1 row, deleted {deleted}")
        _expect(env.outbox.get_row(old_id) is None, "the expired committed row was not deleted")
        _expect(env.outbox.get_row(fresh_id) is not None, "a fresh committed row was wrongly deleted")
        _expect(env.outbox.get_row(pending_id) is not None, "a PENDING row was deleted — forbidden")
        _expect(env.outbox.stats()["pending_count"] == 1, "pending count changed after cleanup")
        return (f"deleted={deleted} (committed older than {env.cfg.OUTBOX_RETENTION_HOURS}h); "
                f"fresh committed + pending retained")
    finally:
        env.close()


def _gate_l(tmpdir, mock):
    """L. SIGTERM leaves the DB intact, keeps pending rows and duplicates nothing."""
    db_path = os.path.join(tmpdir, "gate_l.sqlite3")
    ready_file = os.path.join(tmpdir, "gate_l.ready")
    child_env = dict(os.environ)
    child_env.update({
        "FUTU_ENV": "test",
        "PRODUCER_ID": "self-test-01",
        "MARKET_MODE": "HK",
        "PUBLIC_DIR": tmpdir,
        "OUTBOX_DB_PATH": db_path,
        "INGEST_URL": "http://127.0.0.1:1/unreachable",
        "INGEST_HMAC_SECRET": FIXTURE_TEST_SECRET,
        "HEALTH_FILE_PATH": os.path.join(tmpdir, "gate_l_health.json"),
    })
    proc = subprocess.Popen(
        [sys.executable, os.path.abspath(__file__), "--selftest-shutdown-child",
         "--outbox-db", db_path, "--ready-file", ready_file],
        env=child_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    try:
        deadline = time.time() + 30
        while time.time() < deadline and not os.path.exists(ready_file):
            if proc.poll() is not None:
                out, err = proc.communicate(timeout=5)
                raise SelfTestFailure(f"child exited early rc={proc.returncode} err={err[-400:]}")
            time.sleep(0.1)
        _expect(os.path.exists(ready_file), "the shutdown child never became ready")

        proc.send_signal(signal.SIGTERM)
        try:
            rc = proc.wait(timeout=30)
        except subprocess.TimeoutExpired:
            proc.kill()
            raise SelfTestFailure("the child did not exit within 30s of SIGTERM")
        _expect(rc == 0, f"graceful shutdown must exit 0, got {rc}")
    finally:
        if proc.poll() is None:
            proc.kill()

    cfg = _test_config(tmpdir, mock.url, FIXTURE_TEST_SECRET, db_path)
    outbox = Outbox(db_path=db_path, cfg=cfg, producer_id="self-test-01")
    try:
        integrity = outbox.integrity_check()
        stats = outbox.stats()
        _expect(integrity == "ok", f"PRAGMA integrity_check returned {integrity}")
        _expect(stats["pending_count"] == 1, f"pending must be retained, got {stats['pending_count']}")
        _expect(stats["committed_count"] == 0, "nothing may be committed without an ACK")
        return (f"SIGTERM -> rc=0, integrity_check={integrity}, pending retained="
                f"{stats['pending_count']}, committed={stats['committed_count']}")
    finally:
        outbox.close()


def _gate_m(tmpdir, mock):
    """M. the mock server receives the exact contract headers."""
    env = _Env(tmpdir, mock, "gate_m")
    try:
        ctx = _ctx("HK", "2026-07-24")
        bars = normalize_round([_raw("9988", "0930", "112.30", "112.60", "112.80", "112.10",
                                     "220000", "24700000")], ctx)
        batch_id = env.outbox.enqueue_batch(bars, market="HK", captured_at_utc_ms=ctx.loop_ts_ms)
        row = env.outbox.get_row(batch_id)
        result = env.send_now(batch_id)
        _expect(result.committed, f"send failed: {result.status_or_error}")

        record = mock.last_request()
        headers = {k.lower(): v for k, v in record["headers"].items()}
        _expect(record["path"] == INGEST_PATH, f"wrong path {record['path']}")
        _expect(headers.get("content-type") == "application/json", "Content-Type must be application/json")
        _expect(headers.get("content-encoding") == "gzip", "Content-Encoding must be gzip")
        _expect(headers.get("x-producer-id") == env.cfg.PRODUCER_ID, "X-Producer-Id mismatch")
        _expect(headers.get("x-batch-id") == batch_id, "X-Batch-Id mismatch")
        _expect(re.fullmatch(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
                             headers.get("x-batch-id", "")), "X-Batch-Id is not a uuid")
        _expect(headers.get("x-sequence") == str(row.sequence), "X-Sequence mismatch")
        signature = headers.get("x-signature", "")
        _expect(re.fullmatch(r"sha256=[0-9a-f]{64}", signature), f"bad X-Signature format {signature}")
        _expect(signature == "sha256=" + hmac_sha256_hex(FIXTURE_TEST_SECRET,
                                                         env.outbox.get_row(batch_id).payload),
                "X-Signature is not the HMAC of the raw gzip bytes")
        _expect(record["body_sha256"] == row.payload_sha256,
                "the bytes on the wire differ from the stored outbox payload")
        return ("headers verified: X-Producer-Id/X-Batch-Id(uuid)/X-Sequence/"
                "X-Signature(sha256=<64hex> over raw gzip)/Content-Encoding=gzip")
    finally:
        env.close()


def _gate_n(tmpdir, mock):
    """N. R69:APP-HKT — HKT-displayed US bars convert to exact UTC; DST auto-adapt."""
    original_display = CONFIG.BAR_TIME_DISPLAY
    CONFIG.BAR_TIME_DISPLAY = "HKT"
    try:
        def _hkt_ctx(iso_day, hh, mm):
            day = date.fromisoformat(iso_day)
            stamp = int(datetime(day.year, day.month, day.day, hh, mm, tzinfo=HK_TZ).timestamp() * 1000)
            return CrawlContext("US", day, "REG", stamp, 5)
        # 冬令（EST）：HKT 21:30 = 08:30 EST = 13:30 UTC（pre-market 窗口內，accept）
        ts_w = derive_bar_start_utc_ms("AAPL", "2130", _hkt_ctx("2026-01-15", 21, 30))
        _expect(datetime.fromtimestamp(ts_w / 1000, UTC).isoformat() == "2026-01-15T13:30:00+00:00",
                "HKT->UTC winter (EST) conversion mismatch")
        # 夏令（EDT）：同一 HKT 21:30 = 09:30 EDT = 13:30 UTC（HKT 固定 +8，DST 自動適應）
        ts_s = derive_bar_start_utc_ms("AAPL", "2130", _hkt_ctx("2026-07-15", 21, 30))
        _expect(datetime.fromtimestamp(ts_s / 1000, UTC).isoformat() == "2026-07-15T13:30:00+00:00",
                "HKT->UTC summer (EDT) conversion mismatch")
        # 跨午夜錨點：HKT 01:12 爬到 HKT 01:12 bar = 前一日 13:12 EDT（REG，accept）
        ts_x = derive_bar_start_utc_ms("AAPL", "0112", _hkt_ctx("2026-07-15", 1, 12))
        _expect(datetime.fromtimestamp(ts_x / 1000, UTC).isoformat() == "2026-07-14T17:12:00+00:00",
                "HKT cross-midnight anchor mismatch")
        # 美期／crypto 同一樣錨定（US_FUT/CRYPTO 窗口）
        ts_f = derive_bar_start_utc_ms("NQMAIN", "0112", _hkt_ctx("2026-07-15", 1, 12))
        _expect(ts_f == ts_x, "US_FUT anchor must match US_STOCK anchor for same HKT hhmm")
        # 死區 reject：HKT 12:00 = 00:00 EDT（美股休市）必須 OUT_OF_SESSION
        rejected = False
        try:
            derive_bar_start_utc_ms("AAPL", "1200", _hkt_ctx("2026-07-15", 12, 0))
        except NormalizeReject as rej:
            rejected = (rej.reason == "OUT_OF_SESSION")
        _expect(rejected, "US dead-zone (ET overnight) bar must be rejected")
        return ("HKT-display conversion verified: EST/EDT auto-adapt + cross-midnight anchor "
                "+ US_FUT parity + dead-zone reject")
    finally:
        CONFIG.BAR_TIME_DISPLAY = original_display


SELF_TEST_GATES = (
    ("A", "batch durable in SQLite before HTTP; commit only on valid ACK", _gate_a),
    ("B", "first POST fails, row retained, later retry succeeds", _gate_b),
    ("C", "restart replays pending rows in sequence order", _gate_c),
    ("D", "same HHMM on different trading dates -> distinct bars", _gate_d),
    ("E", "changed OHLC -> revision+1; identical -> no duplicate", _gate_e),
    ("F", "newest bar non-final; later crawl finalises exactly once", _gate_f),
    ("G", "changed current minute -> no false stale", _gate_g),
    ("H", "bad signature / bad ACK cannot commit a row", _gate_h),
    ("I", "fixture artifacts conform exactly to the integration lock", _gate_i),
    ("J", "startup replay happens before a new crawl starts", _gate_j),
    ("K", "cleanup deletes only expired committed rows, never pending", _gate_k),
    ("L", "graceful SIGTERM: DB intact, pending retained, no duplicate commit", _gate_l),
    ("M", "mock server receives the correct headers", _gate_m),
    ("N", "R69 APP-HKT: HKT-displayed US bars -> exact UTC, DST auto-adapt", _gate_n),
)


def run_self_test(only=None, keep_temp=False) -> dict:
    """Execute every test gate offline and return a TestReport dict."""
    global CONFIG
    original_config = CONFIG
    tmpdir = tempfile.mkdtemp(prefix="futu-selftest-")
    mock = MockIngestServer(secret=FIXTURE_TEST_SECRET)
    mock.start()
    started = datetime.now(UTC)
    results = []
    selected = {g.upper() for g in (only or [])} or None

    print("=" * 78)
    print(f"futu.py {APP_VERSION} — SELF TEST  ({CONTRACT_ID} rev {CONTRACT_REVISION})")
    print(f"python {sys.version.split()[0]}  requests={getattr(requests, '__version__', 'MISSING')}  "
          f"sqlite3={sqlite3.sqlite_version}")
    print(f"temp dir: {tmpdir}")
    print(f"mock ingest: {mock.url}")
    print("=" * 78)

    try:
        CONFIG = _test_config(tmpdir, mock.url, FIXTURE_TEST_SECRET,
                              os.path.join(tmpdir, "default.sqlite3"))
        for gate_id, title, func in SELF_TEST_GATES:
            if selected and gate_id not in selected:
                continue
            mock.reset()
            t0 = time.perf_counter()
            try:
                detail = func(tmpdir, mock)
                status = "PASS"
            except SelfTestFailure as exc:
                detail, status = str(exc), "FAIL"
            except Exception as exc:
                detail = f"{type(exc).__name__}: {exc}\n{traceback.format_exc(limit=4)}"
                status = "ERROR"
            elapsed_ms = int((time.perf_counter() - t0) * 1000)
            results.append({"gate": gate_id, "title": title, "status": status,
                            "detail": detail, "elapsed_ms": elapsed_ms})
            icon = "✅" if status == "PASS" else "❌"
            print(f"{icon} [{gate_id}] {title}  ({elapsed_ms} ms)")
            print(f"      {detail}")
    finally:
        mock.stop()
        CONFIG = original_config
        if not keep_temp:
            shutil.rmtree(tmpdir, ignore_errors=True)

    passed = sum(1 for r in results if r["status"] == "PASS")
    failed = len(results) - passed
    finished = datetime.now(UTC)
    report = {
        "contract_id": CONTRACT_ID,
        "contract_revision": CONTRACT_REVISION,
        "version": APP_VERSION,
        "python": sys.version.split()[0],
        "requests": getattr(requests, "__version__", None),
        "sqlite": sqlite3.sqlite_version,
        "started_at": started.isoformat().replace("+00:00", "Z"),
        "finished_at": finished.isoformat().replace("+00:00", "Z"),
        "duration_ms": int((finished - started).total_seconds() * 1000),
        "total": len(results),
        "passed": passed,
        "failed": failed,
        "gates": results,
    }
    print("-" * 78)
    print(f"RESULT: {passed}/{len(results)} gates passed, {failed} failed "
          f"({report['duration_ms']} ms total)")
    print("=" * 78)
    return report


def _run_shutdown_child(db_path, ready_file):
    """Hidden mode used by test gate L: hold one pending batch, await SIGTERM."""
    cfg = Config(overrides={"OUTBOX_DB_PATH": db_path, "FUTU_ENV": "test"})
    global CONFIG
    CONFIG = cfg
    init_delivery_stack(cfg=cfg, db_path=db_path, url=cfg.INGEST_URL,
                        secret=cfg.INGEST_HMAC_SECRET, producer_id=cfg.PRODUCER_ID)
    install_signal_handlers()
    ctx = _ctx("HK", "2026-07-24")
    bars = normalize_round([_raw("700", "0930", "385.2", "385.6", "385.8", "385.0",
                                 "12500", "4815000")], ctx)
    OUTBOX.enqueue_batch(bars, market="HK", captured_at_utc_ms=ctx.loop_ts_ms)
    with open(ready_file, "w", encoding="utf-8") as fh:
        fh.write(str(os.getpid()))
    while not SHUTDOWN_EVENT.wait(0.1):
        pass
    graceful_close(timeout_sec=10)
    return 0


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 20 — W6 INTEGRATION ARTIFACTS (fixture / manifest / README)
# ══════════════════════════════════════════════════════════════════════════════
def _fixture_batch_id(case_name):
    return str(uuid.uuid5(uuid.NAMESPACE_URL, f"{CONTRACT_ID}/{CONTRACT_REVISION}/{case_name}"))


def _fixture_case(case_name, description, producer_id, sequence, market, bars,
                  captured_at_utc_ms, watermark_utc_ms, expected_ack_overrides=None,
                  batch_id=None):
    bid = batch_id or _fixture_batch_id(case_name)
    payload = build_canonical_payload(producer_id, bid, sequence, market, bars,
                                      captured_at_utc_ms, watermark_utc_ms)
    text = canonical_json_text(payload)
    gz = gzip_bytes(text.encode("utf-8"))
    signature = hmac_sha256_hex(FIXTURE_TEST_SECRET, gz)
    ack = {
        "batch_id": bid,
        "status": ACK_STATUS_COMMITTED,
        "accepted": len(payload["bars"]),
        "duplicate": 0,
        "rejected": 0,
        "highest_sequence": sequence,
    }
    ack.update(expected_ack_overrides or {})
    return {
        "case": case_name,
        "description": description,
        "headers": {
            "Content-Type": "application/json",
            "Content-Encoding": "gzip",
            "X-Producer-Id": producer_id,
            "X-Batch-Id": bid,
            "X-Sequence": str(sequence),
            "X-Signature": "sha256=" + signature,
        },
        "canonical_payload": payload,
        "canonical_json_text": text,
        "gzip_hex": gz.hex(),
        "gzip_sha256": sha256_hex(gz),
        "hmac_sha256_hex": signature,
        "expected_ack": ack,
    }


def generate_fixture(output_dir=None) -> None:
    """Write integration/canonical-batch-v1.fixture.json, contract-manifest.json
    and README.md — deterministic, so the server engineer can diff and recompute."""
    out_dir = output_dir or os.path.join(os.path.dirname(os.path.abspath(__file__)), "integration")
    os.makedirs(out_dir, exist_ok=True)

    hk_ctx = _ctx("HK", "2026-07-24")
    us_ctx = _ctx("US", "2026-01-15")
    us_ctx_next = _ctx("US", "2026-01-16")

    hk_0930 = derive_bar_start_utc_ms("00700", "0930", hk_ctx)
    hk_0931 = derive_bar_start_utc_ms("00700", "0931", hk_ctx)
    us_0930 = derive_bar_start_utc_ms("AAPL", "0930", us_ctx)
    us_0931 = derive_bar_start_utc_ms("AAPL", "0931", us_ctx)
    us_0930_next = derive_bar_start_utc_ms("AAPL", "0930", us_ctx_next)

    hk_bars = [
        make_canonical_bar("00700", hk_0930, to_fixed_point_price("385.20"),
                           to_fixed_point_price("385.80"), to_fixed_point_price("385.00"),
                           to_fixed_point_price("385.60"), 12500,
                           to_fixed_point_amount("4815000.00"), is_final=True, revision=1),
        make_canonical_bar("00700", hk_0931, to_fixed_point_price("385.60"),
                           to_fixed_point_price("386.20"), to_fixed_point_price("385.40"),
                           to_fixed_point_price("386.00"), 9800,
                           to_fixed_point_amount("3780000.00"), is_final=False, revision=1),
    ]
    us_bars = [
        make_canonical_bar("AAPL", us_0930, 2312100, 2318000, 2309000, 2315000, 125000,
                           2890000000, is_final=True, revision=1),
        make_canonical_bar("AAPL", us_0931, 2315000, 2316200, 2314000, 2315600, 42000,
                           970000000, is_final=False, revision=1),
    ]
    revision_bars = [
        make_canonical_bar("AAPL", us_0930, 2312100, 2319500, 2309000, 2317700, 131000,
                           3030000000, is_final=True, revision=2),
    ]
    cross_day_bars = [
        make_canonical_bar("AAPL", us_0930, 2312100, 2318000, 2309000, 2315000, 125000,
                           2890000000, is_final=True, revision=1),
        make_canonical_bar("AAPL", us_0930_next, 2322100, 2328000, 2319000, 2325000, 135000,
                           2990000000, is_final=True, revision=1),
    ]
    finalise_bars = [
        make_canonical_bar("AAPL", us_0931, 2315000, 2316200, 2314000, 2315600, 42000,
                           970000000, is_final=True, revision=1),
    ]

    hk_capture = hk_ctx.loop_ts_ms
    us_capture = us_ctx.loop_ts_ms
    us_normal_id = _fixture_batch_id("us_normal")

    cases = [
        _fixture_case("hk_normal", "HK group: one finalised 09:30 bar plus the live 09:31 bar.",
                      "hk-01", 18201, "HK", hk_bars, hk_capture, hk_0930),
        _fixture_case("us_normal", "US group: one finalised 09:30 bar plus the live 09:31 bar.",
                      "us-01", 18202, "US", us_bars, us_capture, us_0930),
        _fixture_case("us_duplicate_resend",
                      "Byte-identical resend of us_normal (same batch_id and sequence): the server "
                      "must answer 200 + status=committed + accepted=0 + duplicate>0.",
                      "us-01", 18202, "US", us_bars, us_capture, us_0930,
                      expected_ack_overrides={"accepted": 0, "duplicate": len(us_bars),
                                              "highest_sequence": 18202},
                      batch_id=us_normal_id),
        _fixture_case("us_revision_supersede",
                      "Same identity as us_normal 09:30 with changed OHLCVA: revision=2 supersedes "
                      "revision=1 (higher revision wins).",
                      "us-01", 18203, "US", revision_bars, us_capture + 60000, us_0930),
        _fixture_case("us_cross_day",
                      "Same HHMM (09:30) on two different trading dates: two distinct identities, "
                      "no collision.",
                      "us-01", 18204, "US", cross_day_bars, us_ctx_next.loop_ts_ms, us_0930_next),
        _fixture_case("us_finalise_transition",
                      "The 09:31 identity previously delivered with is_final=false is now final; "
                      "finalise-once keeps revision=1.",
                      "us-01", 18205, "US", finalise_bars, us_capture + 120000, us_0931),
    ]

    fixture = {
        "contract_id": CONTRACT_ID,
        "contract_revision": CONTRACT_REVISION,
        "schema_version": SCHEMA_VERSION,
        "generator": f"futu.py {APP_VERSION}",
        "generated_by_command": "python3 futu.py --generate-fixture",
        "deterministic": True,
        "hmac": {
            "algorithm": "HMAC-SHA256",
            "input": "the raw gzip bytes of the request body (not the JSON text, not the "
                     "decompressed bytes)",
            "header": "X-Signature: sha256=<hex>",
            "test_secret": FIXTURE_TEST_SECRET,
            "test_secret_note": "TEST ONLY — never a production secret; production secrets come "
                                "from INGEST_HMAC_SECRET per producer.",
            "gzip": {
                "library": "python stdlib gzip.GzipFile",
                "compresslevel": GZIP_COMPRESS_LEVEL,
                "mtime": 0,
                "filename_field": "empty",
                "note": "gzip_hex in every case is the exact byte stream that was signed and sent; "
                        "recompute the HMAC over those bytes.",
            },
        },
        "json_serialisation": {
            "separators": [",", ":"],
            "ensure_ascii": False,
            "key_order": list(PAYLOAD_FIELDS),
            "bar_row_order": list(BAR_ROW_FIELDS),
        },
        "cases": cases,
    }

    manifest = {
        "contract_id": CONTRACT_ID,
        "contract_revision": CONTRACT_REVISION,
        "schema_version": SCHEMA_VERSION,
        "producer": f"futu.py {APP_VERSION}",
        "price_scale": 10000,
        "amount_scale": 100,
        "timeframe_sec": TIMEFRAME_SEC,
        "http_request": {
            "method": "POST",
            "path": INGEST_PATH,
            "headers": ["Content-Type: application/json", "Content-Encoding: gzip",
                        "X-Producer-Id: <producer_id>", "X-Batch-Id: <uuid>",
                        "X-Sequence: <monotonic-integer>",
                        "X-Signature: sha256=<hex HMAC-SHA256 over raw compressed request bytes>"],
        },
        "payload_field_order": list(PAYLOAD_FIELDS),
        "bar_row_order": [
            {"index": i, "name": name,
             "type": ("string" if i == 0 else "boolean" if i == 9 else "integer")}
            for i, name in enumerate(BAR_ROW_FIELDS)
        ],
        "hmac": {
            "algorithm": "HMAC-SHA256",
            "input": "raw gzip bytes of the request body",
            "header_format": "sha256=<64 lowercase hex chars>",
        },
        "ack_required_fields": list(ACK_REQUIRED_FIELDS),
        "ack_commit_rule": "HTTP 2xx AND ack.batch_id == request batch_id AND ack.status == "
                           "'committed' (accepted==0 with duplicate>0 is a documented idempotent "
                           "duplicate and also counts as committed)",
        "semantic_rules": [
            "unique identity = symbol + timeframe_sec + bar_start_utc_ms",
            "bar_start_utc_ms is the market bar start time; never HTTP receive time or Date.now",
            "captured_at_utc_ms is observability only",
            "for the same identity a higher revision wins; lower or equal must be idempotent",
            "only the first valid is_final=true per identity may trigger irreversible state",
            "PRICE_SCALE=10000, AMOUNT_SCALE=100, fixed-point integers",
            "HMAC input is the actual gzip raw bytes sent",
            "the producer's normal path is direct push; file webhook/pull is not the truth",
        ],
        "time_rules": {
            "HK": {"tz": "Asia/Hong_Kong", "sessions": ["09:30-12:00", "13:00-16:00"], "dst": False},
            "US": {"tz": "America/New_York", "sessions": ["09:30-16:00"], "dst": True},
            "bar_start_formula": "market_local_midnight_utc + hhmm_minutes*60000 - tz_offset_ms",
            "examples": {
                "HK 2026-07-24 09:30": "2026-07-24T01:30:00Z",
                "US 2026-01-15 09:30 (EST)": "2026-01-15T14:30:00Z",
                "US 2026-07-15 09:30 (EDT)": "2026-07-15T13:30:00Z",
            },
        },
    }

    readme = f"""# Integration artifacts — {CONTRACT_ID} (revision {CONTRACT_REVISION})

Generated by `futu.py {APP_VERSION}` with `python3 futu.py --generate-fixture`.
These three files are the cross-program acceptance material for the server (`server.js`)
engineer. Nothing here contains a production secret.

## Files

| file | purpose |
| --- | --- |
| `canonical-batch-v1.fixture.json` | Ready-made canonical batches: exact JSON text, exact gzip bytes (hex), exact HMAC signature, exact headers, expected ACK. |
| `contract-manifest.json` | Machine-readable contract summary: field order, scales, HMAC rule, ACK rule, time rules. |
| `README.md` | This document. |

## The contract in one paragraph

The producer POSTs `{INGEST_PATH}` with `Content-Type: application/json`,
`Content-Encoding: gzip`, `X-Producer-Id`, `X-Batch-Id` (uuid), `X-Sequence`
(monotonic per producer) and `X-Signature: sha256=<hex>`. The signature is
**HMAC-SHA256 over the raw gzip request body** — not over the JSON text and not
over the decompressed bytes. The body decompresses to a canonical payload whose
keys are exactly `{", ".join(PAYLOAD_FIELDS)}`, and each bar is a fixed-order
array `{list(BAR_ROW_FIELDS)}`. Prices are fixed point with PRICE_SCALE=10000,
amounts with AMOUNT_SCALE=100.

## How to run the cross-program test

1. Load the fixture:

```js
const fixture = JSON.parse(fs.readFileSync('canonical-batch-v1.fixture.json', 'utf8'));
```

2. For each case, rebuild the exact request body from `gzip_hex`:

```js
const body = Buffer.from(testCase.gzip_hex, 'hex');
```

3. Recompute the signature with the recorded **test-only** secret and compare:

```js
const sig = 'sha256=' + crypto.createHmac('sha256', fixture.hmac.test_secret)
                              .update(body).digest('hex');
console.assert(sig === testCase.headers['X-Signature']);
```

4. Feed `body` + `testCase.headers` into the ingest handler (with the producer
   configured to use `fixture.hmac.test_secret`) and compare the response with
   `testCase.expected_ack`.

5. Case expectations:
   * `hk_normal`, `us_normal` — accepted == number of bars, `status=committed`.
   * `us_duplicate_resend` — identical `batch_id`/`sequence`: the server must
     answer `200`, `status=committed`, `accepted=0`, `duplicate>0`. The producer
     treats that shape as committed and clears the outbox row.
   * `us_revision_supersede` — same identity as `us_normal` 09:30 with
     `revision=2`; the higher revision wins, a replay of revision 1 must be
     ignored.
   * `us_cross_day` — the same HHMM on two trading dates must remain two
     identities (`bar_start_utc_ms` differs by exactly 86400000 ms here).
   * `us_finalise_transition` — the 09:31 identity flips `is_final` from false to
     true **without** a revision bump (finalise once).

6. Python equivalent for step 3:

```python
import hmac, hashlib, json
fixture = json.load(open('canonical-batch-v1.fixture.json'))
case = fixture['cases'][0]
body = bytes.fromhex(case['gzip_hex'])
sig = 'sha256=' + hmac.new(fixture['hmac']['test_secret'].encode(), body, hashlib.sha256).hexdigest()
assert sig == case['headers']['X-Signature']
```

## Reproducing the gzip bytes

The gzip stream is deterministic: `gzip.GzipFile(compresslevel={GZIP_COMPRESS_LEVEL}, mtime=0)`
over the UTF-8 bytes of `canonical_json_text` (JSON separators `(",", ":")`,
`ensure_ascii=False`, key order fixed). Because the exact bytes are shipped in
`gzip_hex`, a different zlib build on the server side never breaks verification.

## HHMM / date assumptions

The Futu UI exposes only `HHMM`. `bar_start_utc_ms` is therefore derived from
`trading date + HHMM + session` in the market timezone
(`Asia/Hong_Kong`, `America/New_York` with EST/EDT), never from the capture
clock. Sessions: HK `09:30-12:00` and `13:00-16:00`; US `09:30-16:00`.
`captured_at_utc_ms` carries the UI capture instant for observability only.
"""

    _atomic_write_json(os.path.join(out_dir, "canonical-batch-v1.fixture.json"), fixture)
    _atomic_write_json(os.path.join(out_dir, "contract-manifest.json"), manifest)
    tmp_readme = os.path.join(out_dir, "README.md.tmp")
    with open(tmp_readme, "w", encoding="utf-8") as fh:
        fh.write(readme)
    os.replace(tmp_readme, os.path.join(out_dir, "README.md"))
    return None


# ══════════════════════════════════════════════════════════════════════════════
# SECTION 21 — CLI + MAIN
# ══════════════════════════════════════════════════════════════════════════════
def parse_args(argv=None):
    parser = argparse.ArgumentParser(
        description=f"futu.py {APP_VERSION} — Kline Probe & canonical batch producer")
    parser.add_argument("market", nargs="?", choices=["HK", "US", "AUTO"], default=None,
                        help="force a market (baseline behaviour); default AUTO/.env")
    parser.add_argument("--reset", action="store_true", help="delete the current market ROUND0 cache")
    parser.add_argument("--reset-all", action="store_true", help="delete every ROUND0 cache")
    parser.add_argument("--bars", type=int, choices=range(1, 9), metavar="N",
                        help="number of K-line segments read per symbol (1..8)")  # P1-01
    parser.add_argument("--self-test", action="store_true", help="run the offline test gates A..M")
    parser.add_argument("--gate", action="append", default=None,
                        help="run only the given self-test gate (repeatable), e.g. --gate A")
    parser.add_argument("--keep-temp", action="store_true", help="keep the self-test temp directory")
    parser.add_argument("--generate-fixture", action="store_true",
                        help="(re)generate the integration/ artifacts")
    parser.add_argument("--integration-dir", default=None, help="output directory for --generate-fixture")
    parser.add_argument("--replay-only", action="store_true",
                        help="replay pending outbox batches and exit (no crawl)")
    parser.add_argument("--print-config", action="store_true", help="print the effective config (no secrets)")
    parser.add_argument("--health-once", action="store_true", help="print one health snapshot and exit")
    parser.add_argument("--env-file", default=None, help="path to the .env file")
    parser.add_argument("--version", action="store_true", help="print the version and exit")
    parser.add_argument("--selftest-shutdown-child", action="store_true", help=argparse.SUPPRESS)
    parser.add_argument("--outbox-db", default=None, help=argparse.SUPPRESS)
    parser.add_argument("--ready-file", default=None, help=argparse.SUPPRESS)
    return parser.parse_args(argv)


def print_startup_banner():
    lp("=" * 68)
    lp(f"🚀 futu.py {APP_VERSION} — canonical batch producer")
    lp(f"   contract     : {CONTRACT_ID} rev {CONTRACT_REVISION}")
    lp(f"   producer_id  : {CONFIG.PRODUCER_ID or '(unset)'}")
    lp(f"   market       : {MARKET_MODE} (force={FORCE_MARKET})")
    lp(f"   ingest_url   : {CONFIG.INGEST_URL or '(unset)'}")
    lp(f"   outbox_db    : {CONFIG.OUTBOX_DB_PATH}")
    lp(f"   health       : http://{CONFIG.HEALTH_BIND_HOST}:{CONFIG.HEALTH_PORT}/health")
    lp(f"   legacy files : {CONFIG.LEGACY_FILE_OUTPUT} | legacy webhook: "
       f"{'on' if CONFIG.LEGACY_WEBHOOK_URL else 'off'}")
    lp(f"   watchdog     : {WATCHDOG_TIMEOUT}s   bars/symbol: {CONFIG.KLINE_BAR_COUNT}")
    lp(f"   fleet        : producer_id/secret/market are .env driven; the machine registry is "
       f"operator input, no code change required")
    lp("=" * 68)
    log_important("START", f"producer_id={CONFIG.PRODUCER_ID} market={MARKET_MODE} "
                           f"version={APP_VERSION}", print_to_pm2=False)


def enforce_production_security():
    problems = CONFIG.validate_for_production()
    if not problems:
        return
    if CONFIG.is_production:
        for problem in problems:
            lp(f"❌ [SECURITY] {problem}")
        log_important("BOOT_ABORT", f"missing production configuration: {problems}")
        sys.exit(1)
    lp(f"⚠️ [SECURITY] non-production environment ({CONFIG.FUTU_ENV}); continuing with: {problems}")


def load_round0_cache(market, reset=False):
    tabs, name_to_symbol, symbol_order = [], {}, {}
    cache_file = get_round0_cache_file(market) if reset else ensure_round0_cache_from_legacy(market)
    if not os.path.exists(cache_file):
        return tabs, name_to_symbol, symbol_order, False
    try:
        with open(cache_file, "r", encoding="utf-8") as fh:
            cache = json.load(fh)
        if cache.get("market") != market or not cache.get("tabs"):
            return tabs, name_to_symbol, symbol_order, False
        tabs = cache["tabs"]
        for idx, row in enumerate(cache.get("data", [])):
            if len(row) >= 2:
                code, name = row[0], row[1]
                try:
                    # FIX K-26：safe unicode flags + try/except fallback（怪字符唔斬倉初始化）
                    cleaned = re.sub(r"\s*[(（](?:期貨)?主連 [^)）]*[)）]", "", str(name), flags=re.UNICODE).strip()
                except Exception:
                    cleaned = str(name).strip()
                name_to_symbol[cleaned] = code
                name_to_symbol[name] = code
                symbol_order[code] = idx
        lp(f"\n🎉 找到 {market} R0 緩存 ({len(tabs)} tabs, {len(symbol_order)} 股票): {cache_file}")
        try:
            refresh_round0_public_file()
        except Exception as exc:
            log_exception("ROUND0_PUBLIC_REFRESH_FAILED", exc)
        return tabs, name_to_symbol, symbol_order, True
    except Exception as exc:
        log_exception("ROUND0_CACHE_LOAD_FAILED", exc, cache_file=cache_file)
        return [], {}, {}, False


def setup_and_run(args):
    """Production entry point: delivery stack -> health -> replay -> crawl."""
    global MARKET_MODE, FORCE_MARKET, KLINE_BAR_COUNT, WATCHDOG_TIMEOUT, _ACTIVE_CRAWLER

    FORCE_MARKET = (args.market or CONFIG.MARKET_MODE or "AUTO").upper()
    if FORCE_MARKET not in ("HK", "US", "AUTO"):
        FORCE_MARKET = "AUTO"
    if args.bars:
        _bc = max(1, min(8, int(args.bars)))  # P1-01: --bars 同行 1–8 clamp，唔繞過 Config
        KLINE_BAR_COUNT = _bc
        CONFIG.KLINE_BAR_COUNT = _bc
    WATCHDOG_TIMEOUT = CONFIG.WATCHDOG_TIMEOUT_SEC

    if args.reset_all:
        for path in (CONFIG.ROUND0_CACHE_HK_FILE, CONFIG.ROUND0_CACHE_US_FILE,
                     CONFIG.ROUND0_FILE, CONFIG.ROUND0_CACHE_META_FILE):
            try:
                if os.path.exists(path):
                    os.remove(path)
                    lp(f"🧹 --reset-all: 已刪除 {path}")
            except OSError as exc:
                log_exception("RESET_ALL_FAILED", exc, path=path)

    enforce_production_security()

    mode = get_market_mode()
    MARKET_MODE = mode  # FIX K-17：IDLE 唔再強制轉 HK——下面 wait-out 迴圈會等開市（FORCE 已由 get_market_mode 處理）
    print_startup_banner()

    # 1) delivery stack + signals + health BEFORE anything can produce data
    init_delivery_stack(cfg=CONFIG)
    install_signal_handlers()
    health_server = HealthServer()
    health_server.start()
    health_writer = HealthFileWriter()
    health_writer.start()

    # 2) startup replay of pending batches BEFORE a new crawl (ordering guarantee)
    SENDER.start()
    replay_report = SENDER.replay_pending_blocking()
    lp(f"📦 [啟動重放] {replay_report}")

    if args.replay_only:
        lp("✅ --replay-only 完成，退出")
        graceful_close()
        return 0

    # 3) wait out market closure
    mode = get_market_mode()
    while mode == "IDLE" and not is_shutting_down():
        lp("🛑 休市，等待 60s...")
        for _ in range(60):
            if is_shutting_down():
                graceful_close()
                return 0
            time.sleep(1)
        mode = get_market_mode()
    if is_shutting_down():
        graceful_close()
        return 0
    MARKET_MODE = mode
    RUNTIME.set(market=MARKET_MODE)
    lp(f"🕒 市場: {MARKET_MODE}")

    # 4) device / app
    if u2 is None:
        lp(f"❌ uiautomator2 不可用: {U2_IMPORT_ERROR}")
        log_important("BOOT_ABORT", "uiautomator2 unavailable")
        graceful_close()
        return 2

    docker_recovery()
    if not wait_device_ready(timeout=120, check_interval=2):
        lp("❌ 設備未就緒，結束")
        graceful_close()
        return 3
    device = connect_device()

    if args.reset:
        cache_file = get_round0_cache_file(MARKET_MODE)
        try:
            if os.path.exists(cache_file):
                os.remove(cache_file)
                lp(f"🧹 --reset: 已刪除 {MARKET_MODE} R0 cache: {cache_file}")
        except OSError as exc:
            log_exception("RESET_FAILED", exc, path=cache_file)

    tabs, name_to_symbol, symbol_order, cache_ok = load_round0_cache(MARKET_MODE, reset=args.reset)

    if cache_ok:
        ensure_app_running(device, force_restart=False)
        try:
            btn = device(resourceId=RID_HDR_LIST)
            if btn.exists(timeout=3.0):
                btn.click()
                time.sleep(2)
                if device(resourceId=RID_OPTIONAL_GROUP).exists(timeout=0.0):
                    stop_futu_update_popup_guard()
        except Exception as exc:
            log_exception("ENTER_KLINE_PAGE_FAILED", exc)
    else:
        ensure_app_running(device, force_restart=True)
        tabs, name_to_symbol, symbol_order = round0_collect_name_code_mapping(device)
        if not tabs:
            lp("❌ ROUND0 沒有取得任何 tab，結束")
            graceful_close()
            return 4
        time.sleep(2)
        try:
            btn = device(resourceId=RID_HDR_LIST)
            if btn.exists(timeout=5.0):
                btn.click()
                time.sleep(2.0)
                if device(resourceId=RID_OPTIONAL_GROUP).exists(timeout=0.0):
                    stop_futu_update_popup_guard()
        except Exception as exc:
            log_exception("ENTER_KLINE_PAGE_FAILED", exc)

    # 5) crawl forever
    d_ref = [device]
    _ACTIVE_CRAWLER = Crawler(d_ref, tabs, name_to_symbol, symbol_order,
                              outbox=OUTBOX, sender=SENDER, cfg=CONFIG)
    try:
        _ACTIVE_CRAWLER.run_forever()
    finally:
        watchdog_stop()
        health_writer.stop()
        health_server.stop()
        graceful_close()
    lp("✅ 結束")
    return 0


def main(argv=None):
    global CONFIG, MARKET_MODE
    args = parse_args(argv)

    if args.env_file:
        CONFIG = Config(env_file=args.env_file)
        _apply_config_globals(CONFIG)
        ensure_public_dir()

    # FIX K-23：確定性指令（--version/--self-test/--generate-fixture/print-config）喺下面
    # load_sessions_config() 之前就 return——測試唔再掂日日俾人改嘅 gd_sessions.json。
    if args.version:
        print(f"futu.py {APP_VERSION} ({CONTRACT_ID} rev {CONTRACT_REVISION})")
        return 0
    if args.selftest_shutdown_child:
        return _run_shutdown_child(args.outbox_db, args.ready_file)
    if args.print_config:
        print(json.dumps(CONFIG.public_snapshot(), ensure_ascii=False, indent=2))
        return 0
    if args.generate_fixture:
        target = args.integration_dir or os.path.join(
            os.path.dirname(os.path.abspath(__file__)), "integration")
        generate_fixture(target)
        print(f"integration artifacts written to {target}")
        return 0
    if args.self_test:
        report = run_self_test(only=args.gate, keep_temp=args.keep_temp)
        return 0 if report["failed"] == 0 else 1

    load_sessions_config()  # R87:EXTCFG-BOOT 開機載入外部時間設定（FIX K-23：淨係上倉路徑先載入）
    if args.health_once:
        init_delivery_stack(cfg=CONFIG)
        print(json.dumps(health_snapshot(), ensure_ascii=False, indent=2, default=str))
        graceful_close(timeout_sec=5)
        return 0

    return setup_and_run(args)


if __name__ == "__main__":
    sys.exit(main())
