File size: 23,809 Bytes
c64385b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
# -*- coding: utf-8 -*-
"""整合回波(O-A0059-001)→ 影子模型的雷達特徵:線上取值、存檔重放、Z–R 換算。



★為什麼有這支(2026-09-08):§3.25 用 ASRAD 的三維合成回波證明「回波代替 QPE」是本專案第一個

  過門檻的候選(雷達時代 +0.053;五季 387 個測試日下低層 +0.054、中層另外 +0.007)。

  線上唯一拿得到的雷達量是氣象署每 10 分鐘的**整合回波**(21 層取最大值、0.0125° 格點 dBZ),

  所以影子模型的訓練端用 MREF3D 的整層最大值、線上端用 O-A0059-001,兩邊都經 Z–R(Z=200R^1.6)

  換成 mm/h,再走 `vb_radar.features_at`——**與現行雷達特徵同一支函式、同名(rq3…d_rq20)**。

★★兩端一致的三個鎖:

  ① 框一律裁到 `vb_radar.BOX`(33×41 格)。回波存檔本身是較大的框(wx_echo.BOX),取特徵前必須裁,

     否則靠框邊的站 rq40 會看到訓練沒見過的格點——不會報錯,只會給不同的值。

  ② 時間對齊:訓練用整點;線上退到整點那一張(≤ MAX_LAG_MIN 分),差分用一小時前那張。

  ③ 缺值:dBZ ≤ MISSING_LE 當 NaN → Z–R 給 0(沒回波=沒雨),跟訓練端 wx_mref_check.zr 一樣。

★資料來源與 wx_echo(本機累積器)相同的 historyapi:清單一次、檔案各一次(8.5 MB XML),

  記憶體快取 TTL_SEC;重放走 `data/echo/recent.npz`(部署時從 `_wx_echo_taipei.npz` 切最近 14 天)。

★這是**影子**:機率只寫進帳本與一行小字,使用者看到的仍是現行模型。切換規則見 WEATHER_PLAN §3.26。

"""
import datetime as dt
import os
import re
import threading
import time
from typing import Any, Dict, List, Optional, Tuple

import numpy as np

DATAID = "O-A0059-001"
HIST = "https://opendata.cwa.gov.tw/historyapi/v1"
ARCHIVE = "data/echo/recent.npz"
MISSING_LE = -90.0
TTL_SEC = 600
INDEX_TTL_SEC = 600
MAX_LAG_MIN = 75
PREV_WINDOW_MIN = (45, 80)          # 「一小時前」那張允許的距離
FILE_DEADLINE_SEC = 120.0
TW_TZ = dt.timezone(dt.timedelta(hours=8))
ENABLED = os.getenv("WX_ECHO", "on").lower() != "off"

_TS_FLAT = re.compile(r"(20\d{2})(\d{2})(\d{2})(\d{2})(\d{2})")
_TS_PATH = re.compile(r"/(20\d{2})/(\d{2})/(\d{2})/(\d{2})/(\d{2})(?:/(\d{2}))?")
_INDEX: Dict[str, Any] = {"at": 0.0, "map": {}}
_FRAMES: Dict[str, Tuple[float, Tuple]] = {}
FRAMES_KEEP = 9                     # 裁好的 BOX 小格點留幾張(「一小時前那張」是往回 45–80 分,要夠留到那麼舊)
FULL_KEEP = 3                       # 整張(解析好、還沒裁)留幾張:給晚一步來要同一張的另一邊直接裁
# ★下載一次、兩邊共用(2026-09-23 主人「/rain 等待時間過長」):同一張 8.5 MB 的回波,模型(這支 frame_dbz)
#   跟動圖(vb_qpf.echo_frame)以前各抓各的、各解析一次;/rain 一進來兩條並行,最新那張常常同時下載兩次,
#   背景 keeper 也只幫動圖那邊暖快取,模型每次都自己現抓(連一小時前那張)。現在都走 full_grid():
#   一把鎖一次抓一張、後到的直接用;抓下來順手把模型要的 BOX 裁好放進 _FRAMES。
DL_LOCK = threading.Lock()
_FULL: Dict[str, Tuple[np.ndarray, np.ndarray, np.ndarray]] = {}
_STATUS: Dict[str, Any] = {"last_ok": None, "last_err": "", "n_ok": 0, "n_fail": 0}
_ARC: Dict[str, Any] = {"path": None, "mtime": 0.0, "grids": {}, "dbz": {}}


def _box():
    import vb_radar as RD
    return tuple(RD.BOX)


def zr(dbz: np.ndarray) -> np.ndarray:
    """dBZ → mm/h(Z=200R^1.6);NaN/缺值當 0。跟訓練端 wx_mref_check.zr 同一條式子。"""
    d = np.asarray(dbz, dtype=np.float64)
    fin = np.isfinite(d) & (d > MISSING_LE)
    z = np.power(10.0, np.where(fin, d, -99.0) / 10.0)
    r = np.power(z / 200.0, 1.0 / 1.6)
    r[~fin] = 0.0
    return r.astype(np.float32)


def _mask(s: Any) -> str:
    key = os.getenv("CWA_API_KEY", "").strip()
    t = str(s)
    if key:
        t = t.replace(key, "<KEY>")
    return re.sub(r"Authorization=[^&\s\"']+", "Authorization=<KEY>", t)


def _now_tw() -> dt.datetime:
    return dt.datetime.now(TW_TZ).replace(tzinfo=None)


def _strip_ns(t: str) -> str:
    return t.rsplit("}", 1)[-1]


# ── 解析(原本在 wx_echo,搬來這裡讓線上與累積器共用同一支)──────────────
CROP_TOL = 0.006          # 半格:24.90 存成浮點會略小於 24.90,不留容差會把最南一列切掉(訓練端 wx_mref 同值)


def parse_xml(txt: str, box: Tuple[float, float, float, float], tol: float = 0.0

              ) -> Optional[Tuple[np.ndarray, np.ndarray, np.ndarray]]:
    """`cwaopendata` XML → (lat, lon, dBZ),只留 box 內;認不出規格就回 None(不猜)。

    tol:框邊界的容差。累積器(wx_echo)用 0 維持原本的格點數;影子模型取特徵用 CROP_TOL,跟訓練端一致(33×41)。"""
    full = parse_grid(txt)
    return None if full is None else crop_points(full, box, tol)


def parse_grid(txt: str) -> Optional[Tuple[np.ndarray, np.ndarray, np.ndarray]]:
    """`cwaopendata` XML → 整張 (lat 軸, lon 軸, dBZ[ny, nx]),缺值 NaN;認不出規格回 None。"""
    import xml.etree.ElementTree as ET
    try:
        root = ET.fromstring(txt)
    except Exception:
        return None
    best, bestn = None, 0
    for el in root.iter():
        b = (el.text or "").strip()
        if len(b) < 5000:
            continue
        n = b.count(",") + b.count(" ")
        if n > bestn:
            best, bestn = b, n
    if best is None or bestn < 1000:
        return None
    vals = np.array([float(x) for x in re.split(r"[,\s]+", best) if x], dtype=np.float32)
    tag: Dict[str, str] = {}
    for el in root.iter():
        t = _strip_ns(el.tag)
        b = (el.text or "").strip()
        if b and t not in tag:
            tag[t] = b

    def num(name):
        v = tag.get(name)
        if v is None:
            return None
        m = re.search(r"-?\d+\.?\d*", v)
        return float(m.group()) if m else None

    lo0, la0, res = num("StartPointLongitude"), num("StartPointLatitude"), num("GridResolution")
    nx, ny = num("GridDimensionX"), num("GridDimensionY")
    if None in (lo0, la0, res, nx, ny) or res <= 0:
        return None
    nx, ny = int(nx), int(ny)
    if nx * ny != vals.size:
        return None
    g = vals.reshape(ny, nx)
    g[g <= MISSING_LE] = np.nan
    return la0 + np.arange(ny) * res, lo0 + np.arange(nx) * res, g


def crop_points(full: Tuple[np.ndarray, np.ndarray, np.ndarray], box: Tuple[float, float, float, float],

                tol: float = 0.0) -> Optional[Tuple[np.ndarray, np.ndarray, np.ndarray]]:
    """整張 → 只留 box(±tol)內的點列表 (lat, lon, dBZ);框外回 None。"""
    LA, LO, g = full
    a0, a1, o0, o1 = box
    iy = np.nonzero((LA >= a0 - tol) & (LA <= a1 + tol))[0]
    ix = np.nonzero((LO >= o0 - tol) & (LO <= o1 + tol))[0]
    if not iy.size or not ix.size:
        return None
    sub = g[np.ix_(iy, ix)]
    LAm, LOm = np.meshgrid(LA[iy], LO[ix], indexing="ij")
    return LAm.ravel(), LOm.ravel(), sub.ravel().astype(np.float32)


def parse_time(txt: str) -> Optional[str]:
    """XML 裡的觀測時間 → 'YYYYMMDDHHMM'(台灣時間);找不到回 None。"""
    m = re.search(r"<(?:\w+:)?(?:DateTime|ObsTime|obsTime|dataTime)[^>]*>\s*([0-9T:\-+ ]{12,30})", txt)
    if not m:
        return None
    s = m.group(1).strip()
    try:
        t = dt.datetime.fromisoformat(s.replace("Z", "+00:00"))
    except ValueError:
        return None
    if t.tzinfo is not None:
        t = t.astimezone(TW_TZ).replace(tzinfo=None)
    return t.strftime("%Y%m%d%H%M")


# ── 線上取得 ─────────────────────────────────────────────────────────
def _get(url: str, params: Optional[Dict[str, Any]] = None, get=None):
    """串流讀+牆鐘上限(伺服器滴答式回應會讓 timeout 永遠不觸發,見 wx_echo)。回 (status, bytes)。"""
    import requests
    key = os.getenv("CWA_API_KEY", "").strip()
    p = dict(params or {})
    if "opendata.cwa.gov.tw" in url and "Authorization=" not in url:
        p["Authorization"] = key
    if get is not None:                                   # 測試替身:直接回 (status, bytes)
        return get(url, p)
    r = requests.get(url, params=p, timeout=(8, 30), stream=True,                # ★連線 8 秒:連不上就快點改走 S3(2026-10-07)
                     headers={"User-Agent": "Mozilla/5.0 (compatible; vb-echo/1.0)"})
    t0 = time.time()
    chunks: List[bytes] = []
    try:
        for c in r.iter_content(65536):
            if c:
                chunks.append(c)
            if time.time() - t0 > FILE_DEADLINE_SEC:
                raise TimeoutError("單檔超過 %g 秒" % FILE_DEADLINE_SEC)
    finally:
        r.close()
    return r.status_code, b"".join(chunks)


def _harvest(payload: str) -> Dict[str, str]:
    out: Dict[str, str] = {}
    for u in re.findall(r'"(https?://[^"\s]+)"', payload):
        m = _TS_PATH.search(u)
        if m:
            out["".join(m.groups()[:5])] = u
            continue
        m = _TS_FLAT.search(u)
        if m:
            out["".join(m.groups())] = u
    return out


def index(get=None, now: Optional[float] = None) -> Dict[str, str]:
    """{時間戳(台灣): 下載網址},historyapi 的清單,快取 INDEX_TTL_SEC。"""
    t = now if now is not None else time.time()
    if _INDEX["map"] and t - _INDEX["at"] < INDEX_TTL_SEC:
        return _INDEX["map"]
    # ★端點順序跟 wx_echo 一樣:getMetadata 才給檔案清單(1,440 個網址);getFileList 回的是一頁帶
    #   reCAPTCHA 的 HTML、HTTP 200 但零個網址——「200 但空的」比 404 難查,所以兩個都試、以撈到網址為準。
    err = ""
    for ep in ("getMetadata", "getFileList"):
        try:
            code, body = _get("%s/%s/%s" % (HIST, ep, DATAID), {"limit": 2000}, get)
        except Exception as e:
            err = _mask("%s: %s" % (type(e).__name__, str(e)[:80]))
            continue
        if code != 200:
            err = "清單 %s HTTP %d" % (ep, code)
            continue
        got = _harvest(body.decode("utf-8", "replace"))
        if got:
            _INDEX.update(at=t, map=got)
            return got
        err = "清單 %s 200 但沒有檔案網址" % ep
    _STATUS["last_err"] = err
    return _INDEX["map"]


def frame(ts: str, get=None, now: Optional[float] = None) -> Optional[Tuple]:
    """某個時間戳的 (ts, lat, lon, rain_mm/h)(已裁到 vb_radar.BOX、已 Z–R)。取不到回 None。"""
    g = frame_dbz(ts, get, now)
    return None if g is None else (g[0], g[1], g[2], zr(g[3]))


def frame_dbz(ts: str, get=None, now: Optional[float] = None) -> Optional[Tuple]:
    """同 frame,但值是 **dBZ**(缺值 NaN、還沒 Z–R)——Space 端存檔(vb_frames)存這個原量。"""
    t = now if now is not None else time.time()
    hit = _FRAMES.get(ts)
    if hit and t - hit[0] < TTL_SEC * 6:
        return hit[1]
    full = full_grid(ts, get, t)
    if full is None:
        return None
    hit = _FRAMES.get(ts)                                  # full_grid 剛下載的話已經順手裁好
    if hit and t - hit[0] < TTL_SEC * 6:
        return hit[1]
    return _keep_box(ts, full, t)


def _keep_box(ts: str, full, t: float) -> Optional[Tuple]:
    g = crop_points(full, _box(), CROP_TOL)
    if g is None:
        return None
    out = (ts, g[0], g[1], g[2])
    _FRAMES[ts] = (t, out)
    for k in sorted(_FRAMES)[:-FRAMES_KEEP]:
        _FRAMES.pop(k, None)
    return out


S3_LATEST = "https://cwaopendata.s3.ap-northeast-1.amazonaws.com/Observation/O-A0059-001.json"   # fileapi 轉址去的公開物件(只有最新一張)
LATEST_MIN_S = 120.0
_LATEST: Dict[str, Any] = {"tried": 0.0, "ts": None}


def parse_json_grid(doc: Dict[str, Any]) -> Optional[Tuple[str, Tuple[np.ndarray, np.ndarray, np.ndarray]]]:
    """fileapi/S3 的 JSON(跟 XML 同一份規格:parameterSet + 逗號分隔的 content)→ (時間戳 台灣, (lat 軸, lon 軸, dBZ))。認不出回 None。"""
    try:
        ds = doc["cwaopendata"]["dataset"]
        ps = ds["datasetInfo"]["parameterSet"]
        lo0, la0, res = float(ps["StartPointLongitude"]), float(ps["StartPointLatitude"]), float(ps["GridResolution"])
        nx, ny = int(ps["GridDimensionX"]), int(ps["GridDimensionY"])
        when = str(ps["DateTime"])
        content = str(ds["contents"]["content"])
    except (KeyError, TypeError, ValueError):
        return None
    try:
        vals = np.array([float(x) for x in re.split(r"[,\s]+", content.strip()) if x], dtype=np.float32)
    except ValueError:
        return None
    if vals.size != nx * ny or res <= 0:
        return None
    g = vals.reshape(ny, nx)
    g[g <= MISSING_LE] = np.nan
    try:
        t = dt.datetime.fromisoformat(when.replace("Z", "+00:00"))
    except ValueError:
        return None
    if t.tzinfo is not None:
        t = t.astimezone(TW_TZ).replace(tzinfo=None)
    return t.strftime("%Y%m%d%H%M"), (la0 + np.arange(ny) * res, lo0 + np.arange(nx) * res, g)


def latest_fallback(get=None, now: Optional[float] = None) -> Optional[Tuple[str, Tuple[np.ndarray, np.ndarray, np.ndarray]]]:
    """★2026-10-07 historyapi(opendata.cwa.gov.tw)連不上時:S3 公開桶上的最新一張(JSON,8.9 MB),跟 fileapi 給的是同一個檔。

    兩分鐘內不重抓;回 (時間戳, 整張) 並進 _FULL/_FRAMES,之後 full_grid(那個時間戳) 直接命中。"""
    t = now if now is not None else time.time()
    if t - _LATEST["tried"] < LATEST_MIN_S:
        ts = _LATEST["ts"]
        return (ts, _FULL[ts]) if ts and ts in _FULL else None
    _LATEST["tried"] = t
    try:
        if get is not None:
            code, body = get(S3_LATEST, None)
        else:
            import requests
            r = requests.get(S3_LATEST, timeout=(8, 90), headers={"User-Agent": "Mozilla/5.0 (compatible; vb-echo/1.0)"})
            code, body = r.status_code, r.content
        if code != 200:
            raise RuntimeError("S3 HTTP %d" % code)
        import json
        got = parse_json_grid(json.loads(body.decode("utf-8", "ignore")))
    except Exception as e:
        _STATUS["last_err"] = _mask("S3 最新一張 %s: %s" % (type(e).__name__, str(e)[:80]))
        _STATUS["n_fail"] += 1
        return None
    if got is None:
        _STATUS["last_err"] = "S3 JSON 認不出規格"
        _STATUS["n_fail"] += 1
        return None
    ts, full = got
    _FULL[ts] = full                                   # ★不拿 DL_LOCK:full_grid 在鎖裡也會叫到這裡(Lock 不可重入)
    for k in sorted(_FULL)[:-FULL_KEEP]:
        _FULL.pop(k, None)
    try:
        _keep_box(ts, full, t)
    except Exception:
        pass
    _LATEST["ts"] = ts
    _STATUS.update(last_ok=ts, n_ok=_STATUS["n_ok"] + 1, s3=_STATUS.get("s3", 0) + 1)
    return ts, full


def full_grid(ts: str, get=None, now: Optional[float] = None) -> Optional[Tuple[np.ndarray, np.ndarray, np.ndarray]]:
    """某個時間戳的整張回波(dBZ、缺值 NaN):模型(frame_dbz)與動圖(vb_qpf.echo_frame)共用的下載+解析。

    一次只抓一張(DL_LOCK);別人正在抓同一張就等它、抓好直接用。抓到時順手把模型要的 BOX 裁進 _FRAMES。

    historyapi 沒有這張、或抓不到 → 看 S3 的最新一張是不是剛好這個時間戳(latest_fallback)。"""
    hit = _FULL.get(ts)
    if hit is not None:
        return hit

    def _fb():
        fb = latest_fallback(get, now)
        return fb[1] if (fb and fb[0] == ts) else None
    with DL_LOCK:
        hit = _FULL.get(ts)
        if hit is not None:
            return hit
        t = now if now is not None else time.time()
        url = index(get, t).get(ts)
    if not url:
        return _fb()
    with DL_LOCK:
        hit = _FULL.get(ts)
        if hit is not None:
            return hit
        try:
            code, body = _get(url, None, get)
        except Exception as e:
            _STATUS["last_err"] = _mask("%s: %s" % (type(e).__name__, str(e)[:80]))
            _STATUS["n_fail"] += 1
            code, body = None, b""
        if code != 200:
            if code is not None:
                _STATUS["last_err"] = "檔案 HTTP %d" % code
                _STATUS["n_fail"] += 1
            return None if code == 404 else _fb_outside(get, now, ts)
        full = parse_grid(body.decode("utf-8", "ignore"))
        if full is None:
            _STATUS["last_err"] = "XML 認不出規格"
            _STATUS["n_fail"] += 1
            return None
        _FULL[ts] = full
        for k in sorted(_FULL)[:-FULL_KEEP]:
            _FULL.pop(k, None)
        _STATUS.update(last_ok=ts, n_ok=_STATUS["n_ok"] + 1)
        try:
            _keep_box(ts, full, t)
        except Exception:
            pass
        return full


def _fb_outside(get, now, ts):
    """historyapi 那張抓不到 → S3 的最新一張是不是剛好這個時間戳(latest_fallback 不拿 DL_LOCK,在鎖裡叫也行)。"""
    fb = latest_fallback(get, now)
    return fb[1] if (fb and fb[0] == ts) else None


def _nearest_ts(keys: List[str], target: dt.datetime, lo_min: int, hi_min: int) -> Optional[str]:
    """target 往回 lo_min~hi_min 分鐘內最接近 target 的時間戳。"""
    best, bestd = None, None
    for k in keys:
        try:
            tk = dt.datetime.strptime(k, "%Y%m%d%H%M")
        except ValueError:
            continue
        d = (target - tk).total_seconds() / 60.0
        if lo_min <= d <= hi_min and (bestd is None or d < bestd):
            best, bestd = k, d
    return best


def live_features(lat: float, lon: float, now: Optional[dt.datetime] = None, get=None

                  ) -> Optional[Dict[str, Optional[float]]]:
    """線上:最近一張整合回波(≤ MAX_LAG_MIN 分)+ 一小時前那張 → rq*/d_rq*(回波版)。抓不到回 None。"""
    if not ENABLED:
        return None
    import vb_radar as RD
    t0 = now or _now_tw()
    keys = sorted(set(index(get)) | set(_FULL) | set(_FRAMES))
    if not keys or _nearest_ts(keys, t0, 0, MAX_LAG_MIN) is None:      # historyapi 連不上(清單空或都太舊)→ S3 最新一張
        fb = latest_fallback(get)
        if fb:
            keys = sorted(set(keys) | {fb[0]})
    if not keys:
        return None
    k0 = _nearest_ts(keys, t0, 0, MAX_LAG_MIN)
    if k0 is None:
        return None
    g = frame(k0, get)
    if g is None:
        return None
    tk = dt.datetime.strptime(k0, "%Y%m%d%H%M")
    kp = _nearest_ts(keys, tk, PREV_WINDOW_MIN[0], PREV_WINDOW_MIN[1])
    gp = frame(kp, get) if kp else None
    return RD.features_at(g, gp, lat, lon)


# ── 存檔重放(帳本用) ───────────────────────────────────────────────
def load_archive(path: Optional[str] = None, raw: bool = False) -> Dict[str, Tuple]:
    """`data/echo/recent.npz`(lat/lon/ts/val,dBZ)→ {ts: (ts, lat, lon, rain)};裁到 vb_radar.BOX。

    raw=True 給 dBZ(NaN 缺值)而不是 Z–R 後的雨強——Space 端存檔灌種用。"""
    p = path or os.environ.get("VB_ECHO_ARCHIVE", ARCHIVE)
    try:
        mt = os.path.getmtime(p)
    except OSError:
        return {}
    if not (_ARC["path"] == p and _ARC["mtime"] == mt):
        z = np.load(p)
        la, lo, ts, va = z["lat"], z["lon"], z["ts"], z["val"]
        a0, a1, o0, o1 = _box()
        m = (la >= a0 - CROP_TOL) & (la <= a1 + CROP_TOL) & (lo >= o0 - CROP_TOL) & (lo <= o1 + CROP_TOL)
        dbz = {}
        for i, t in enumerate(ts):
            v = va[i][m].astype(np.float32)
            v[v <= MISSING_LE] = np.nan
            dbz[str(t)] = (str(t), la[m], lo[m], v)
        grids = {k: (k, g[1], g[2], zr(g[3])) for k, g in dbz.items()}
        _ARC.update(path=p, mtime=mt, grids=grids, dbz=dbz)
    return _ARC["dbz"] if raw else _ARC["grids"]


def _sb_frame(ts: str) -> Optional[Tuple]:
    """靜態存檔沒那格時,看 Space 自己存進 Supabase 的(vb_frames,存 dBZ)。沒設/沒有/讀不到 → None。"""
    try:
        import vb_frames as FR
        g = FR.get("echo", ts)
    except Exception:
        return None
    return None if g is None else (g[0], g[1], g[2], zr(g[3]))


def archive_features(lat: float, lon: float, t: dt.datetime, path: Optional[str] = None

                     ) -> Dict[str, Optional[float]]:
    """重放:t 那個整點(台灣時間)的回波版雷達特徵;存檔沒那格回 {}(呼叫端當缺值,不能改叫 live)。

    ★來源順序:部署帶上來的靜態檔 → Space 自己存進 Supabase 的逐時存檔(vb_frames)。兩邊同框同量。"""
    import vb_radar as RD
    grids = load_archive(path)
    tt = t.astimezone(TW_TZ).replace(tzinfo=None) if t.tzinfo else t
    t0 = tt.replace(minute=0, second=0, microsecond=0)
    k0, k1 = t0.strftime("%Y%m%d%H%M"), (t0 - dt.timedelta(hours=1)).strftime("%Y%m%d%H%M")
    g = grids.get(k0) or _sb_frame(k0)
    if g is None:
        return {}
    gp = grids.get(k1) or _sb_frame(k1)
    return RD.features_at(g, gp, lat, lon)


def export_recent(src: str, dst: str, days: float = 14.0, now: Optional[dt.datetime] = None) -> int:
    """把本機的 `_wx_echo_taipei.npz` 切最近 days 天(仍存 dBZ、原框;讀的時候才裁與 Z–R)。回筆數。"""
    try:
        z = np.load(src)
    except OSError:
        return 0
    ts = z["ts"]
    cut = ((now or _now_tw()) - dt.timedelta(days=days)).strftime("%Y%m%d%H%M")
    keep = np.array([str(t) >= cut for t in ts])
    n = int(keep.sum())
    if n == 0:
        return 0
    os.makedirs(os.path.dirname(dst) or ".", exist_ok=True)
    np.savez_compressed(dst, lat=z["lat"], lon=z["lon"], ts=ts[keep], val=z["val"][keep])
    return n


def line(path: Optional[str] = None) -> str:
    """/health 一行:影子模型有沒有載入、回波存檔到哪、線上抓取的狀態。"""
    model = "有" if os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), "wx_model_h1echo.json")) else "無"
    grids = load_archive(path)
    newest = max(grids) if grids else "無"
    st = _STATUS
    try:
        import vb_nowcast as N
        role = "回波版模型(主數字;WX_PRIMARY=qpe 可換回)" if N.PRIMARY == "echo" else "影子模型(回波版)"
    except Exception:
        role = "回波版模型"
    return ("%s:模型檔 %s;回波存檔 %d 格、最新 %s;線上抓取 成功 %d 失敗 %d、最近成功 %s%s"
            % (role, model, len(grids), newest, st["n_ok"], st["n_fail"], st["last_ok"] or "無",
               (";最近錯誤 " + st["last_err"]) if st["last_err"] else ""))


def reset() -> None:
    _INDEX.update(at=0.0, map={})
    _FRAMES.clear()
    _FULL.clear()
    _STATUS.update(last_ok=None, last_err="", n_ok=0, n_fail=0)
    _ARC.update(path=None, mtime=0.0, grids={}, dbz={})