#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""recheck_reenable.py —— 实跑验证 3 条已恢复站点，通过则开回来"""
import json, os, re, shutil, subprocess, datetime, time
D = "/root/gov_crawler/"; CFG = D + "daily_crawl_config.json"
T = ["crawl_baohuahb.py", "crawl_yyth.py", "crawl_jianping_hb.py"]
res = {}
for f in T:
    print("── 实跑 %s" % f, flush=True)
    try:
        r = subprocess.run(["python3", D + f], capture_output=True, text=True, timeout=180, cwd=D)
        ls = [y for y in (r.stdout or "").split("\n") if y.strip()]
        err = [y for y in (r.stderr or "").split("\n") if y.strip()]
        print("   EXIT=%d" % r.returncode)
        for x in ls[-3:]: print("   out:", x[:105])
        for x in err[-2:]: print("   ERR:", x[:105])
        res[f] = dict(exit=r.returncode, tail=ls[-1][:120] if ls else "", err=(err[-1][:120] if err else ""))
    except subprocess.TimeoutExpired:
        print("   ⏱ >180s"); res[f] = dict(exit="TIMEOUT", tail="", err=">180s")
# 判定并开回
ok = [f for f, v in res.items() if v.get("exit") == 0]
print("\n=== 通过实跑: %s" % ok)
txt = open(CFG, encoding="utf-8").read()
changed = []
for f in ok:
    i = txt.find('"%s"' % f)
    if i < 0: continue
    s0 = txt.rfind("{", 0, i); s1 = txt.find('"script"', i + 30)
    if s1 < 0: s1 = len(txt)
    blk = txt[s0:s1]
    if '"enabled": false' not in blk:
        print("   %s 的 enabled 非 false，跳过" % f); continue
    nb = blk.replace('"enabled": false', '"enabled": true', 1)
    nb = re.sub(r'("note"\s*:\s*")', r'\g<1>[2026-09-26 复检：站点已恢复，重新启用] ', nb, count=1)
    txt = txt[:s0] + nb + txt[s1:]
    changed.append(f)
if changed:
    json.loads(txt)
    bak = D + "Archive/daily_crawl_config.json.bak_%s_reenable" % datetime.date.today().strftime("%Y%m%d")
    if not os.path.exists(bak): shutil.copy2(CFG, bak)
    open(CFG, "w", encoding="utf-8").write(txt)
    print("✅ 已开回: %s（备份 %s）" % (changed, os.path.basename(bak)))
cfg = json.load(open(CFG, encoding="utf-8"))
lst = cfg if isinstance(cfg, list) else cfg.get("tasks", [])
for f in T:
    e = [c for c in lst if c.get("script") == f]
    print("   回读 %-24s enabled=%s" % (f, e[0].get("enabled") if e else "N/A"))
