#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# fix_minus2.py — 正则版：排除词只排标题
import ast, os, re, shutil
D = '/root/gov_crawler/'
f = 'search_app.py'
p = D + f
src = open(p, encoding='utf-8').read()
PAT = re.compile(r"([ \t]*)like_conds\.append\(['\"]\(r\.title NOT LIKE \?\s+AND\s+r\.site_name NOT LIKE \?\s+AND\s+r\.summary NOT LIKE \?\)['\"]\)\n([ \t]*)like_params\.extend\(\[[^\]]*\]\)")
m = PAT.findall(src)
print('正则命中:', len(m))
def repl(mo):
    ind = mo.group(1)
    return (ind + "# QC20260930 用户口径：-词 只排除「标题」含该词的结果（不再排 site_name/summary）\n"
            + ind + "like_conds.append('(r.title NOT LIKE ?)')\n"
            + ind + "like_params.extend(['%' + t + '%'])")
src2 = PAT.sub(repl, src)
if src2 == src:
    print('⚠️ 未改动（正则没匹配上）')
    for i, ln in enumerate(src.split('\n'), 1):
        if 'NOT LIKE' in ln and 'title' in ln:
            print('  实际写法 L%d: %r' % (i, ln))
else:
    try:
        ast.parse(src2)
    except SyntaxError as e:
        print('语法错，未落盘:', e)
        raise SystemExit(1)
    b = D + 'Archive/' + f + '.bak_20260930_minus'
    if not os.path.exists(b):
        shutil.copy2(p, b)
    open(p, 'w', encoding='utf-8').write(src2)
    print('✅ 已改（备份 %s）' % os.path.basename(b))
    for i, ln in enumerate(src2.split('\n'), 1):
        if 'NOT LIKE' in ln and 'title' in ln:
            print('  新写法 L%d: %s' % (i, ln.strip()[:110]))
