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('--format', choices=['docx','html','pdf'], default='docx', help='批量输出格式')
    parser.add_argument('--reverse', action='store_true', help='DOCX 批量转为 Markdown（生成同名 zip）')
    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='静默子进程输出')
    parser.add_argument('-c','--config', help='配置文件路径（JSON），未提供则尝试当前目录 HOS_M2F.config.json', default='')
    args = parser.parse_args()

    inp = Path(args.input_dir)
    outp = Path(args.output_dir)
    outp.mkdir(parents=True, exist_ok=True)
    def _is_docx(p: Path):
        return p.suffix.lower() == '.docx'
    files = [p for p in inp.rglob('*') if p.is_file() and (_is_md(p) if not args.reverse else _is_docx(p))]
    total = len(files)
    if total == 0:
        print('No markdown files found.')
        return
    import json as _json
    company_cfg = None
    if args.config:
        try:
            company_cfg = _json.loads(Path(args.config).read_text(encoding='utf-8'))
        except Exception:
            company_cfg = None
    else:
        p0 = Path.cwd() / 'HOS_M2F.config.json'
        if p0.exists():
            try:
                company_cfg = _json.loads(p0.read_text(encoding='utf-8'))
            except Exception:
                company_cfg = None
    for idx, f in enumerate(files, start=1):
        name = f.name
        def cb(pct):
            _print_progress(name, pct, idx, total)
        if args.reverse:
            from hos_m2f.docx2md import convert_docx_to_md
            tgt = outp / (f.stem + '.md')
            convert_docx_to_md(f, tgt)
            _print_progress(name, 100, idx, total)
            sys.stdout.write('\n'); sys.stdout.flush()
            continue
        text = f.read_text(encoding='utf-8')
        if args.format == 'docx':
            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,
                    company_cfg=company_cfg,
                    source_md_path=f,
                )
                tgt = outp / (f.stem + '.docx')
                doc.save(str(tgt))
        elif args.format == 'html':
            import subprocess as sp, sys as _sys
            tgt = outp / (f.stem + '.html')
            sp.run([_sys.executable, '-m', 'hos_m2f.md2html', str(f), str(tgt), '-p', 'wx'], check=True)
        elif args.format == 'pdf':
            import subprocess as sp, sys as _sys
            tgt = outp / (f.stem + '.pdf')
            sp.run([_sys.executable, '-m', 'hos_m2f.md2pdf', str(f), str(tgt)], check=True)
        _print_progress(name, 100, idx, total)
        sys.stdout.write('\n')
        sys.stdout.flush()
    print(f'Processed {total} files -> {outp}')

if __name__ == '__main__':
    main()
