#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
将高校舆情分析 Markdown 报告转换为 Word 文档（A4 公文格式）
严格遵循：上37mm/下35mm/左28mm/右26mm，小标宋标题+黑体章标题+楷体节标题+仿宋正文
"""

import re
import sys
from docx import Document
from docx.shared import Pt, Cm, Mm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn


def set_paragraph_format(p, is_title=False, is_heading1=False, is_heading2=False, is_heading3=False, is_reference=False):
    """设置段落格式"""
    # 行距固定值 28 磅
    p.paragraph_format.line_spacing = Pt(28)
    p.paragraph_format.line_spacing_rule = 3  # 固定值

    if is_title:
        p.paragraph_format.space_before = Pt(56)  # 首行下空二行
        p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
        p.paragraph_format.first_line_indent = Pt(0)
    elif is_heading1:
        p.paragraph_format.space_before = Pt(12)
        p.paragraph_format.space_after = Pt(12)
        p.paragraph_format.first_line_indent = Pt(0)
    elif is_heading2:
        p.paragraph_format.space_before = Pt(6)
        p.paragraph_format.space_after = Pt(6)
        p.paragraph_format.first_line_indent = Pt(0)
    else:
        # 正文：首行缩进 2 字符
        p.paragraph_format.first_line_indent = Pt(32)  # 3号字16磅 × 2 = 32磅
        p.paragraph_format.space_before = Pt(0)
        p.paragraph_format.space_after = Pt(0)

    if is_reference:
        p.paragraph_format.first_line_indent = Pt(0)


def set_font(run, font_name='FangSong', font_size=Pt(16), is_bold=False):
    """设置字体格式"""
    run.font.name = font_name
    run.font.size = font_size
    run.font.bold = is_bold
    run._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)


def markdown_to_word(md_file, docx_file):
    """将 Markdown 文件转换为 Word 文档（公文格式）"""

    with open(md_file, 'r', encoding='utf-8') as f:
        content = f.read()

    doc = Document()

    # 页面布局：A4，页边距上37mm/下35mm/左28mm/右26mm
    section = doc.sections[0]
    section.page_width = Cm(21)
    section.page_height = Cm(29.7)
    section.top_margin = Mm(37)
    section.bottom_margin = Mm(35)
    section.left_margin = Mm(28)
    section.right_margin = Mm(26)

    # 默认字体：3号仿宋（16磅）
    style = doc.styles['Normal']
    font = style.font
    font.name = 'FangSong'
    font.size = Pt(16)
    style._element.rPr.rFonts.set(qn('w:eastAsia'), 'FangSong')
    style.paragraph_format.line_spacing = Pt(28)
    style.paragraph_format.line_spacing_rule = 3

    lines = content.split('\n')
    i = 0
    title_written = False
    in_references = False

    while i < len(lines):
        line = lines[i].strip()

        # 跳过空行
        if not line:
            i += 1
            continue

        # 跳过元信息行（---, **报告日期** 等）
        if line == '---' or line.startswith('**报告日期') or line.startswith('**编制时间') or line.startswith('**密级') or line.startswith('**事件数量'):
            i += 1
            continue

        # 跳过 HTML 标签
        if '<span' in line or '</span>' in line:
            line = re.sub(r'<span[^>]*></span>', '', line)

        # 报告标题（# 开头）
        if line.startswith('# ') and not line.startswith('## '):
            if not title_written:
                p = doc.add_paragraph()
                set_paragraph_format(p, is_title=True)
                text = line[2:].strip()
                run = p.add_run(text)
                set_font(run, font_name='XiaoBiaoSong', font_size=Pt(22), is_bold=True)
                title_written = True
            i += 1
            continue

        # 一级标题（## 开头）→ 黑体章标题
        if line.startswith('## ') and not line.startswith('### '):
            text = line[3:].strip()
            # 判断是否是参考文献章节
            if '参考文献' in text:
                in_references = True
            p = doc.add_paragraph()
            set_paragraph_format(p, is_heading1=True)
            run = p.add_run(text)
            set_font(run, font_name='SimHei', font_size=Pt(16), is_bold=True)
            i += 1
            continue

        # 二级标题（### 开头）→ 楷体节标题 （一）（二）（三）
        if line.startswith('### '):
            text = line[4:].strip()
            p = doc.add_paragraph()
            set_paragraph_format(p, is_heading2=True)
            run = p.add_run(text)
            set_font(run, font_name='KaiTi', font_size=Pt(16), is_bold=False)
            i += 1
            continue

        # 列表项
        if line.startswith('- ') or line.startswith('* '):
            p = doc.add_paragraph()
            set_paragraph_format(p, is_reference=in_references)
            text = line[2:].strip()
            text = text.replace('**', '')
            run = p.add_run('  ' + text)
            font_size = Pt(14) if in_references else Pt(16)
            set_font(run, font_name='FangSong', font_size=font_size)
            i += 1
            continue

        # 普通段落
        p = doc.add_paragraph()
        is_ref = in_references
        set_paragraph_format(p, is_reference=is_ref)

        text = line.replace('**', '')

        # 处理角标
        for n in range(1, 30):
            circled = chr(0x2460 + n - 1)  # ①②③...
            text = text.replace(circled, circled)

        font_size = Pt(14) if is_ref else Pt(16)
        run = p.add_run(text)
        set_font(run, font_name='FangSong', font_size=font_size)

        i += 1

    doc.save(docx_file)
    print(f'转换完成：{docx_file}')
    return docx_file


if __name__ == '__main__':
    if len(sys.argv) >= 3:
        md_file = sys.argv[1]
        docx_file = sys.argv[2]
    else:
        print('用法：python3 md2docx.py <input.md> <output.docx>')
        sys.exit(1)

    markdown_to_word(md_file, docx_file)
