#!/usr/bin/env python3
"""
使用 pandoc 将日本旅游指南 Markdown 转换为精美的 Word 文档
支持表格、代码块、标题等格式的完美转换
"""

import subprocess
import os
import shutil
import tempfile

import os

# 文件路径（使用相对路径，基于脚本所在目录）
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
# skills/docx/scripts/ → skills/docx/ → skills/ → 项目根目录
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(SCRIPT_DIR)))
DOCS_DIR = os.path.join(ROOT_DIR, 'docs')

input_md = os.path.join(DOCS_DIR, 'japan-travel-guide.md')
output_docx = os.path.join(DOCS_DIR, 'japan-travel-guide.docx')

# 创建临时目录用于存放资源文件
temp_dir = tempfile.mkdtemp()

try:
    # 方法1：直接使用 pandoc 基本转换
    cmd1 = ['pandoc', input_md, '-f', 'markdown', '-t', 'docx',
            '-o', output_docx,
            '--wrap=preserve',
            '--standalone']

    result1 = subprocess.run(cmd1, capture_output=True, text=True)

    if result1.returncode == 0 and os.path.exists(output_docx):
        print(f"✅ Word 文档已生成: {output_docx}")
        file_size = os.path.getsize(output_docx) / 1024
        print(f"📄 文件大小: {file_size:.1f} KB")
    else:
        print("方法1失败，尝试方法2...")

        # 方法2：使用 pandoc + 自定义引用文档
        # 创建自定义样式
        from docx import Document
        from docx.shared import Pt, Inches, Cm, RGBColor
        from docx.enum.text import WD_ALIGN_PARAGRAPH
        from docx.oxml.ns import qn

        doc = Document()

        # 设置默认样式
        style = doc.styles['Normal']
        style.font.name = 'Calibri'
        style.font.size = Pt(11)

        # 设置标题样式
        for i in range(1, 4):
            heading_style = doc.styles[f'Heading {i}']
            heading_style.font.name = 'Microsoft YaHei'
            heading_style.font.bold = True
            if i == 1:
                heading_style.font.size = Pt(22)
                heading_style.font.color.rgb = RGBColor(0x1a, 0x5c, 0x96)
            elif i == 2:
                heading_style.font.size = Pt(16)
                heading_style.font.color.rgb = RGBColor(0x2e, 0x86, 0xab)
            elif i == 3:
                heading_style.font.size = Pt(13)
                heading_style.font.color.rgb = RGBColor(0x48, 0x9f, 0xad)

        # 读取并解析 markdown 文件
        with open(input_md, 'r', encoding='utf-8') as f:
            content = f.read()

        lines = content.split('\n')
        current_table = []
        in_table = False
        in_code = False

        for i, line in enumerate(lines):
            # 跳过前几行的标题（会在最后单独添加）
            if i == 0 and line.startswith('#'):
                continue

            # 处理代码块
            if line.strip().startswith('```'):
                if not in_code:
                    in_code = True
                else:
                    in_code = False
                continue

            if in_code:
                continue

            # 检测表格
            is_table_line = '|' in line and line.strip().startswith('|')

            if is_table_line:
                if not in_table:
                    in_table = True
                    current_table = []
                current_table.append(line)
                continue
            else:
                if in_table and current_table:
                    # 处理表格
                    doc.add_paragraph()  # 空行
                    in_table = False
                    current_table = []

            # 处理标题
            if line.startswith('# '):
                text = line[2:].strip()
                # 移除 emoji
                text = ''.join(c for c in text if ord(c) < 0x1F300 or c in '📋📱🗺️🚇💴🏨🎫🍽️🌐📲⚠️📅📝🎉')
                heading = doc.add_heading(text, level=1)
            elif line.startswith('## '):
                text = line[3:].strip()
                heading = doc.add_heading(text, level=2)
            elif line.startswith('### '):
                text = line[4:].strip()
                heading = doc.add_heading(text, level=3)
            elif line.strip() == '':
                doc.add_paragraph()
            else:
                # 处理普通段落
                text = line.strip()
                if text:
                    p = doc.add_paragraph(text)

        doc.save(output_docx)
        print(f"✅ Word 文档已生成（备用方法）: {output_docx}")

finally:
    # 清理临时目录
    shutil.rmtree(temp_dir, ignore_errors=True)

print("\n📌 提示：生成的 Word 文档可以使用 Microsoft Word 或 WPS 打开")
print("📌 建议在 Word 中微调样式和格式以获得最佳效果")