# version v20261113
# pip install websockets msgpack zstandard psutil
# 用法：python client_demo.py（启动） / python client_demo.py --help（查看配置说明）
import asyncio, hashlib, json, random, os, re, ssl, sys, time, threading, struct
from datetime import datetime

# 第三方依赖：缺失时给出安装提示（不影响 --help 查看说明）
try:
    import websockets, msgpack
    import zstandard as zstd
    import psutil
except ImportError as _import_error:
    _MISSING_DEPENDENCY = _import_error
else:
    _MISSING_DEPENDENCY = None

if sys.stdout and hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if sys.stderr and hasattr(sys.stderr, "reconfigure"):
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")

# ==================== ① 配置区（改这里就够了）====================
# ① 鉴权
AUTH_KEY = "你的key"

# ② 服务器（地址解析：启动时先查 /realtime/ws-endpoint，失败/超时回落 WS_URI）
domain = "zhunData.cn"
WS_URI = f"wss://{domain}/ws/"
# WS_ENDPOINT_URL 可用环境变量覆盖（便于联调）
WS_ENDPOINT_URL = os.environ.get("WS_ENDPOINT_URL") or f"https://{domain}/api/v1/realtime/ws-endpoint"
WS_ENDPOINT_TIMEOUT = 3

# ③ 订阅列表（按需增删）
SUBSCRIBE_CHANNEL = "market_quote"
SUBSCRIBE_SYMBOLS = [
    "tick.stock.sz.000001",
    "tick.stock.sh.600744",
]

# ④ 客户端标识
CLIENT_VERSION = "v20261113"
# 版本号格式 vYYYYMMDD；服务端据此判断是否需要提示升级（版本过低会被拒绝，关闭码 4006）
CLIENT_CAP = "qb2"  # 下行整批压缩：带 cap=qb2 时服务端发 QB2（省约一半下行流量）；置 "" 回退明文 QB1

# ⑤ 网络与重连（秒）
RECONNECT_MIN = 1  # 最小重连等待time（秒）
RECONNECT_MAX = 3  # 最大重连等待time（秒）

# ⑥ 输出与文件
CLIENT_MEMORY_LOG_FILE = "client_memory_monitor.log"
CLIENT_TICK_SIZE_LOG_FILE = "client_tick_data_size.log"
# ==============================================================


# ==================== ② 协议 / 编解码（zstd 字典 / msgpack / QH1·QB1·QB2）====================
# 客户端本地字典目录：不存在就创建，再向服务端请求
CLIENT_DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ws_client_data")
DICT_MAGIC = b"QD1"
dctx = None


def _latest_local_dict(path_dir):
    if not os.path.isdir(path_dir):
        return None
    pattern = re.compile(r"^tick_dict_v(\d+)\.zdict$")
    best = None
    best_version = -1
    for name in os.listdir(path_dir):
        match = pattern.match(name)
        if not match:
            continue
        version = int(match.group(1))
        if version > best_version:
            best_version = version
            best = os.path.join(path_dir, name)
    return best


def _load_local_dict(path):
    with open(path, "rb") as fh:
        raw = fh.read()
    data = zstd.ZstdCompressionDict(raw)
    return data, raw


# ---- 行情帧解码：QB1(批量) / QH1(单条) / 旧格式兼容 ----
_MAGIC_MSG = b"QH1"
_MAGIC_BATCH = b"QB1"
_MAGIC_BATCH_Z = b"QB2"
_TYPE_NAMES = {1: "market_quote", 2: "limit_alert"}


def decode_ws_frame(frame, dctx):
    """把服务端下发的二进制帧解成 [{type, key, data}, ...]。"""
    if isinstance(frame, str):
        return []
    if frame[:3] == _MAGIC_BATCH_Z:
        # 服务端下行整批压缩帧：先解外层 zstd，再按 QB1 解析
        raw_len = struct.unpack(">I", frame[3:7])[0]
        frame = zstd.ZstdDecompressor().decompress(frame[7:], max_output_size=raw_len)
    if frame[:3] == _MAGIC_BATCH:
        count = struct.unpack(">H", frame[3:5])[0]
        pos = 5
        envelopes = []
        for _ in range(count):
            length = struct.unpack(">I", frame[pos:pos + 4])[0]
            pos += 4
            envelopes.append(frame[pos:pos + length])
            pos += length
    elif frame[:3] == _MAGIC_MSG:
        envelopes = [frame]
    else:
        # 旧格式：zstd(msgpack({type, key, data}))，兼容旧版服务端
        raw = dctx.decompress(frame)
        result = msgpack.unpackb(raw, raw=False)
        return result if isinstance(result, list) else [result]

    payloads = []
    for env in envelopes:
        type_code = env[3]
        key_len = struct.unpack(">H", env[4:6])[0]
        key = env[6:6 + key_len].decode("utf-8")
        data = msgpack.unpackb(dctx.decompress(env[6 + key_len:]), raw=False)
        payloads.append({"type": _TYPE_NAMES.get(type_code, "market_quote"),
                         "key": key, "data": data})
    return payloads


# ---- 字典协议：本地版本上报 / 缺失或版本不一致时下载 ----
async def ensure_dictionary(ws):
    """本地有字典就报版本；缺失或与服务端不一致则下载最新字典。"""
    global dctx
    os.makedirs(CLIENT_DATA_DIR, exist_ok=True)
    local_path = _latest_local_dict(CLIENT_DATA_DIR)
    local_version = 0
    local_dict_id = 0
    local_data = None
    if local_path:
        try:
            local_data, _ = _load_local_dict(local_path)
            local_dict_id = local_data.dict_id()
            local_version = int(os.path.basename(local_path)[len("tick_dict_v"):-len(".zdict")])
        except Exception as error:
            print(f"[Demo Client] local dict invalid, will download: {error}")
            local_path = None
            local_data = None
            local_version = 0
            local_dict_id = 0

    print(f"[Demo Client] local dict version={local_version} id={local_dict_id} path={local_path}")
    await ws.send(json.dumps({
        "action": "dict_info",
        "version": local_version,
        "dict_id": local_dict_id,
    }))

    info = None
    while True:
        msg = await ws.recv()
        if isinstance(msg, str):
            data = json.loads(msg)
            if data.get("type") == "dict_info":
                info = data
                break
            _handle_text_message(data)

    if not info.get("available"):
        raise RuntimeError("服务端没有可用字典: %s" % info.get("msg"))

    server_version = int(info["version"])
    server_dict_id = int(info["dict_id"])
    server_size = int(info["size"])
    server_sha = info.get("sha256")

    if info.get("match") and local_path and local_data is not None:
        dctx = zstd.ZstdDecompressor(dict_data=local_data)
        print(f"[Demo Client] dict match, reuse local version={local_version} id={local_dict_id}")
        return

    print(f"[Demo Client] download required: local={local_version}/{local_dict_id} server={server_version}/{server_dict_id}")
    await ws.send(json.dumps({"action": "dict_download"}))

    raw = None
    while True:
        msg = await ws.recv()
        if isinstance(msg, str):
            data = json.loads(msg)
            if data.get("type") == "dict_download":
                if data.get("ok") is False:
                    raise RuntimeError("字典下载失败: %s" % data.get("msg"))
            else:
                _handle_text_message(data)
            continue
        if isinstance(msg, (bytes, bytearray)) and msg[:3] == DICT_MAGIC:
            if len(msg) < 7:
                raise RuntimeError("字典帧太短")
            version = struct.unpack(">I", msg[3:7])[0]
            body = bytes(msg[7:])
            if version != server_version:
                raise RuntimeError("字典版本不一致: frame=%s expected=%s" % (version, server_version))
            if len(body) != server_size:
                raise RuntimeError("字典大小不一致: frame=%s expected=%s" % (len(body), server_size))
            if server_sha and hashlib.sha256(body).hexdigest() != server_sha:
                raise RuntimeError("字典 SHA256 校验失败")
            raw = body
            break

    if raw is None:
        raise RuntimeError("没有收到字典数据")

    target = os.path.join(CLIENT_DATA_DIR, "tick_dict_v%d.zdict" % server_version)
    tmp = target + ".tmp"
    with open(tmp, "wb") as fh:
        fh.write(raw)
    os.replace(tmp, target)
    # 只保留服务端当前版本，避免本地旧的高版本导致反复下载
    pattern = re.compile(r"^tick_dict_v\d+\.zdict$")
    for name in os.listdir(CLIENT_DATA_DIR):
        old_path = os.path.join(CLIENT_DATA_DIR, name)
        if pattern.match(name) and os.path.abspath(old_path) != os.path.abspath(target):
            try:
                os.remove(old_path)
            except Exception:
                pass
    loaded, _ = _load_local_dict(target)
    if loaded.dict_id() != server_dict_id:
        raise RuntimeError("下载字典 dict_id 不一致")
    dctx = zstd.ZstdDecompressor(dict_data=loaded)
    print(f"[Demo Client] downloaded version={server_version} id={server_dict_id} bytes={len(raw)} path={target}")


# ==================== ③ 网络层（地址解析 / 连接 / 重连 / 心跳）====================
def resolve_ws_uri():
    """查询 ws-endpoint；成功返回 (url, node, node_name)，失败返回 (WS_URI, None, None)。"""
    import urllib.parse
    import urllib.request

    query = urllib.parse.urlencode({"key": AUTH_KEY})
    try:
        req = urllib.request.Request(
            f"{WS_ENDPOINT_URL}?{query}",
            headers={"User-Agent": f"zhun-ws-client/{CLIENT_VERSION}"},
        )
        with urllib.request.urlopen(req, timeout=WS_ENDPOINT_TIMEOUT) as resp:
            payload = json.loads(resp.read().decode("utf-8"))
        data = (payload or {}).get("data") or {}
        url = data.get("url")
        if url:
            node = data.get("node")
            node_name = data.get("node_name") or node
            fallback = data.get("fallback")
            # 节点编码属于服务端内部信息，客户端日志只显示最终接入地址
            print(f"[*] 已获取接入地址: {url}")
            return url, node, node_name
        print(f"[!] ws-endpoint 返回无 url，回落默认 {WS_URI}")
    except Exception as exc:
        print(f"[!] ws-endpoint 查询失败（{exc}），回落默认 {WS_URI}")
    return WS_URI, None, None


async def run_client():
    """带自动重连机制的主客户端循环"""
    monitor_task = asyncio.create_task(memory_monitor())
    size_monitor_task = asyncio.create_task(tick_data_size_monitor())

    while True:
        try:
            # 先问服务端该连哪台（失败自动回落默认地址），再做鉴权连接
            base_uri, _node, _node_name = resolve_ws_uri()
            print(f"[*] Connecting to WebSocket server: {base_uri} ...")

            # 通过 URL 参数传递鉴权 Key
            ws_uri = f"{base_uri}?key={AUTH_KEY}&version={CLIENT_VERSION}"
            if CLIENT_CAP:
                ws_uri += f"&cap={CLIENT_CAP}"

            _ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
            _ssl_ctx.check_hostname = False
            _ssl_ctx.verify_mode = ssl.CERT_NONE

            async with websockets.connect(ws_uri, ssl=_ssl_ctx) as ws:
                print("[+] Connected!")
                await ensure_dictionary(ws)
                await subscribe_client(ws)
                await receive_data(ws)

        except (
                websockets.ConnectionClosed,
                ConnectionRefusedError,
                OSError,
                asyncio.TimeoutError
        ) as e:
            print(f"[!] Connection closed or error: {e}")
            if hasattr(e, 'code') and e.code in (4003, 4001, 4009):
                print(f"[!] Auth rejected (code={e.code}), not reconnecting")
                return
            wait_time = random.randint(RECONNECT_MIN, RECONNECT_MAX)
            print(f"[*] 将在 {wait_time} s before reconnecting...")
            await asyncio.sleep(wait_time)

        except Exception as e:
            print(f"[Fatal Error] Unknown error: {e}")
            await asyncio.sleep(RECONNECT_MAX)


# ==================== ④ 业务处理（消息分发 / 统计 / 日志）====================
_recv_size_lock = threading.Lock()
_recv_size_hourly_bytes = 0
_recv_size_trading_bytes = 0
_current_hour = -1
_trading_day = None


async def memory_monitor():
    """
    异步内存监控协程：每隔 60 秒将客户端内存占用写入日志文件
    """
    process = psutil.Process(os.getpid())
    while True:
        await asyncio.sleep(60)
        try:
            mem_mb = process.memory_info().rss / 1024 / 1024
            log_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

            log_msg = f"[{log_time}] Client RSS Memory: {mem_mb:.2f} MB\n"

            # 追加写入到日志文件
            with open(CLIENT_MEMORY_LOG_FILE, "a", encoding="utf-8") as f:
                f.write(log_msg)

        except Exception as e:
            print(f"[Client Monitor Error] {e}")


async def tick_data_size_monitor():
    global _recv_size_hourly_bytes, _recv_size_trading_bytes, _current_hour, _trading_day

    while True:
        await asyncio.sleep(60)
        try:
            now = datetime.now()
            hour = now.hour
            today = now.date()

            with _recv_size_lock:
                hourly_bytes = _recv_size_hourly_bytes
                trading_bytes = _recv_size_trading_bytes

            log_time = now.strftime('%Y-%m-%d %H:%M:%S')

            if hour != _current_hour and _current_hour != -1:
                with _recv_size_lock:
                    _recv_size_hourly_bytes = 0
                hourly_mb = hourly_bytes / 1024 / 1024
                log_msg = f"[{log_time}] 上一h Tick 数据接收量: {hourly_mb:.2f} MB ({hourly_bytes} bytes)\n"
                with open(CLIENT_TICK_SIZE_LOG_FILE, "a", encoding="utf-8") as f:
                    f.write(log_msg)

            _current_hour = hour

            if 9 <= hour <= 15:
                if today != _trading_day:
                    if _trading_day is not None:
                        with _recv_size_lock:
                            _recv_size_trading_bytes = 0
                        trading_mb = trading_bytes / 1024 / 1024
                        log_msg = f"[{log_time}] 上一交易日(9-15点) Tick 数据接收量: {trading_mb:.2f} MB ({trading_bytes} bytes)\n"
                        with open(CLIENT_TICK_SIZE_LOG_FILE, "a", encoding="utf-8") as f:
                            f.write(log_msg)
                    _trading_day = today
            else:
                if _trading_day is not None and today != _trading_day:
                    with _recv_size_lock:
                        _recv_size_trading_bytes = 0
                    trading_mb = trading_bytes / 1024 / 1024
                    log_msg = f"[{log_time}] 上一交易日(9-15点) Tick 数据接收量: {trading_mb:.2f} MB ({trading_bytes} bytes)\n"
                    with open(CLIENT_TICK_SIZE_LOG_FILE, "a", encoding="utf-8") as f:
                        f.write(log_msg)
                    _trading_day = None

        except Exception as e:
            print(f"[Client Tick Size Monitor Error] {e}")


async def subscribe_client(ws):
    """
    封装订阅逻辑，方便在每次重连成功后重新执行
    """
    # 订阅 Market quote（symbols 来自顶部配置区 SUBSCRIBE_SYMBOLS）
    sub_quote_msg = {
        "action": "subscribe",
        "channel": SUBSCRIBE_CHANNEL,
        "symbols": list(SUBSCRIBE_SYMBOLS),
    }
    await ws.send(json.dumps(sub_quote_msg))
    # 连接后服务端可能先推 notice，再回 subscribe_ok；
    # 这里循环读到 subscribe_ok 为止，其他文本按正常消息处理，避免把通知当成订阅确认。
    while True:
        response = await ws.recv()
        if not isinstance(response, str):
            print(f"[*] Server confirmed: {response}")
            break
        try:
            data = json.loads(response)
        except Exception:
            print(f"[*] Server confirmed: {response}")
            break
        if data.get("type") == "subscribe_ok":
            print(f"[*] Server confirmed: {response}")
            break
        _handle_text_message(data)


def _handle_text_message(text_data: dict):
    msg_type = text_data.get("type", "unknown")
    if msg_type == "key_expiring_soon":
        print(f"⚠️ [续订提醒] Key expiring soon | days_remaining: {text_data.get('days_remaining')} | expired_at: {text_data.get('expired_at')}")
    elif msg_type == "key_expired_warning":
        print(f"⚠️ [过期警告] Key expired | grace_remaining: {text_data.get('grace_hours_remaining')}h | expired_at: {text_data.get('expired_at')}")
    elif msg_type == "key_expired_disconnect":
        print(f"🚫 [断开连接] Key expired timeout, server disconnecting | {text_data.get('msg')}")
    elif msg_type == "subscribe_ok":
        print(f"✅ [Subscribe OK] channel: {text_data.get('channel')} | symbol: {text_data.get('symbols')}")
    elif msg_type == "subscribe_rejected":
        print(f"❌ [Subscribe rejected] {text_data.get('msg')}")
    elif msg_type == "error":
        print(f"❌ [Server error] {text_data.get('msg')}")
    elif msg_type == "notice":
        if text_data.get("category") == "client_update":
            print(f"📢 [客户端更新] 最新版本 {text_data.get('latest_version')} | "
                  f"{text_data.get('msg')}")
        else:
            print(f"📢 [通知] {text_data.get('msg')}")
    else:
        print(f"📩 [Text message] {text_data}")


def _handle_binary_message(tick_data: dict):

    msg_type = tick_data.get("type", "unknown")
    code = tick_data.get("key", "N/A")
    data = tick_data.get("data", "N/A")
    if msg_type == "limit_alert":
        print(f"🚨 [Limit-up alert] symbol: {code} | 数据: {tick_data}")
    elif msg_type == "market_quote":

        tick_time = data.get('time')
        datetime_str = None
        if tick_time:
            datetime_str = datetime.fromtimestamp(tick_time / 1000)

        print(f"📈 [Market quote] symbol: {code} | time: {datetime_str} {data}")
    else:
        pass


async def receive_data(ws):
    """
    封装数据接收与解压逻辑
    """
    global _recv_size_hourly_bytes, _recv_size_trading_bytes

    async for message in ws:
        try:
            if isinstance(message, str):
                _handle_text_message(json.loads(message))
                continue

            # print(f"[Debug] Received binary message length: {len(message)} bytes, {message}")

            msg_size = len(message)
            for payload in decode_ws_frame(message, dctx):
                _handle_binary_message(payload)

            with _recv_size_lock:
                _recv_size_hourly_bytes += msg_size
                now_hour = datetime.now().hour
                if 9 <= now_hour <= 15:
                    _recv_size_trading_bytes += msg_size

        except Exception as e:
            print(f"[Error] 解压或解析数据failed: {e}")


# ==================== ⑤ 主入口 main() ====================
def print_help():
    """打印使用说明：python client_demo.py --help"""
    print(
        f"""
实时行情 WebSocket 客户端示例（{CLIENT_VERSION}）

用法
    python client_demo.py           启动客户端：连接 → 自动同步字典 → 订阅 → 接收行情
    python client_demo.py --help    显示本说明

运行前只需修改文件顶部「配置区」
    AUTH_KEY          ① 你的 Key，由客服分配
    SUBSCRIBE_CHANNEL ② 订阅频道：market_quote（行情）/ limit_alert（涨停预警）
    SUBSCRIBE_SYMBOLS ③ 订阅标的列表，格式 tick.{{asset_type}}.{{suffix}}.{{code}}
                         asset_type：stock / index / fund / bond
                         suffix    ：sz / sh / bj / *
                         例：tick.stock.sz.000001、tick.stock.sh.600744、
                             tick.stock.*（通配所有股票，需对应权限）
    CLIENT_VERSION    ④ 客户端版本，保持 {CLIENT_VERSION} 即可
    CLIENT_CAP        ⑤ 保持 qb2：自动压缩，下行流量约减半
    服务器地址无需修改：客户端启动时会先向服务端获取接入地址，
                        取不到时自动回落到默认地址

依赖安装
    pip install websockets msgpack zstandard psutil

版本要求
    当前最低版本 v20261103，2026-11-21 起要求 v20261113；
    版本过低会被拒绝连接（关闭码 4006）。
    最新客户端下载：https://zhundata.cn/ws-realtime-quote.html
    客服 QQ：657688959（添加时备注：实时推送）
"""
    )


def main():
    # --help / -h：只打印说明，不启动连接
    if any(arg in ("-h", "--help") for arg in sys.argv[1:]):
        print_help()
        return
    if _MISSING_DEPENDENCY is not None:
        print(f"[!] 缺少依赖：{_MISSING_DEPENDENCY}")
        print("    请先安装：pip install websockets msgpack zstandard psutil")
        return
    try:
        # 【核心新增】每次启动客户端时，清空旧的日志文件，方便观察本次运行的数据
        if os.path.exists(CLIENT_MEMORY_LOG_FILE):
            os.remove(CLIENT_MEMORY_LOG_FILE)
            print(f"[*] Cleared old client memory log: {CLIENT_MEMORY_LOG_FILE}")

        if os.path.exists(CLIENT_TICK_SIZE_LOG_FILE):
            os.remove(CLIENT_TICK_SIZE_LOG_FILE)
            print(f"[*] Cleared old client tick size log: {CLIENT_TICK_SIZE_LOG_FILE}")

        asyncio.run(run_client())
    except KeyboardInterrupt:
        print("\n[*] Client exited manually.")


if __name__ == "__main__":
    main()
