#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# fix_minus_filter.py — 结果出来后按标题剔除排除词（分支无关兜底）
import ast, os, re, shutil
D = '/root/gov_crawler/'
f = 'search_app.py'
p = D + f
src = open(p, encoding='utf-8').read()
lines = src.split('\n')
print('=== 候选锚点（return rows / has_more / render 附近）===')
hits = []
for i, ln in enumerate(lines, 1):
    if re.search(r'\brows\b', ln) and re.search(r'return|has_more|render|resp|send_', ln):
        hits.append((i, ln))
for i, ln in hits[-25:]:
    print('  L%-5d %s' % (i, ln.rstrip()[:118]))
print('  共 %d 个候选' % len(hits))

FILTER_LINES = [
    '# QC20261008 排除词后过滤：只排除「标题」含排除词的结果（分支无关兜底）',
    'try:',
    '    _fi, _fe = parse_google_query(q or "")',
    '    if _fe and rows:',
    '        _bk = len(rows)',
    '        def _tt(r):',
    '            try:',
    '                return (r.get("title") if isinstance(r, dict) else r["title"]) or ""',
    '            except Exception:',
    '                return ""',
    '        rows = [r for r in rows if not any(t in _tt(r) for t in _fe)]',
    '        if len(rows) != _bk:',
    '            try:',
    '                total = max(0, int(total or 0) - (_bk - len(rows)))',
    '            except Exception:',
    '                pass',
    'except Exception:',
    '    pass',
]

CANDS = [
    r'^\s*return rows, total, has_more',
    r'^\s*return rows, total\s*$',
    r'^\s*rows, total, has_more\s*=',
]
applied = False
for pat in CANDS:
    for i, ln in enumerate(lines):
        if re.match(pat, ln):
            ind = ln[:len(ln) - len(ln.lstrip())]
            block = [ind + x if x.strip() else x for x in FILTER_LINES]
            new = lines[:i] + block + [ln] + lines[i + 1:]
            src2 = '\n'.join(new)
            try:
                ast.parse(src2)
            except SyntaxError as e:
                print('锚点 L%d 语法错（跳过）: %s' % (i + 1, e))
                continue
            b = D + 'Archive/' + f + '.bak_20261008_filter'
            if not os.path.exists(b):
                shutil.copy2(p, b)
            open(p, 'w', encoding='utf-8').write(src2)
            print('OK 已在 L%d 之前插入过滤（锚点 %s）' % (i + 1, pat))
            applied = True
            break
    if applied:
        break
if not applied:
    print('WARN 没有合适锚点，未改动 —— 请把上面的候选行发我，下一步人工定位')
