#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# fix_global_minus.py — 入口处归一化：排除词只用来过滤，不再参与检索（全局生效）
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')

# ---------- A. 清理之前 6 处引用 q（未定义 → 静默失效）的哑块 ----------
if '# QC20261008 排除词后过滤' in src:
    out, skip, cnt = [], False, 0
    for l in lines:
        if '# QC20261008 排除词后过滤' in l and '渲染前' not in l:
            skip = True
            cnt += 1
            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('A. 清理哑块 %d 处' % cnt)

# ---------- B. 入口归一化：handle_search_page 里 q 首次赋值之后 ----------
m = re.search(r'^    def handle_search_page\(self, params\):', src, re.M)
if not m:
    print('B. WARN 未找到 handle_search_page')
else:
    seg = src[m.end():m.end() + 4000].split('\n')
    qline = None
    for i, l in enumerate(seg):
        if re.match(r'^        q\s*=', l):
            qline = i
            break
    if qline is None:
        print('B. WARN 未在 handle_search_page 里找到 q = 赋值')
        for i, l in enumerate(seg[:40]):
            if 'q' in l and '=' in l:
                print('   %s' % l.strip()[:100])
    else:
        lines = src.split('\n')
        # 定位绝对行号
        abs_ln = src[:m.end()].count('\n') + qline
        ins = [
            '        # QC20261008 入口归一化：-词 只作排除用，不参与检索（全局生效）',
            '        try:',
            '            self._orig_q = q',
            '            _qi, _qe = parse_google_query((q or "").strip())',
            '            if _qe and _qi:',
            '                q = " ".join(_qi)',
            '        except Exception:',
            '            pass',
        ]
        lines = lines[:abs_ln + 1] + ins + lines[abs_ln + 1:]
        src = '\n'.join(lines)
        print('B. 已在 handle_search_page 的 q 赋值后（原文 L%d）插入归一化' % (abs_ln + 1))

# ---------- C. 渲染层过滤改成读原始查询 ----------
old = '    _ei, _ee = parse_google_query(q or "")'
new = '    _ei, _ee = parse_google_query((getattr(self, "_orig_q", None) or q) or "")'
n = src.count(old)
src = src.replace(old, new)
print('C. 渲染层过滤改为读 _orig_q：%d 处' % n)

try:
    ast.parse(src)
except SyntaxError as e:
    print('语法错，未落盘:', e)
    raise SystemExit(1)
b = D + 'Archive/search_app.py.bak_20261008_global'
if not os.path.exists(b):
    shutil.copy2(p, b)
open(p, 'w', encoding='utf-8').write(src)
print('OK 已写入（备份 search_app.py.bak_20261008_global）')
print('\n=== 校验：出现的关键行 ===')
for i, l in enumerate(src.split('\n'), 1):
    if 'QC20261008' in l or '_orig_q' in l:
        print('  L%-5d %s' % (i, l.strip()[:104]))
