#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# fix_route_filter.py — 在路由拿到 search() 结果后立即按标题剔除排除词
import ast, os, re, shutil
D = '/root/gov_crawler/'
p = D + 'search_app.py'
src = open(p, encoding='utf-8').read()
lines = src.split('\n')
# 先移除之前插入的无效过滤块（引用 q 的那些）
if '# QC20261008 排除词后过滤' in src:
    out, skip = [], False
    for l in lines:
        if '# QC20261008 排除词后过滤' in l:
            skip = True
            continue
        if skip:
            if re.match(r'^\s*(try:|_fi, _fe|_qc = query|if _fe and rows|_bk = len\(rows\)|def _tt|return \(_r|return ""|rows = \[_r|if len\(rows\) != _bk|total = max\(0|except Exception:|pass\s*$)', l):
                continue
            skip = False
        out.append(l)
    src = '\n'.join(out)
    lines = src.split('\n')
    print('已移除旧过滤块')
ANCHOR = re.compile(r'^(\s*)results, total, has_more = search\(')
NEW = [
    '# QC20261008 排除词过滤（路由级，只排标题）',
    'try:',
    '    _ei, _ee = parse_google_query(combined_q or "")',
    '    if _ee and results:',
    '        _bk = len(results)',
    '        def _ttl(_r):',
    '            try:',
    '                return (_r.get("title") if isinstance(_r, dict) else _r["title"]) or ""',
    '            except Exception:',
    '                return ""',
    '        results = [_r for _r in results if not any(_t in _ttl(_r) for _t in _ee)]',
    '        if len(results) != _bk:',
    '            try:',
    '                total = max(0, int(total or 0) - (_bk - len(results)))',
    '            except Exception:',
    '                pass',
    'except Exception:',
    '    pass',
]
hit = None
for i, l in enumerate(lines):
    if ANCHOR.match(l):
        hit = i
        break
if hit is None:
    print('WARN 未找到路由锚点 results, total, has_more = search(')
    for i, l in enumerate(lines, 1):
        if 'search(combined_q' in l:
            print('  L%d: %s' % (i, l.strip()[:110]))
    raise SystemExit(0)
ind = ANCHOR.match(lines[hit]).group(1)
new = lines[:hit + 1] + [(ind + x) if x.strip() else x for x in NEW] + lines[hit + 1:]
src2 = '\n'.join(new)
try:
    ast.parse(src2)
except SyntaxError as e:
    print('语法错，未落盘:', e)
    raise SystemExit(1)
b = D + 'Archive/search_app.py.bak_20261008_routefilter'
if not os.path.exists(b):
    shutil.copy2(p, b)
open(p, 'w', encoding='utf-8').write(src2)
print('OK 已在路由 L%d 之后插入过滤' % (hit + 1))
