#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# fix_jxth_ua.py — 给 fetch_api 的请求补现代 UA
import ast, os, re, shutil, sqlite3, subprocess
D = '/root/gov_crawler/'
f = 'crawl_jxth.py'
p = D + f
src = open(p, encoding='utf-8').read()
print('H 的当前内容:')
for i, ln in enumerate(src.split('\n'), 1):
    if re.search(r'^\s*H\s*=', ln):
        print('  L%d %s' % (i, ln.strip()[:120]))
OLD = '    hh = dict(H)\n'
NEW = ('    hh = dict(H)\n'
       '    hh["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"  # QC20260926\n')
if 'hh["User-Agent"]' in src:
    print('已补过 UA')
elif src.count(OLD) >= 1:
    src2 = src.replace(OLD, NEW, 1)
    ast.parse(src2)
    b = D + 'Archive/' + f + '.bak_20260926_ua'
    if not os.path.exists(b):
        shutil.copy2(p, b)
    open(p, 'w', encoding='utf-8').write(src2)
    print('OK 已补 UA（备份 %s）' % os.path.basename(b))
else:
    print('WARN 未找到 hh = dict(H)')
con = sqlite3.connect('file:/root/search.db?mode=ro', uri=True, timeout=30)
n0 = con.execute("SELECT COUNT(*) FROM gov_raw WHERE page_url LIKE '%jxth.gov.cn%'").fetchone()[0]
print('跑前行数:', n0)
try:
    r = subprocess.run(['python3', p], capture_output=True, text=True, timeout=200, cwd=D)
    print('EXIT=%d' % r.returncode)
    for x in [y for y in (r.stdout or '').split('\n') if y.strip()][-6:]:
        print('   out:', x[:118])
except subprocess.TimeoutExpired:
    print('>200s（在抓详情 → 列表通了）')
con2 = sqlite3.connect('file:/root/search.db?mode=ro', uri=True, timeout=30)
n1 = con2.execute("SELECT COUNT(*) FROM gov_raw WHERE page_url LIKE '%jxth.gov.cn%'").fetchone()[0]
print('跑后行数:', n1, ('OK +%d' % (n1 - n0)) if n1 > n0 else '未变')
