#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""fix_heshan_retry.py —— 给 search_api / fetch_detail 加重试"""
import ast, os, shutil, subprocess, time
D = "/root/gov_crawler/"; f = "crawl_heshan_gkmlpt.py"; p = D + f
src = open(p, encoding="utf-8").read()

OLD1 = '    r = requests.get(url, params=params, headers=HEADERS, timeout=30)\n'
NEW1 = ('    r = None\n'
        '    for _try in range(3):            # QC20260926 加重试：源站偶发连接失败会崩掉整轮\n'
        '        try:\n'
        '            r = requests.get(url, params=params, headers=HEADERS, timeout=30)\n'
        '            break\n'
        '        except Exception:\n'
        '            if _try == 2:\n'
        '                raise\n'
        '            time.sleep(2 * (_try + 1))\n')

OLD2 = ('        r = requests.get(url, headers=HEADERS, timeout=30)\n'
        "        r.encoding = 'utf-8'\n"
        '    except:\n'
        '        return None, "", None\n')
NEW2 = ('        r = None\n'
        '        for _try in range(3):        # QC20260926 加重试\n'
        '            try:\n'
        '                r = requests.get(url, headers=HEADERS, timeout=30)\n'
        "                r.encoding = 'utf-8'\n"
        '                break\n'
        '            except Exception:\n'
        '                if _try == 2:\n'
        '                    return None, "", None\n'
        '                time.sleep(2 * (_try + 1))\n')

ok = 0
for o, n in ((OLD1, NEW1), (OLD2, NEW2)):
    if src.count(o) == 1:
        src = src.replace(o, n); ok += 1
    else:
        print("  ⚠️ 锚点命中 %d 次，跳过该处" % src.count(o))
print("替换成功 %d/2 处" % ok)
try: ast.parse(src)
except SyntaxError as e: raise SystemExit("语法错 %s" % e)
b = D + "Archive/" + f + ".bak_20260926_retry"
if not os.path.exists(b): shutil.copy2(p, b)
open(p, "w", encoding="utf-8").write(src)
print("✅ 已落盘（备份 %s）" % os.path.basename(b))
t0 = time.time()
try:
    r = subprocess.run(["python3", p, "龙口镇"], capture_output=True, text=True, timeout=110, cwd=D)
    print("EXIT=%d 耗时=%.0fs" % (r.returncode, time.time() - t0))
    for x in [y for y in (r.stdout or "").split("\n") if y.strip()][:5]:
        print("   out:", x[:105])
except subprocess.TimeoutExpired:
    print("⏱ >110s（在正常爬，属预期）")
