#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""fix_shaowu_offby1.py —— 修 range 上界 off-by-one"""
import ast, os, shutil, subprocess, sqlite3, time
D = "/root/gov_crawler/"; f = "crawl_shaowu.py"; p = D + f
src = open(p, encoding="utf-8").read()
OLD = "for pg in range(1, _MAX_PG or 53):"
NEW = "for pg in range(1, (_MAX_PG or 52) + 1):   # QC20260925 修 off-by-one: args=1 时 range(1,1) 为空导致循环不执行"
if OLD not in src:
    print("⚠️ 锚点未命中，当前行：")
    for ln in src.split("\n"):
        if "for pg in range" in ln: print("   ", ln.strip())
    raise SystemExit
src = src.replace(OLD, NEW, 1)
try: ast.parse(src)
except SyntaxError as e: raise SystemExit("语法错 %s" % e)
b = D + "Archive/" + f + ".bak_20260925_offby1"
if not os.path.exists(b): shutil.copy2(p, b)
open(p, "w", encoding="utf-8").write(src)
print("✅ 已改 range 上界（备份 %s）" % os.path.basename(b))
db = sqlite3.connect("file:/root/search.db?mode=ro", uri=True, timeout=30)
n0 = db.execute("SELECT COUNT(*) FROM gov_raw WHERE site_name LIKE '%邵武%'").fetchone()[0]
print("跑前行数: %d" % n0)
t0 = time.time()
try:
    r = subprocess.run(["python3", p, "1"], capture_output=True, text=True, timeout=120, 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()][:8]:
        print("   out:", x[:105])
except subprocess.TimeoutExpired:
    print("⏱ >120s（现在会真的去爬了）")
db2 = sqlite3.connect("file:/root/search.db?mode=ro", uri=True, timeout=30)
n1 = db2.execute("SELECT COUNT(*) FROM gov_raw WHERE site_name LIKE '%邵武%'").fetchone()[0]
print("跑后行数: %d (%s)" % (n1, "✅+%d" % (n1 - n0) if n1 > n0 else "未变"))
