import sys
import tempfile
from pathlib import Path
from .md2json import parse_to_model

def _css(profile: str):
    p = (profile or '').lower()
    base = "body{margin:16px;font-size:16px;line-height:1.75;} img{max-width:100%;height:auto;} pre{background:#f6f6f6;padding:12px;overflow:auto;} code{font-family:Consolas,monospace;} h1,h2,h3{margin:1em 0 0.5em;} ul,ol{margin:0.5em 0 0.5em 1.5em;}"
    if p == 'wx':
        return base + " p{word-break:break-word;}"
    if p == 'csdn':
        return base + " pre{background:#2b2b2b;color:#ddd;}"
    return base

def render_html(model, profile: str):
    css = _css(profile)
    out = ["<html><head><meta charset=\"utf-8\"><style>" + css + "</style></head><body>"]
    for b in model['blocks']:
        t = b['type']
        if t == 'heading':
            lvl = int(b.get('level',1))
            lvl = 1 if lvl < 1 else 6 if lvl > 6 else lvl
            out.append(f"<h{lvl}>" + b.get('text','') + f"</h{lvl}>")
        elif t == 'text':
            out.append("<p>" + b.get('text','') + "</p>")
        elif t == 'list':
            out.append("<p>• " + b.get('text','') + "</p>")
        elif t == 'code':
            s = b.get('text','').replace('&','&amp;').replace('<','&lt;').replace('>','&gt;')
            out.append("<pre><code>" + s + "</code></pre>")
        elif t == 'image':
            p = b.get('path','')
            if p:
                out.append(f"<p><img src=\"{p}\"/></p>")
        elif t == 'table':
            hdr = b.get('header',[])
            rows = b.get('rows',[])
            out.append("<table>")
            if hdr:
                out.append("<thead><tr>" + ''.join([f"<th>{c}</th>" for c in hdr]) + "</tr></thead>")
            for r in rows:
                out.append("<tr>" + ''.join([f"<td>{c}</td>" for c in r]) + "</tr>")
            out.append("</table>")
    out.append("</body></html>")
    return "".join(out)

def main():
    import argparse
    parser = argparse.ArgumentParser(
        prog='HOS_M2F.2html',
        description='Markdown 转 HTML，支持博客样式',
        epilog=(
            '示例:\n'
            '  HOS_M2F.2html input.md output.html [-p wx|csdn]\n'
            '相关命令:\n'
            '  HOS_M2F.2docx input.md output.docx [-p paper|patent|softcopy] [-nm] [-nc] [-q]\n'
            '  HOS_M2F.2pdf  input.md output.pdf\n'
            '  HOS_M2F.2json input.md output.json\n'
            '  HOS_M2F.2xml  input.md output.xml\n'
            '  HOS_M2F.2png  input.mmd output.png\n'
        ),
        formatter_class=argparse.RawTextHelpFormatter,
    )
    parser.add_argument('input', help='输入 Markdown 文件路径')
    parser.add_argument('output', help='输出 HTML 文件路径')
    parser.add_argument('-p','--profile', choices=['wx','csdn'], default='', help='博客样式配置')
    args = parser.parse_args()
    inp = Path(args.input)
    outp = Path(args.output)
    text = inp.read_text(encoding='utf-8')
    with tempfile.TemporaryDirectory() as td:
        model = parse_to_model(text, Path(td))
        html = render_html(model, args.profile)
        outp.write_text(html, encoding='utf-8')
    print(f'Converted to HTML: {inp} -> {outp}')

if __name__ == '__main__':
    main()
