#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""check_dis_batch.py —— 查 Dis-db 里昨日(09-24)新增各站的实际回填状态"""
import json
import subprocess

DB = "22e399b8-3c5b-80f5-b6dc-c6d96cafa1bd"
TOKENS = [
    "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",   # 参考里的 Dis-db 旧 key
    "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",   # Hermes Memory token
]
DOMAINS = ["qdndz.gov.cn", "yingquan.gov.cn", "jcx.gov.cn",
           "binyang.gov.cn", "dazu.gov.cn", "ahqy.gov.cn", "jinyun.gov.cn"]


def api(tok, url, method="GET", body=None):
    cmd = ["curl", "-sS", "-X", method, "-H", "Authorization: Bearer " + tok,
           "-H", "Notion-Version: 2022-06-28", "-H", "Content-Type: application/json",
           "--max-time", "60", url]
    if body is not None:
        cmd += ["-d", json.dumps(body, ensure_ascii=False)]
    p = subprocess.run(cmd, capture_output=True, timeout=90)
    try:
        return json.loads(p.stdout.decode("utf-8", "ignore"))
    except Exception:
        return {"_raw": p.stdout.decode("utf-8", "ignore")[:200]}


tok = None
for t in TOKENS:
    r = api(t, "https://api.notion.com/v1/databases/%s" % DB)
    ok = "properties" in r
    print("token %s… → %s" % (t[4:12], "✅ 可访问" if ok else "❌ " + str(r.get("code") or r.get("_raw", ""))[:60]))
    if ok and tok is None:
        tok = t
        print("   列:", list(r["properties"].keys()))
if not tok:
    raise SystemExit("两个 token 都不通")

for d in DOMAINS:
    r = api(tok, "https://api.notion.com/v1/databases/%s/query" % DB, "POST",
            {"filter": {"property": "Url", "url": {"contains": d}}, "page_size": 100})
    rows = r.get("results", [])
    print("\n=== %s → %d 条 ===" % (d, len(rows)))
    for pg in rows:
        pr = pg["properties"]

        def txt(k):
            v = pr.get(k) or {}
            t = v.get("rich_text") or v.get("title") or []
            return "".join(x.get("plain_text", "") for x in t).strip()
        url = (pr.get("Url") or {}).get("url") or ""
        num = (pr.get("配置编号") or {}).get("number")
        print("   %-14s | Script_name=%-28s | 编号=%-6s | 备注=%s" % (
            txt("站点名")[:14] or "(无)", txt("Script_name") or "❌空", str(num), txt("备注")[:12]))
        if not rows:
            print("   （Dis-db 里没有该域名的记录）")
