
import json
import os

TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>修修助手 - 版本历史</title>
    <style>
        body { font-family: sans-serif; max-width: 800px; margin: 40px auto; padding: 20px; line-height: 1.6; background: #f4f4f9; color: #333; }
        h1 { border-bottom: 2px solid #00bcd4; padding-bottom: 10px; }
        .version-entry { background: #fff; padding: 20px; margin-bottom: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        .version-entry h3 { margin-top: 0; color: #00bcd4; }
        .version-entry pre { background: #f0f0f0; padding: 15px; border-radius: 5px; overflow-x: auto; white-space: pre-wrap; font-family: monospace; }
        .btn { display: inline-block; padding: 10px 20px; background: #00bcd4; color: #fff; text-decoration: none; border-radius: 5px; margin-top: 10px; margin-right: 10px; }
        .btn:hover { background: #00acc1; }
        .actions { margin-top: 10px; }
    </style>
</head>
<body>
    <h1>修修助手 - 版本历史</h1>
    
    <!-- VERSIONS_PLACEHOLDER -->

</body>
</html>"""

def generate():
    try:
        with open('versions.json', 'r', encoding='utf-8') as f:
            versions = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        versions = []

    # Sort versions by date descending (assuming standard format or rely on order)
    # Actually just trust the JSON order or prepend? Let's assume JSON is ordered or we prepend.
    # The user might manually reorder. Let's just iterate.

    entries_html = ""
    for v in versions:
        if not v.get('visible', True):
            continue
            
        preview_btn = ""
        if v.get('preview_url'):
            preview_btn = f'<a href="{v["preview_url"]}" class="btn" style="background: #e91e63;" target="_blank">在线预览</a>'
            
        entry = f"""
        <div class="version-entry">
            <h3>{v.get('version')} ({v.get('date')})</h3>
            <pre>{v.get('log')}</pre>
            <div class="actions">
                <a href="./versions/{v.get('zip_name')}" class="btn">下载压缩包</a>
                {preview_btn}
            </div>
        </div>
        """
        entries_html += entry

    final_html = TEMPLATE.replace('<!-- VERSIONS_PLACEHOLDER -->', entries_html)
    
    with open('history.html', 'w', encoding='utf-8') as f:
        f.write(final_html)
    print("Generated history.html from versions.json")

if __name__ == "__main__":
    generate()
