#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# diag_jxth_runtime.py — 运行时诊断 + 修 L86 + 修 NAME
import ast, os, re, sqlite3, subprocess
D = '/root/gov_crawler/'
f = 'crawl_jxth.py'
p = D + f
src = open(p, encoding='utf-8').read()
bad = '# QC20260925 去掉整站清空再重灌(抢锁+中途死掉会清空整站; page_url 有 UNIQUE 索引，插入本就幂等)     conn.execute("DELETE FROM gov_raw WHERE site_name=?", (NAME,))\n'
if bad in src:
    src = src.replace(bad, '# QC20260925 去掉整站清空再重灌(抢锁+中途死掉会清空整站; page_url 有 UNIQUE 索引，插入本就幂等)\n    # conn.execute("DELETE FROM gov_raw WHERE site_name=?", (NAME,))  # QC20260926 已去除\n', 1)
    print('① L86 修正：注释与语句分行 OK')
else:
    print('① L86 未匹配')
dbg = '        d = fetch_api(pg)\n'
if dbg in src:
    src = src.replace(dbg, dbg + '        print("  [DEBUG] type=%s repr=%s" % (type(d).__name__, repr(d)[:400]), flush=True)\n', 1)
    print('② 已插调试打印')
src2 = re.sub(r'(?m)^NAME\s*=\s*"靖西市"', 'NAME = "泰和县"', src, count=1)
print('③ NAME:', '已改泰和县' if 'NAME = "泰和县"' in src2 else '未匹配')
try:
    ast.parse(src2)
    src = src2
except SyntaxError as e:
    print('语法错，撤销 NAME 改动:', e)
open(p, 'w', encoding='utf-8').write(src)
con = sqlite3.connect('file:/root/search.db?mode=ro', uri=True, timeout=30)
print('跑前行数:', con.execute("SELECT COUNT(*) FROM gov_raw WHERE page_url LIKE '%jxth.gov.cn%'").fetchone()[0])
try:
    r = subprocess.run(['python3', p], capture_output=True, text=True, timeout=100, cwd=D)
    print('EXIT=%d' % r.returncode)
    for x in [y for y in (r.stdout or '').split('\n') if y.strip()][:14]:
        print('   out:', x[:160])
except subprocess.TimeoutExpired:
    print('>100s')
cur = open(p, encoding='utf-8').read()
cur = re.sub(r'(?m)^\s*print\("  \[DEBUG\].*\n', '', cur)
ast.parse(cur)
open(p, 'w', encoding='utf-8').write(cur)
print('④ 调试打印已撤除（L86 与 NAME 修正保留）')
con2 = sqlite3.connect('file:/root/search.db?mode=ro', uri=True, timeout=30)
print('跑后行数:', con2.execute("SELECT COUNT(*) FROM gov_raw WHERE page_url LIKE '%jxth.gov.cn%'").fetchone()[0])
