#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# fix_minus_all.py — 在所有 return rows, total, has_more 之前插入标题排除过滤
import ast, os, re, shutil
D = '/root/gov_crawler/'
f = 'search_app.py'
p = D + f
src = open(p, encoding='utf-8').read()
FTAG = '# QC20261008 排除词后过滤'
if FTAG in src:
    print('已有过滤，先移除旧的以免重复……')
    lines = [l for l in src.split('\n')]
    out, skip = [], 0
    for i, l in enumerate(lines):
        if FTAG in l:
            skip = 1
            continue
        if skip:
            if re.match(r'^\s*(try:|_fi, _fe|if _fe and rows|_bk = len\(rows\)|def _tt|return \(r\.get|except Exception:|return ""|rows = \[r for r in rows|if len\(rows\) != _bk|total = max\(0|pass)', l):
                continue
            skip = 0
        out.append(l)
    src = '\n'.join(out)
    print('  旧过滤已移除')

FILTER = [
    '# 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',
]
CALLP = re.compile(r'^(\s*)(self\.search|return self\.search|search\()')
lines = src.split('\n')
# 在所有 'return rows, total, has_more' / 'return rows, total' 前插入
pat = re.compile(r'^(\s*)return rows, total(, has_more)?\s*$')
idx = [i for i, l in enumerate(lines) if pat.match(l)]
print('返回点数量:', len(idx), '行号:', [i + 1 for i in idx])
new, prev = [], 0
cnt = 0
for i in idx:
    ind = pat.match(lines[i]).group(1)
    new.extend(lines[prev:i])
    new.extend([(ind + x) if x.strip() else x for x in FILTER])
    new.append(lines[i])
    prev = i + 1
    cnt += 1
new.extend(lines[prev:])
src2 = '\n'.join(new)
try:
    ast.parse(src2)
except SyntaxError as e:
    print('语法错，未落盘:', e)
    raise SystemExit(1)
b = D + 'Archive/' + f + '.bak_20261008_allfilter'
if not os.path.exists(b):
    shutil.copy2(p, b)
open(p, 'w', encoding='utf-8').write(src2)
print('OK 已在 %d 处返回点插入过滤（备份 %s）' % (cnt, os.path.basename(b)))
# 顺带查一下主搜索路由到底调用哪个函数
print('\n=== 谁在调用 search() / 主路由用什么 ===')
for i, l in enumerate(src2.split('\n'), 1):
    if re.search(r'=\s*search\(|self\.search\(|\bsearch\(q|def handle_search|render_main_page\(', l):
        print('  L%-5d %s' % (i, l.strip()[:110]))
