# -*- coding: utf-8 -*-
"""
Word转PDF转换器
使用Microsoft Word COM对象进行转换，保持最佳格式
"""

import sys
import os
import json


def word_to_pdf(word_path, pdf_path):
    """
    将Word文档转换为PDF
    :param word_path: Word文档路径
    :param pdf_path: 输出PDF路径
    :return: dict 转换结果
    """
    result = {'success': False, 'msg': ''}
    
    # 检查输入文件是否存在
    if not os.path.exists(word_path):
        result['msg'] = f"Word文件不存在: {word_path}"
        return result
    
    # 确保输出目录存在
    output_dir = os.path.dirname(pdf_path)
    if output_dir and not os.path.exists(output_dir):
        os.makedirs(output_dir, exist_ok=True)
    
    try:
        # 使用win32com.client调用Microsoft Word
        import win32com.client as win32
        
        word = win32.DispatchEx('Word.Application')
        word.Visible = False
        word.DisplayAlerts = 0  # 不显示警告对话框
        
        try:
            doc = word.Documents.Open(word_path)
            
            # 检查是否需要先保存（处理临时文件）
            if doc.Saved == False:
                doc.Save()
            
            # 转换为PDF
            doc.ExportAsFixedFormat(
                OutputFileName=pdf_path,
                ExportFormat=17,  # wdExportFormatPDF
                OpenAfterExport=False,
                OptimizeFor=0,  # wdExportOptimizeForPrint
                Range=0,  # wdExportAllDocument
                Item=0,  # wdExportDocumentContent
                IncludeDocProps=True,
                KeepIRM=True,
                CreateBookmarks=0,  # wdExportCreateNoBookmarks
                DocStructureTags=True,
                BitmapMissingFonts=True,
                UseISO19005_1=False
            )
            
            doc.Close(SaveChanges=0)  # wdDoNotSaveChanges
            
            # 检查PDF是否生成成功
            if os.path.exists(pdf_path):
                result['success'] = True
                result['msg'] = '转换成功'
            else:
                result['msg'] = 'PDF文件未生成'
                
        except Exception as e:
            result['msg'] = f"Word处理错误: {str(e)}"
        finally:
            word.Quit()
            
    except ImportError:
        result['msg'] = '缺少pywin32库，请安装: pip install pywin32'
    except Exception as e:
        result['msg'] = f"转换失败: {str(e)}"
    
    return result


def main():
    if len(sys.argv) != 3:
        print(json.dumps({'success': False, 'msg': '参数错误: 需要word_path和pdf_path'}))
        sys.exit(1)
    
    word_path = sys.argv[1]
    pdf_path = sys.argv[2]
    
    result = word_to_pdf(word_path, pdf_path)
    print(json.dumps(result, ensure_ascii=False))


if __name__ == '__main__':
    main()