#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""patch_search_app_originals2.py —— 按用户反馈微调 /originals/：

① 拼接 URL 的 ID 文字：去掉下划线、不改小手（cursor:text）
② 更根本的一步：加 draggable="false" —— <a> 按住拖动会变成「拖链接」而不是选中文字，
   这才是「影响正常选中」的真凶，光改 cursor 不够
③ 外链图标：方框箭头(external-link) → 链条(link) 图标

安全：逐段 anchor 替换，命中数必须为 1，否则整脚本中止不落盘；改前备份；改后 ast 校验。
"""
import ast
import io
import os
import shutil
import sys

P = "/root/gov_crawler/search_app.py"
BAK = "/root/gov_crawler/Archive/search_app.py.bak_20260924_origfeat2"

src = io.open(P, encoding="utf-8").read()
orig = src
edits = []


def repl(name, old, new, expect=1):
    global src
    n = src.count(old)
    if n != expect:
        edits.append((name, "❌ 命中 %d 次（期望 %d）" % (n, expect)))
        return False
    src = src.replace(old, new)
    edits.append((name, "✅"))
    return True


# ── ① ID 文字：去下划线 + 不改小手 ──────────────────────────────────
repl("①ID 去下划线/小手",
     """    '.kw{color:inherit;border-bottom:1px dotted #9aa0a6}'
    '.kw:hover{color:#1a73e8;border-bottom-color:#1a73e8}'""",
     """    '.kw{color:inherit;cursor:text}'
    '.kw:hover{color:#1a73e8}'""")

# ── ② 加 draggable=false：让 ID 能被正常拖选（而不是拖链接）────────
repl("②ID 可正常拖选",
     """    return ('<a class="kw ' + cls + '" href="/originals/?q=' + urllib.parse.quote(str(text)) +
            '" title="按此关键词搜索">' + html.escape(str(text)) + '</a>')""",
     """    return ('<a class="kw ' + cls + '" draggable="false" href="/originals/?q=' +
            urllib.parse.quote(str(text)) + '" title="按此关键词搜索">' +
            html.escape(str(text)) + '</a>')""")

# ── ③ 图标：方框箭头 → 链条(link) ───────────────────────────────────
repl("③图标换链条",
     """            'title="在 industrialinfo 打开 ' + d + '"><svg width="12" height="12" viewBox="0 0 24 24" '
            'fill="none" stroke="#1a73e8" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">'
            '<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>'
            '<polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg></a>')""",
     """            'title="在 industrialinfo 打开 ' + d + '"><svg width="13" height="13" viewBox="0 0 24 24" '
            'fill="none" stroke="#1a73e8" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">'
            '<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>'
            '<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg></a>')""")

# ── 汇总 ─────────────────────────────────────────────────────────────
print("=" * 80)
for n, r in edits:
    print("  %-18s %s" % (n, r))
print("=" * 80)

if [n for n, r in edits if not r.startswith("✅")]:
    print("❌ 有锚点未命中，未改动任何内容")
    sys.exit(1)

try:
    ast.parse(src)
except SyntaxError as e:
    io.open("/tmp/search_app_candidate2.py", "w", encoding="utf-8").write(src)
    print("❌ 语法错误，未落盘：%s（待检文本 /tmp/search_app_candidate2.py）" % e)
    sys.exit(1)

os.makedirs(os.path.dirname(BAK), exist_ok=True)
if not os.path.exists(BAK):
    shutil.copy2(P, BAK)
io.open(P, "w", encoding="utf-8").write(src)
print("✅ 已写入  备份 %s" % BAK)
print("   行数 %d → %d" % (orig.count("\n") + 1, src.count("\n") + 1))
