#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
将 Markdown 报告转换为 Word 文档（严格按照公文格式）
"""

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):
    """设置段落格式"""
    # 行距固定值 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)  # 约 2 行
        p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    elif is_heading1:
        # 第一层标题：3 号黑体
        p.paragraph_format.space_before = Pt(12)
        p.paragraph_format.space_after = Pt(12)
    elif is_heading2:
        # 第二层标题：3 号楷体
        p.paragraph_format.space_before = Pt(6)
        p.paragraph_format.space_after = Pt(6)
    else:
        # 正文：首行缩进 2 字符
        p.paragraph_format.first_line_indent = Pt(21)  # 约 2 字符（3 号字约 10.5 磅，2 字符约 21 磅）
        p.paragraph_format.space_before = Pt(0)
        p.paragraph_format.space_after = Pt(0)

def set_font(run, font_name='SimSun', 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 文档（公文格式）"""
    
    # 读取 Markdown 文件
    with open(md_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 创建 Word 文档
    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 号仿宋（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')
    
    # 行距固定值 28 磅
    style.paragraph_format.line_spacing = Pt(28)
    style.paragraph_format.line_spacing_rule = 3
    
    lines = content.split('\n')
    i = 0
    title_written = False
    
    while i < len(lines):
        line = lines[i].strip()
        
        # 跳过空行
        if not line:
            i += 1
            continue
        
        # 跳过 span 标签
        if '<span' in line or '</span>' in line:
            line = re.sub(r'<span[^>]*></span>', '', line)
        
        # 处理报告标题（第一行非空内容）
        if not title_written and not line.startswith('#'):
            p = doc.add_paragraph()
            set_paragraph_format(p, is_title=True)
            run = p.add_run(line)
            set_font(run, font_name='XiaoBiaoSong', font_size=Pt(22), is_bold=True)  # 2 号=22 磅
            title_written = True
            i += 1
            continue
        
        # 处理 Markdown 一级标题（## ）→ 第一层标题"一、"
        if line.startswith('## '):
            p = doc.add_paragraph()
            set_paragraph_format(p, is_heading1=True)
            text = line[3:]
            run = p.add_run(text)
            set_font(run, font_name='SimHei', font_size=Pt(16), is_bold=True)  # 3 号=16 磅
            i += 1
            continue
        
        # 处理 Markdown 二级标题（### ）→ 第二层标题"（一）"
        if line.startswith('### '):
            p = doc.add_paragraph()
            set_paragraph_format(p, is_heading2=True)
            text = line[4:]
            run = p.add_run(text)
            set_font(run, font_name='KaiTi', font_size=Pt(16), is_bold=False)  # 3 号楷体
            i += 1
            continue
        
        # 处理 Markdown 三级标题（#### ）→ 第三层标题"1."
        if line.startswith('#### '):
            p = doc.add_paragraph()
            set_paragraph_format(p)
            text = line[5:]
            run = p.add_run(text)
            set_font(run, font_name='FangSong', font_size=Pt(16), is_bold=False)
            i += 1
            continue
        
        # 处理列表项（- 或 * 开头）
        if line.startswith('- ') or line.startswith('* '):
            p = doc.add_paragraph()
            set_paragraph_format(p)
            text = line[2:]
            # 检查是否包含第三层标记
            if re.match(r'^\d+\.', text):
                run = p.add_run(text)
                set_font(run, font_name='FangSong', font_size=Pt(16))
            else:
                run = p.add_run('  ' + text)  # 缩进
                set_font(run, font_name='FangSong', font_size=Pt(16))
            i += 1
            continue
        
        # 处理普通段落（正文）
        p = doc.add_paragraph()
        set_paragraph_format(p)
        
        # 处理文本中的粗体标记
        text = line.replace('**', '')
        # 处理角标（①②③等）
        text = re.sub(r'①', '①', text)
        text = re.sub(r'②', '②', text)
        text = re.sub(r'③', '③', text)
        text = re.sub(r'④', '④', text)
        text = re.sub(r'⑤', '⑤', text)
        text = re.sub(r'⑥', '⑥', text)
        text = re.sub(r'⑦', '⑦', text)
        text = re.sub(r'⑧', '⑧', text)
        text = re.sub(r'⑨', '⑨', text)
        
        run = p.add_run(text)
        set_font(run, font_name='FangSong', font_size=Pt(16))
        
        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:
        md_file = "/home/admin/.openclaw/workspace/reports/justice-mission/briefings/2026-03-13-美以伊冲突舆情简报.md"
        docx_file = "/home/admin/.openclaw/workspace/reports/justice-mission/briefings/2026-03-13-美以伊冲突舆情简报.docx"
    
    markdown_to_word(md_file, docx_file)
