#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""极简 Markdown -> HTML，供 LibreOffice 转 PDF/DOCX 使用。"""
import re, sys, html, pathlib

CSS = """
@page { size: A4; margin: 1.8cm 1.7cm 1.8cm 1.7cm; }
body { font-family: "Noto Sans CJK SC", "SimSun", "宋体", sans-serif; font-size: 10.5pt; line-height: 1.45; color: #111; }
h1 { font-size: 18pt; text-align: center; margin: 12pt 0 14pt 0; page-break-before: always; }
h1:first-of-type { page-break-before: auto; }
h2 { font-size: 14pt; margin: 14pt 0 8pt 0; border-bottom: 1px solid #444; padding-bottom: 3pt; }
h3 { font-size: 12pt; margin: 10pt 0 6pt 0; }
h4 { font-size: 11pt; margin: 8pt 0 4pt 0; }
p { margin: 4pt 0; text-align: justify; }
table { border-collapse: collapse; width: 100%; margin: 6pt 0; font-size: 9.5pt; }
th, td { border: 1px solid #333; padding: 3pt 5pt; vertical-align: top; }
th { background: #eee; font-weight: bold; }
ul, ol { margin: 4pt 0 4pt 18pt; }
li { margin: 2pt 0; }
blockquote { border-left: 3px solid #777; margin: 6pt 0; padding: 2pt 8pt; color: #333; }
pre { background: #f4f4f4; border: 1px solid #ccc; padding: 6pt; font-family: "DejaVu Sans Mono", monospace; font-size: 9pt; white-space: pre-wrap; }
code { font-family: "DejaVu Sans Mono", monospace; font-size: 9.5pt; }
hr { border: 0; border-top: 1px solid #888; margin: 10pt 0; }
"""

def inline(s):
    s = html.escape(s, quote=False)
    s = re.sub(r'`([^`]+)`', r'<code>\1</code>', s)
    s = re.sub(r'\*\*([^*]+)\*\*', r'<strong>\1</strong>', s)
    s = re.sub(r'(?<!\*)\*([^*]+)\*(?!\*)', r'<em>\1</em>', s)
    return s

def is_table_sep(line):
    return bool(re.match(r'^\s*\|?[\s:\-\|]+\|?\s*$', line)) and '-' in line

def convert(md):
    lines = md.splitlines()
    out = []
    i = 0
    while i < len(lines):
        line = lines[i].rstrip()
        if not line.strip():
            i += 1; continue
        # fenced code
        if line.strip().startswith('```'):
            i += 1; code=[]
            while i < len(lines) and not lines[i].strip().startswith('```'):
                code.append(lines[i]); i += 1
            i += 1
            out.append('<pre>'+html.escape('\n'.join(code))+'</pre>')
            continue
        # heading
        m = re.match(r'^(#{1,4})\s+(.*)$', line)
        if m:
            lvl=len(m.group(1)); out.append(f'<h{lvl}>{inline(m.group(2))}</h{lvl}>'); i += 1; continue
        # hr
        if re.match(r'^\s*---+\s*$', line):
            out.append('<hr>'); i += 1; continue
        # table
        if '|' in line and i+1 < len(lines) and is_table_sep(lines[i+1]):
            header = [c.strip() for c in line.strip().strip('|').split('|')]
            i += 2
            rows=[]
            while i < len(lines) and '|' in lines[i] and lines[i].strip():
                rows.append([c.strip() for c in lines[i].strip().strip('|').split('|')]); i += 1
            out.append('<table><thead><tr>'+''.join(f'<th>{inline(c)}</th>' for c in header)+'</tr></thead><tbody>')
            for r in rows:
                out.append('<tr>'+''.join(f'<td>{inline(c)}</td>' for c in r)+'</tr>')
            out.append('</tbody></table>')
            continue
        # list
        if re.match(r'^\s*[-*+]\s+', line):
            items=[]
            while i < len(lines) and re.match(r'^\s*[-*+]\s+', lines[i]):
                items.append(re.sub(r'^\s*[-*+]\s+','',lines[i])); i += 1
            out.append('<ul>'+''.join(f'<li>{inline(x)}</li>' for x in items)+'</ul>')
            continue
        if re.match(r'^\s*\d+[.)、]\s+', line):
            items=[]
            while i < len(lines) and re.match(r'^\s*\d+[.)、]\s+', lines[i]):
                items.append(re.sub(r'^\s*\d+[.)、]\s+','',lines[i])); i += 1
            out.append('<ol>'+''.join(f'<li>{inline(x)}</li>' for x in items)+'</ol>')
            continue
        # blockquote
        if line.startswith('>'):
            q=[]
            while i < len(lines) and lines[i].startswith('>'):
                q.append(lines[i].lstrip('>').strip()); i += 1
            out.append('<blockquote>'+inline(' '.join(q))+'</blockquote>')
            continue
        # paragraph: gather until blank/special
        para=[line.strip()]
        i += 1
        while i < len(lines) and lines[i].strip() and not re.match(r'^(#{1,4})\s+', lines[i]) and not lines[i].strip().startswith('```') and not re.match(r'^\s*[-*+]\s+', lines[i]) and not re.match(r'^\s*\d+[.)、]\s+', lines[i]) and not lines[i].startswith('>'):
            para.append(lines[i].strip()); i += 1
        out.append('<p>'+inline(' '.join(para)).replace('\n','<br>')+'</p>')
    return '<!DOCTYPE html><html><head><meta charset="utf-8"><style>'+CSS+'</style></head><body>'+'\n'.join(out)+'</body></html>'

def main():
    if len(sys.argv) != 3:
        print('usage: 00_md2html.py input.md output.html'); sys.exit(2)
    src=pathlib.Path(sys.argv[1]); dst=pathlib.Path(sys.argv[2])
    dst.write_text(convert(src.read_text(encoding='utf-8')),encoding='utf-8')
    print('saved',dst)

if __name__=='__main__': main()
