import sys
import tempfile
from pathlib import Path
import xml.etree.ElementTree as ET
from .md2json import parse_to_model

def main():
    import argparse
    parser = argparse.ArgumentParser(
        prog='HOS_M2F.2xml',
        description='Markdown 转 XML',
        epilog=(
            '示例:\n'
            '  HOS_M2F.2xml input.md output.xml\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.2pdf  input.md output.pdf\n'
            '  HOS_M2F.2json input.md output.json\n'
            '  HOS_M2F.2png  input.mmd output.png\n'
        ),
        formatter_class=argparse.RawTextHelpFormatter,
    )
    parser.add_argument('input', help='输入 Markdown 文件路径')
    parser.add_argument('output', help='输出 XML 文件路径')
    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))
        root = ET.Element('document')
        for b in model['blocks']:
            t = b['type']
            if t == 'heading':
                e = ET.SubElement(root, 'heading')
                e.set('level', str(b.get('level', 1)))
                e.text = b.get('text', '')
            elif t == 'text':
                e = ET.SubElement(root, 'paragraph')
                e.text = b.get('text', '')
            elif t == 'code':
                e = ET.SubElement(root, 'code')
                e.set('lang', b.get('lang',''))
                e.text = b.get('text','')
            elif t == 'image':
                e = ET.SubElement(root, 'image')
                e.set('kind', b.get('kind',''))
                e.set('path', b.get('path',''))
            elif t == 'table':
                e = ET.SubElement(root, 'table')
                h = ET.SubElement(e, 'header')
                for c in b.get('header',[]):
                    ET.SubElement(h,'cell').text = c
                body = ET.SubElement(e,'body')
                for r in b.get('rows',[]):
                    row = ET.SubElement(body,'row')
                    for c in r:
                        ET.SubElement(row,'cell').text = c
            elif t == 'anchor':
                e = ET.SubElement(root, 'anchor')
                e.set('name', b.get('name',''))
            elif t == 'list':
                e = ET.SubElement(root, 'list')
                e.set('kind', b.get('kind',''))
                e.text = b.get('text','')
        tree = ET.ElementTree(root)
        ET.indent(tree, space='  ')
        tree.write(str(outp), encoding='utf-8', xml_declaration=True)
    print(f'Converted to XML: {inp} -> {outp}')

if __name__ == '__main__':
    main()
