#!/usr/bin/env python3.12
"""按用户 2026-10-10 规则：同一「词(中文)」标注只保留在 `brand` 字段。

规则原文：
    「如果 brand 和 title 里都同时出现了品牌词或者需要标注中文的词，
      只标注 brand 里的即可，尽量减少重复标注导致的内容过长。」

⭐ 作用域（2026-10-10 用户纠正，务必遵守）：
    本条**只作用于 `brand_hotspots`（品牌热点）**。
    **其他 4 个板块不要处理** —— 那些板块的 title 带 `(中文)` 标注是正常态。
    （默认只跑 brand_hotspots；`--all` 才会跑全板块，正常流水线**不要**加。）

判据：
  · 取某条 `brand` 里所有 `拉丁(中文)` 形态的词条；
  · 若 `title` 里出现**同一词 + 同一中文标注**，则把 `title` 中的 `(中文)` 去掉（裸写）；
  · `brand` 不动（保留标注）；`summary` / `hero_summary` 不在本条范围内
    （用户口径只提 brand↔title；是否扩到 summary 已于 2026-10-10 提交用户待定）。

用法：
    python3.12 dedupe_brand_annotations.py <json路径> [--dry-run] [--all]
示例：
    python3.12 /data/news/scripts/dedupe_brand_annotations.py \
        /data/news/json/ko-1010data.json --dry-run
"""

import json
import re
import sys

SCOPE = ['brand_hotspots']          # ⭐ 用户口径：只处理品牌热点
TERM = re.compile(r'([A-Za-z][A-Za-z0-9 .\-#&]*?)\(([\u4e00-\u9fff·]{1,12})\)')


def terms_of(brand: str):
    """从 brand 字段抽出 (拉丁词, 中文标注) 词条表。"""
    if not brand or '(' not in brand:
        return []
    return [(w.strip(), cn) for w, cn in TERM.findall(brand) if w.strip()]


def process(path: str, dry: bool, all_sec: bool) -> int:
    with open(path, encoding='utf-8') as f:
        data = json.load(f)

    changed = []
    for sec, items in data.items():
        if not isinstance(items, list):
            continue
        if not all_sec and sec not in SCOPE:
            continue                                  # 非品牌热点：按用户口径不动
        for i, item in enumerate(items):
            if not isinstance(item, dict):
                continue
            title = item.get('title')
            if not isinstance(title, str):
                continue
            for w, cn in terms_of(item.get('brand', '')):
                pat = re.escape(w) + r'\(' + re.escape(cn) + r'\)'
                new_title, n = re.subn(pat, w, title)
                if n:
                    changed.append((f'{sec}[{i}].title', f'{w}({cn})', w, new_title))
                    title = new_title
            item['title'] = title

    print(f'文件: {path}')
    print(f'作用域: {"全板块 (--all)" if all_sec else "仅 brand_hotspots（用户口径）"}')
    print(f'去重复标注: {len(changed)} 处' + ('  (dry-run，未写盘)' if dry else ''))
    for path_, old, new, full in changed:
        print(f'  {path_}: {old} → {new}')
        print(f'      → {full}')
    if changed and not dry:
        with open(path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        print('✅ 已写盘')
    return len(changed)


def main():
    args = [a for a in sys.argv[1:] if not a.startswith('--')]
    dry = '--dry-run' in sys.argv
    all_sec = '--all' in sys.argv
    if len(args) != 1:
        print(__doc__)
        sys.exit(2)
    process(args[0], dry, all_sec)


if __name__ == '__main__':
    main()
