#!/bin/bash
# 生成最终 Word 文档（跳过 App 截图）
python3 - << 'PYEOF'
import os
from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH

BASE_DIR = "/root/openclaw-workspace/projects/yu-zhi-ran/content/published/2026-04-14-上海阳台种菜一年"
MD_FILE = os.path.join(BASE_DIR, "final-article-optimized.md")
IMAGES_DIR = os.path.join(BASE_DIR, "images")
OUTPUT_DOCX = os.path.join(BASE_DIR, "上海阳台种菜一年_发布版.docx")

SKIP_IMAGES = ["08-App截图.png"]

with open(MD_FILE, "r", encoding="utf-8") as f:
    lines = f.readlines()

doc = Document()
doc.styles['Normal'].font.name = '微软雅黑'
doc.styles['Normal'].font.size = Pt(11)

def add_heading(text, level=1):
    h = doc.add_heading(text, level=level)
    h.alignment = WD_ALIGN_PARAGRAPH.LEFT
    return h

for line in lines:
    line = line.rstrip('\n')

    if line.startswith('# '):
        add_heading(line[2:], level=1)
        continue
    if line.startswith('## '):
        add_heading(line[3:], level=2)
        continue
    if line.startswith('### '):
        add_heading(line[4:], level=3)
        continue
    if line.startswith('---'):
        doc.add_paragraph('_' * 60)
        continue

    if line.startswith('!['):
        import re
        m = re.match(r'!\[(.*?)\]\((images/.*?)\)', line)
        if m:
            alt, fname = m.groups()
            if fname in SKIP_IMAGES:
                p = doc.add_paragraph("[此处省略App截图，保持内容中立]")
                p.italic = True
                continue
            img_path = os.path.join(IMAGES_DIR, os.path.basename(fname))
            if os.path.exists(img_path):
                try:
                    doc.add_picture(img_path, width=Inches(6))
                    last_para = doc.paragraphs[-1]
                    last_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
                except Exception:
                    doc.add_paragraph(f"[图片错误: {fname}]")
            else:
                doc.add_paragraph(f"[缺失图片: {fname}]")
        continue

    if not line.strip():
        doc.add_paragraph()
        continue

    p = doc.add_paragraph()
    tmp = line
    while '**' in tmp:
        before = tmp[:tmp.find('**')]
        if before:
            p.add_run(before)
        tmp = tmp[tmp.find('**')+2:]
        if '**' in tmp:
            bold_text = tmp[:tmp.find('**')]
            run = p.add_run(bold_text)
            run.bold = True
            tmp = tmp[tmp.find('**')+2:]
        else:
            run = p.add_run(tmp)
            run.bold = True
            break
    if '**' not in line:
        p.add_run(line)

doc.save(OUTPUT_DOCX)
print(f"✅ 最终发布 Word: {OUTPUT_DOCX}")
print(f"📊 段落数: {len(doc.paragraphs)}")
print(f"💾 文件大小: {os.path.getsize(OUTPUT_DOCX)/1024:.1f} KB")
print(f"⚠️  跳过图片: {', '.join(SKIP_IMAGES)}")
PYEOF
