#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""简易 Markdown → DOCX（面向学生资料：标题、段落、列表、表格、引用、粗体）"""
import re, sys
from docx import Document
from docx.shared import Pt, Cm, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml.ns import qn
from docx.oxml import OxmlElement

BLUE = RGBColor(0x1F, 0x3B, 0x63)


def _font(run, name="宋体", size=10.5, bold=False, color=None):
    run.font.name = name
    run.font.size = Pt(size)
    run.font.bold = bold
    if color is not None:
        run.font.color.rgb = color
    rPr = run._element.get_or_add_rPr()
    rf = rPr.find(qn("w:rFonts"))
    if rf is None:
        rf = OxmlElement("w:rFonts"); rPr.append(rf)
    rf.set(qn("w:ascii"), "Times New Roman")
    rf.set(qn("w:hAnsi"), "Times New Roman")
    rf.set(qn("w:eastAsia"), name)


def _rich(p, text, size=10.5, bold_all=False):
    """支持 **粗体** 行内标记"""
    parts = re.split(r"(\*\*.+?\*\*)", text)
    for part in parts:
        if not part:
            continue
        if part.startswith("**") and part.endswith("**"):
            r = p.add_run(part[2:-2]); _font(r, "宋体", size, True)
        else:
            r = p.add_run(part); _font(r, "宋体", size, bold_all)


def _shade(cell, hexcolor):
    tcPr = cell._tc.get_or_add_tcPr()
    shd = OxmlElement("w:shd")
    shd.set(qn("w:val"), "clear"); shd.set(qn("w:color"), "auto"); shd.set(qn("w:fill"), hexcolor)
    tcPr.append(shd)


def _cell(cell, text, size=9, bold=False, align="left"):
    cell.text = ""
    p = cell.paragraphs[0]
    p.paragraph_format.space_before = Pt(1)
    p.paragraph_format.space_after = Pt(1)
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER if align == "center" else WD_ALIGN_PARAGRAPH.LEFT
    _rich(p, text.strip(), size=size, bold_all=bold)


def md2docx(md_path, out_path, title="", subtitle=""):
    lines = open(md_path, encoding="utf-8").read().split("\n")
    doc = Document()
    s = doc.sections[0]
    s.page_width, s.page_height = Cm(21.0), Cm(29.7)
    s.left_margin = s.right_margin = Cm(2.4)
    s.top_margin, s.bottom_margin = Cm(2.2), Cm(2.0)
    s.header_distance, s.footer_distance = Cm(1.2), Cm(1.4)
    st = doc.styles["Normal"]
    st.font.name = "宋体"; st.font.size = Pt(10.5)
    st.element.rPr.rFonts.set(qn("w:eastAsia"), "宋体")
    st.paragraph_format.line_spacing = 1.4

    # 页脚页码
    fp = s.footer.paragraphs[0]
    fp.alignment = WD_ALIGN_PARAGRAPH.CENTER
    r = fp.add_run("第 "); _font(r, "宋体", 9)
    rf = fp.add_run(); f1 = OxmlElement("w:fldChar"); f1.set(qn("w:fldCharType"), "begin")
    it = OxmlElement("w:instrText"); it.set(qn("xml:space"), "preserve"); it.text = "PAGE"
    f2 = OxmlElement("w:fldChar"); f2.set(qn("w:fldCharType"), "separate")
    t = OxmlElement("w:t"); t.text = "1"
    f3 = OxmlElement("w:fldChar"); f3.set(qn("w:fldCharType"), "end")
    rf._r.append(f1); rf._r.append(it); rf._r.append(f2); rf._r.append(t); rf._r.append(f3)
    _font(rf, "宋体", 9)
    r = fp.add_run(" 页"); _font(r, "宋体", 9)

    i = 0
    n = len(lines)
    first_h1 = True
    while i < n:
        line = lines[i].rstrip("\n")
        if not line.strip():
            i += 1; continue
        # 表格
        if line.lstrip().startswith("|") and i + 1 < n and re.match(r"^\s*\|[\s:|-]+\|\s*$", lines[i+1]):
            rows = []
            while i < n and lines[i].lstrip().startswith("|"):
                rows.append(lines[i]); i += 1
            cells = [[c.strip() for c in r.strip().strip("|").split("|")] for r in rows]
            head, body = cells[0], [r for r in cells[2:]]
            ncol = len(head)
            t = doc.add_table(rows=1 + len(body), cols=ncol)
            t.style = "Table Grid"; t.alignment = WD_TABLE_ALIGNMENT.CENTER
            # 按内容长度分配列宽
            widths = []
            for j in range(ncol):
                lens = [len(head[j]) if j < len(head) else 0] +                        [len(r[j]) if j < len(r) else 0 for r in body]
                widths.append(max(4, sum(lens) / max(1, len(lens))))
            tot = sum(widths)
            avail = 16.2
            cm = [max(1.6, avail * w / tot) for w in widths]
            k = avail / sum(cm)
            cm = [c * k for c in cm]
            t.autofit = False
            tbl = t._tbl
            for gi, gc in enumerate(tbl.tblGrid.findall(qn("w:gridCol"))):
                gc.set(qn("w:w"), str(int(Cm(cm[gi]).twips)))
            for row in t.rows:
                for gi, cell in enumerate(row.cells):
                    cell.width = Cm(cm[gi])
            for j, h in enumerate(head):
                _cell(t.cell(0, j), h, 9, True, "center"); _shade(t.cell(0, j), "E8EEF7")
            for ri, row in enumerate(body, 1):
                for j in range(ncol):
                    _cell(t.cell(ri, j), row[j] if j < len(row) else "", 9,
                          align="center" if j > 0 and len(row[j]) <= 12 else "left")
            doc.add_paragraph().paragraph_format.space_after = Pt(2)
            continue
        # 标题
        m = re.match(r"^(#{1,4})\s+(.*)$", line)
        if m:
            level, text = len(m.group(1)), m.group(2).strip()
            if level == 1:
                p = doc.add_paragraph(); p.alignment = WD_ALIGN_PARAGRAPH.CENTER
                r = p.add_run(text); _font(r, "黑体", 18, True, BLUE)
                p.paragraph_format.space_after = Pt(4)
                if first_h1:
                    first_h1 = False
            elif level == 2:
                p = doc.add_paragraph()
                p.paragraph_format.space_before = Pt(12); p.paragraph_format.space_after = Pt(4)
                r = p.add_run(text); _font(r, "黑体", 14, True, BLUE)
                # 下边框
                pPr = p._p.get_or_add_pPr(); pbdr = OxmlElement("w:pBdr")
                bottom = OxmlElement("w:bottom")
                bottom.set(qn("w:val"), "single"); bottom.set(qn("w:sz"), "8")
                bottom.set(qn("w:space"), "2"); bottom.set(qn("w:color"), "1F3B63")
                pbdr.append(bottom); pPr.append(pbdr)
            elif level == 3:
                p = doc.add_paragraph()
                p.paragraph_format.space_before = Pt(8); p.paragraph_format.space_after = Pt(2)
                r = p.add_run(text); _font(r, "黑体", 12, True, RGBColor(0x2E, 0x5C, 0x8A))
            else:
                p = doc.add_paragraph()
                p.paragraph_format.space_before = Pt(6)
                r = p.add_run(text); _font(r, "黑体", 10.5, True)
            i += 1; continue
        # 分隔线
        if re.match(r"^-{3,}$", line.strip()):
            p = doc.add_paragraph()
            pPr = p._p.get_or_add_pPr(); pbdr = OxmlElement("w:pBdr")
            bottom = OxmlElement("w:bottom")
            bottom.set(qn("w:val"), "dashed"); bottom.set(qn("w:sz"), "6")
            bottom.set(qn("w:space"), "1"); bottom.set(qn("w:color"), "BBBBBB")
            pbdr.append(bottom); pPr.append(pbdr)
            p.paragraph_format.space_before = Pt(4); p.paragraph_format.space_after = Pt(6)
            i += 1; continue
        # 引用
        if line.startswith(">"):
            p = doc.add_paragraph()
            p.paragraph_format.left_indent = Cm(0.4)
            p.paragraph_format.space_before = Pt(2); p.paragraph_format.space_after = Pt(2)
            _rich(p, line.lstrip("> ").strip(), size=9.5)
            for r in p.runs:
                r.font.color.rgb = RGBColor(0x55, 0x55, 0x55)
            i += 1; continue
        # 列表
        m = re.match(r"^(\s*)[-*]\s+(.*)$", line)
        if m:
            indent = len(m.group(1)) // 2
            p = doc.add_paragraph()
            p.paragraph_format.left_indent = Cm(0.6 + 0.6 * indent)
            p.paragraph_format.first_line_indent = Cm(-0.4)
            p.paragraph_format.space_before = Pt(1); p.paragraph_format.space_after = Pt(1)
            p.add_run("• "); _rich(p, m.group(2).strip())
            i += 1; continue
        m = re.match(r"^(\d+)\.\s+(.*)$", line)
        if m:
            p = doc.add_paragraph()
            p.paragraph_format.left_indent = Cm(0.7)
            p.paragraph_format.first_line_indent = Cm(-0.5)
            p.paragraph_format.space_before = Pt(1); p.paragraph_format.space_after = Pt(1)
            p.add_run(f"{m.group(1)}. "); _rich(p, m.group(2).strip())
            i += 1; continue
        # 普通段落
        p = doc.add_paragraph()
        p.paragraph_format.space_before = Pt(2); p.paragraph_format.space_after = Pt(2)
        _rich(p, line.strip())
        i += 1

    doc.save(out_path)
    return out_path


if __name__ == "__main__":
    src, dst = sys.argv[1], sys.argv[2]
    print(md2docx(src, dst))
