#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# fix_minus_pure.py — 纯负词分支（只发 -词）
import ast, os, re, shutil
D = '/root/gov_crawler/'
f = 'search_app.py'
p = D + f
src = open(p, encoding='utf-8').read()
ANCHOR = "        if q and not _ent_done:"
NEWBLOCK = """        # ── QC20261008 纯负词分支：只发「-词」(无正词) → 直接按「标题不含该词」列出 ──
        if q and not _ent_done:
            _pinc, _pexc = parse_google_query(q)
            if (not _pinc) and _pexc:
                try:
                    _wc, _wp = [], []
                    for _t in _pexc:
                        _wc.append('(r.title NOT LIKE ?)')
                        _wp.append('%' + _t + '%')
                    if daterange and daterange != 'all':
                        _d2 = {'1d': 1, '7d': 7, '30d': 30}[daterange]
                        _wc.append("(r.publish_date GLOB '20[0-9][0-9]-[0-9][0-9]-[0-9][0-9]*' AND SUBSTR(r.publish_date,1,10) >= date('now', '-%d days'))" % _d2)
                    try:
                        _if9, _ip9 = _ind_in_clause('r.industry', industry_filter)
                        if _if9:
                            _wc.append('(' + _if9 + ')')
                            _wp.extend(_ip9)
                    except Exception:
                        pass
                    _wsql = ' AND '.join(_wc) if _wc else '1=1'
                    c.execute('SELECT COUNT(*) FROM gov_raw r WHERE ' + _wsql, _wp)
                    total = c.fetchone()[0]
                    c.execute('SELECT r.* FROM gov_raw r WHERE ' + _wsql + ' ORDER BY r.publish_date DESC, r.id DESC LIMIT ? OFFSET ?', _wp + [fetch_size, offset])
                    rows = [dict(r) for r in c.fetchall()]
                    _ent_done = True
                except Exception:
                    pass
        if q and not _ent_done:"""
n = src.count(ANCHOR)
print('锚点出现次数:', n)
if n != 1:
    print('⚠️ 锚点不唯一/未找到，未改动')
    raise SystemExit(1)
src2 = src.replace(ANCHOR, NEWBLOCK, 1)
try:
    ast.parse(src2)
except SyntaxError as e:
    print('语法错，未落盘:', e)
    raise SystemExit(1)
b = D + 'Archive/' + f + '.bak_20261008_pureminus'
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 'QC20261008' in ln:
        print('  L%d: %s' % (i, ln.strip()[:100]))
