#!/usr/bin/env python3
"""
清理已发布的 HTML 文件：
1. 删除所有 <img> 标签
2. 清理标题中的 (约XXX字) 括号
"""
import re
from pathlib import Path

files = [
    "automation/data/releases/2026-04-21/zhihu/zhihu_TOPIC-BBB1CC_zhihu.html",
    "automation/data/releases/2026-04-21/wechat/wechat_TOPIC-BBB1CC_wechat.html",
    "automation/data/releases/2026-04-21/xiaohongshu/xiaohongshu_TOPIC-BBB1CC_xiaohongshu.html"
]

def clean_html(html: str) -> str:
    # 1. 删除所有 <img ...> 标签
    html = re.sub(r'<img[^>]*>', '', html)

    # 2. 清理标题中的 (约XXX字) 等括号内容
    def clean_text(text: str) -> str:
        text = re.sub(r'[（(]约\s*\d+字[）)]', '', text)
        text = re.sub(r'[（(]MVP[）)]', '', text)
        text = re.sub(r'[（(][^）)]*?[）)]', '', text)  # 保守移除任意括号内容
        return text.strip()

    # 处理 <title> 标签
    def clean_title(match):
        return match.group(1) + clean_text(match.group(2)) + match.group(3)
    html = re.sub(r'(<title>)([^<]*)(</title>)', clean_title, html)

    # 处理内容中的标题标签 (h1-h6)
    def clean_heading(match):
        return match.group(1) + clean_text(match.group(2)) + match.group(3)
    html = re.sub(r'(<h[1-6][^>]*>)([^<]*)(</h[1-6]>)', clean_heading, html)

    return html

if __name__ == "__main__":
    for f in files:
        path = Path(f)
        if not path.exists():
            print(f"跳过（不存在）: {f}")
            continue
        original = path.read_text(encoding='utf-8')
        cleaned = clean_html(original)
        path.write_text(cleaned, encoding='utf-8')
        print(f"✅ 已清理: {f}")

    print("全部完成！")