#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""把练习题 md 转成可导入题库的 .docx（纯标准库，无需 python-docx）。

用法：python3 make_docx.py <in.md> [out.docx]
规则：
  - `# 标题`        → 居中加粗大标题
  - `> 说明`        → 灰色小字
  - 其余非空行      → 正文段落（宋体/Times New Roman，小四＝12pt）
  - 空行           → 空段落（保留题块间距）
"""
import sys, zipfile, re
from xml.sax.saxutils import escape

CT = '''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
</Types>'''

RELS = '''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>'''

DOC_RELS = '''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
</Relationships>'''

STYLES = '''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:docDefaults><w:rPrDefault><w:rPr>
<w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" w:eastAsia="宋体" w:cs="Times New Roman"/>
<w:sz w:val="24"/><w:szCs w:val="24"/><w:lang w:val="en-US" w:eastAsia="zh-CN"/>
</w:rPr></w:rPrDefault>
<w:pPrDefault><w:pPr><w:spacing w:after="60" w:line="300" w:lineRule="auto"/></w:pPr></w:pPrDefault>
</w:docDefaults>
<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>
</w:styles>'''


def para(text, bold=False, size=24, color=None, align=None, spacing=None):
    ppr = ''
    inner = ''
    if align:
        ppr += f'<w:jc w:val="{align}"/>'
    if spacing is not None:
        ppr += f'<w:spacing w:after="{spacing}"/>'
    if color:
        inner += f'<w:color w:val="{color}"/>'
    if bold:
        inner += '<w:b/><w:bCs/>'
    if size:
        inner += f'<w:sz w:val="{size}"/><w:szCs w:val="{size}"/>'
    rpr = f'<w:rPr>{inner}</w:rPr>' if inner else ''
    ppr_xml = f'<w:pPr>{ppr}</w:pPr>' if ppr else ''
    return (f'<w:p>{ppr_xml}<w:r>{rpr}'
            f'<w:t xml:space="preserve">{escape(text)}</w:t></w:r></w:p>')


def build(md_path, out_path):
    lines = open(md_path, encoding='utf-8').read().splitlines()
    body = []
    for ln in lines:
        s = ln.rstrip()
        if not s.strip():
            body.append(para('', spacing=60))
            continue
        if s.startswith('# '):
            body.append(para(s[2:].strip(), bold=True, size=32, align='center', spacing=120))
        elif s.startswith('> '):
            body.append(para(s[2:].strip(), size=18, color='666666', spacing=60))
        elif s.startswith('## '):
            body.append(para(s[3:].strip(), bold=True, size=26, spacing=80))
        else:
            body.append(para(s))
    doc = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
           '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
           '<w:body>' + ''.join(body) +
           '<w:sectPr><w:pgSz w:w="11906" w:h="16838"/>'
           '<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" '
           'w:header="851" w:footer="992" w:gutter="0"/></w:sectPr>'
           '</w:body></w:document>')
    with zipfile.ZipFile(out_path, 'w', zipfile.ZIP_DEFLATED) as z:
        z.writestr('[Content_Types].xml', CT)
        z.writestr('_rels/.rels', RELS)
        z.writestr('word/_rels/document.xml.rels', DOC_RELS)
        z.writestr('word/document.xml', doc)
        z.writestr('word/styles.xml', STYLES)
    print('已生成：', out_path)


if __name__ == '__main__':
    src = sys.argv[1]
    dst = sys.argv[2] if len(sys.argv) > 2 else re.sub(r'\.md$', '.docx', src)
    build(src, dst)
