import sys
import tempfile
from pathlib import Path
from .md2json import parse_to_model
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import A4

def main():
    import argparse
    parser = argparse.ArgumentParser(
        prog='HOS_M2F.2pdf',
        description='Markdown 转 PDF',
        epilog=(
            '示例:\n'
            '  HOS_M2F.2pdf input.md output.pdf\n'
            '相关命令:\n'
            '  HOS_M2F.2docx input.md output.docx [-p paper|patent|softcopy] [-nm] [-nc] [-q]\n'
            '  HOS_M2F.2html input.md output.html [-p wx|csdn]\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='输出 PDF 文件路径')
    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))
        styles = getSampleStyleSheet()
        flow = []
        doc = SimpleDocTemplate(str(outp), pagesize=A4)
        page_w, page_h = A4
        max_w = page_w - doc.leftMargin - doc.rightMargin
        for b in model['blocks']:
            t = b['type']
            if t == 'heading':
                lvl = int(b.get('level',1))
                style_name = 'Heading' + str(min(3, lvl))
                st = styles[style_name] if style_name in styles else styles['Heading1']
                flow.append(Paragraph(b.get('text',''), st))
                flow.append(Spacer(1, 8))
            elif t == 'text':
                flow.append(Paragraph(b.get('text',''), styles['BodyText']))
            elif t == 'list':
                flow.append(Paragraph('• ' + b.get('text',''), styles['BodyText']))
            elif t == 'code':
                flow.append(Paragraph('<font face="Courier">' + b.get('text','').replace('&','&amp;').replace('<','&lt;').replace('>','&gt;') + '</font>', styles['BodyText']))
            elif t == 'image':
                p = b.get('path','')
                if p:
                    img = Image(p)
                    img._restrictSize(max_w, page_h * 0.6)
                    flow.append(img)
            elif t == 'table':
                txt = '\n'.join([' | '.join(b.get('header',[]))] + [' | '.join(r) for r in b.get('rows',[])])
                flow.append(Paragraph(txt, styles['BodyText']))
        doc.build(flow)
    print(f'Converted to PDF: {inp} -> {outp}')

if __name__ == '__main__':
    main()
