#!/usr/bin/env python3
"""微信公众号草稿发布 v4 — 干净版"""
import json, requests
from wechatpy import WeChatClient
from bs4 import BeautifulSoup

APP_ID = "wx13587bb0f62ac3ee"
APP_SECRET = "306b749759ea19c4c84823629100a358"
HTML_FILE = "pi-english-tutor介绍.html"
COVER_FILE = "cover.png"
TITLE = "不用多开一个App，一行命令变身英语老师"

IMAGES = [
    ("img2_pain.png",   "你有没有这种经历"),
    ("img3_solution.png","AI 同时输出英文和中文"),
    ("img4_levelup.png", "每个等级对 AI"),
    ("img5_cta.png",    "如果你日常用 pi"),
]

client = WeChatClient(APP_ID, APP_SECRET)
token = client.fetch_access_token()
print("✅ access_token")

upload_url = f"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={token['access_token']}&type=image"

# 封面
with open(COVER_FILE, "rb") as f:
    cover_id = requests.post(upload_url, files={"media": f}).json()["media_id"]
print("✅ 封面 (21:9)")

# 内容图
img_tags = {}
for filename, anchor in IMAGES:
    with open(filename, "rb") as f:
        url = requests.post(upload_url, files={"media": f}).json()["url"]
    img_tags[anchor] = f'<p style="text-align:center;margin:24px 0"><img src="{url}" style="max-width:100%;border-radius:8px" alt=""/></p>'
    print(f"✅ {filename}")

# HTML
with open(HTML_FILE, "r", encoding="utf-8") as f:
    soup = BeautifulSoup(f.read(), "html.parser")
body = soup.find("body")
html = "".join(str(c) for c in body.contents) if body else str(soup)

# 去掉转换器留下的提示文字
import re
html = re.sub(r'<!--.*?-->', '', html, flags=re.DOTALL)
html = re.sub(r'⚠️.*?H1 标题.*?\n', '', html)

for anchor, tag in img_tags.items():
    html = html.replace(anchor, tag + "\n" + anchor)

print(f"📄 {len(html)} 字符")

# 草稿
draft_url = f"https://api.weixin.qq.com/cgi-bin/draft/add?access_token={token['access_token']}"
payload = {
    "articles": [{
        "title": TITLE,
        "thumb_media_id": cover_id,
        "content": html,
        "content_source_url": "https://github.com/T-DWAG/pi-english-tutor",
        "digest": "学英语不用多开App，写代码时顺带练口语。",
        "need_open_comment": 0,
    }]
}
r = requests.post(draft_url, data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
                  headers={"Content-Type": "application/json; charset=utf-8"})
result = r.json()
if "media_id" in result:
    print(f"✅ draft_id={result['media_id']}")
    print("📋 草稿箱 → 预览 → 群发")
else:
    print(f"❌ {result}")
