#!/usr/bin/env python3
"""
生成图文混排的 HTML（图片内联为 base64），方便直接复制
"""

import os
import re
import base64

BASE_DIR = "/root/openclaw-workspace/projects/yu-zhi-ran/content/published/2026-04-14-上海阳台种菜一年"
MD_FILE = os.path.join(BASE_DIR, "final-article.md")
IMAGES_DIR = os.path.join(BASE_DIR, "images")  # 使用发布目录内的 images
OUT_HTML = os.path.join(BASE_DIR, "上海阳台种菜一年_内联.html")

# 读取 Markdown
with open(MD_FILE, "r", encoding="utf-8") as f:
    content = f.read()

# 预加载图片并转为 base64
image_cache = {}
for fname in os.listdir(IMAGES_DIR):
    if fname.endswith('.png'):
        path = os.path.join(IMAGES_DIR, fname)
        with open(path, "rb") as imgf:
            b64 = base64.b64encode(imgf.read()).decode('utf-8')
            image_cache[fname] = b64

# 替换图片
def replace_img(match):
    alt = match.group(1)
    fname = match.group(2)
    key = os.path.basename(fname)
    if key in image_cache:
        return f'<img src="data:image/png;base64,{image_cache[key]}" alt="{alt}" style="max-width:100%; margin:20px 0; display:block;">'
    else:
        return f'<p>[图片缺失: {fname}]</p>'

content = re.sub(r'!\[(.*?)\]\((images/.*?)\)', replace_img, content)

# Markdown 转 HTML
html_lines = []
for line in content.split('\n'):
    if line.startswith('# '):
        html_lines.append(f'<h1>{line[2:]}</h1>')
    elif line.startswith('## '):
        html_lines.append(f'<h2>{line[3:]}</h2>')
    elif line.startswith('### '):
        html_lines.append(f'<h3>{line[4:]}</h3>')
    elif line.startswith('---'):
        html_lines.append('<hr>')
    elif line.startswith('> '):
        html_lines.append(f'<blockquote>{line[2:]}</blockquote>')
    elif re.match(r'^[-*] ', line):
        html_lines.append(f'<li>{line[2:]}</li>')
    elif re.match(r'^\d+\. ', line):
        html_lines.append(f'<li>{line[line.find(". ")+2:]}</li>')
    elif line.strip() == '':
        html_lines.append('<br>')
    else:
        tmp = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', line)
        tmp = re.sub(r'\*(.*?)\*', r'<em>\1</em>', tmp)
        html_lines.append(f'<p>{tmp}</p>')

html = f'''<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>上海阳台种菜一年</title>
<style>
body {{ font-family: "Microsoft YaHei", sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; line-height: 1.8; }}
h1 {{ font-size: 28px; border-bottom: 2px solid #4CAF50; padding-bottom: 10px; }}
h2 {{ font-size: 24px; margin-top: 40px; border-left: 4px solid #4CAF50; padding-left: 10px; }}
h3 {{ font-size: 20px; margin-top: 30px; color: #666; }}
img {{ max-width: 100%; height: auto; border-radius: 4px; margin: 20px 0; display: block; margin-left: auto; margin-right: auto; }}
blockquote {{ border-left: 4px solid #4CAF50; background: #f9f9f9; padding: 10px 20px; margin: 20px 0; color: #666; }}
li {{ margin-bottom: 8px; }}
p {{ margin-bottom: 16px; }}
</style>
</head>
<body>
{chr(10).join(html_lines)}
</body>
</html>'''

with open(OUT_HTML, "w", encoding="utf-8") as f:
    f.write(html)

print(f"✅ HTML 已生成: {OUT_HTML}")
print(f"📊 字符数: {len(content)}")
print(f"🖼️  内嵌图片: {len(image_cache)} 张")
