#!/usr/bin/env python3
"""Convert .md articles to .html for Tencent Cloud Lighthouse file manager preview.

Usage:
    python3 md2html.py                          # convert all .md under ~/.hermes/articles/
    python3 md2html.py path/to/file.md          # convert specific file(s)

Requires: pip install markdown
"""
import markdown
from pathlib import Path
import sys

CSS = """
body { font-family: -apple-system, 'Noto Sans CJK SC', sans-serif; max-width: 720px; margin: 40px auto; padding: 0 20px; line-height: 1.8; color: #333; }
h1 { color: #1a6fb5; border-bottom: 3px solid #1a6fb5; padding-bottom: 8px; font-size: 24px; }
h2 { color: #1a6fb5; margin-top: 32px; font-size: 20px; }
h3 { color: #333; font-size: 17px; }
blockquote { background: #e8f4fd; padding: 12px 16px; border-left: 4px solid #1a6fb5; margin: 16px 0; color: #555; }
table { border-collapse: collapse; width: 100%; margin: 16px 0; }
th, td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
th { background: #e8f4fd; color: #1a6fb5; }
strong { color: #e67e22; }
ul, ol { padding-left: 24px; }
li { margin: 6px 0; }
hr { border: none; border-top: 1px solid #eee; margin: 24px 0; }
p { margin: 12px 0; }
"""

def md_to_html(md_path: str):
    md_text = Path(md_path).read_text()
    html_body = markdown.markdown(md_text, extensions=['tables', 'fenced_code'])
    html = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{CSS}</style></head>
<body>
{html_body}
</body></html>"""
    out_path = str(md_path).replace('.md', '.html')
    Path(out_path).write_text(html)
    return out_path

if __name__ == '__main__':
    if len(sys.argv) > 1:
        for path in sys.argv[1:]:
            out = md_to_html(path)
            print(out)
    else:
        base = Path('/home/ubuntu/.hermes/articles')
        for md_file in base.rglob('*.md'):
            html_file = str(md_file).replace('.md', '.html')
            if not Path(html_file).exists():
                out = md_to_html(str(md_file))
                print(out)
    print("Done")
