import sys
import os
from pathlib import Path
import tempfile
from .md2docx_mermaid import parse as parse_docx

def _print_progress(name: str, percent: int, idx: int, total: int):
    w = 30
    done = int(percent * w / 100)
    bar = '#' * done + '.' * (w - done)
    msg = f"[{bar}] {percent:3d}% | {idx}/{total} | {name}"
    sys.stdout.write('\r' + msg)
    sys.stdout.flush()

def _is_md(p: Path):
    return p.suffix.lower() in ['.md', '.markdown']

def main():
    import argparse
    parser = argparse.ArgumentParser(
        prog='HOS_M2F.batch',
        description='批量将文件夹中的 Markdown 转为 DOCX（带进度）',
        epilog=(
            '示例:\n'
            '  HOS_M2F.batch input_dir output_dir [-p paper|patent|softcopy] [-nm] [-nc] [-q]\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.2xml  input.md output.xml\n'
            '  HOS_M2F.2png  input.mmd output.png\n'
        ),
    )
    parser.add_argument('input_dir', help='输入文件夹路径')
    parser.add_argument('output_dir', help='输出文件夹路径')
    parser.add_argument('-p','--profile', choices=['paper','patent','softcopy'], default='', help='DOCX 样式配置')
    parser.add_argument('-nm','--no-mermaid', action='store_true', help='禁用 Mermaid 渲染')
    parser.add_argument('-nc','--no-run-code', action='store_true', help='禁用代码执行（Matplotlib/表格）')
    parser.add_argument('-q','--quiet', action='store_true', help='静默子进程输出')
    args = parser.parse_args()

    inp = Path(args.input_dir)
    outp = Path(args.output_dir)
    outp.mkdir(parents=True, exist_ok=True)
    files = [p for p in inp.rglob('*') if p.is_file() and _is_md(p)]
    total = len(files)
    if total == 0:
        print('No markdown files found.')
        return
    for idx, f in enumerate(files, start=1):
        name = f.name
        def cb(pct):
            _print_progress(name, pct, idx, total)
        text = f.read_text(encoding='utf-8')
        with tempfile.TemporaryDirectory() as td:
            doc = parse_docx(
                text,
                Path(td),
                profile=args.profile,
                run_code=(not args.no_run_code),
                render_mermaid=(not args.no_mermaid),
                quiet=args.quiet,
                progress_cb=cb,
            )
            tgt = outp / (f.stem + '.docx')
            doc.save(str(tgt))
        _print_progress(name, 100, idx, total)
        sys.stdout.write('\n')
        sys.stdout.flush()
    print(f'Processed {total} files -> {outp}')

if __name__ == '__main__':
    main()

