#!/usr/bin/env python3
"""
PDF 导出脚本 V2 - 使用 markdown + weasyprint
支持完整 Markdown 格式，更好的中文渲染

用法: python3 export_pdf_v2.py --title "标题" --content "内容" --output "输出路径"
"""
import sys
import os
import argparse

# 添加依赖路径
sys.path.insert(0, '/workspace/.local/lib/python3.11/site-packages')

import markdown
from weasyprint import HTML, CSS


def get_default_font():
    """获取系统默认中文字体"""
    font_paths = [
        # Windows
        ('C:/Windows/Fonts/msyh.ttc', 'Microsoft YaHei'),
        ('C:/Windows/Fonts/simhei.ttf', 'SimHei'),
        ('C:/Windows/Fonts/simsun.ttc', 'SimSun'),
        ('C:/Windows/Fonts/arialuni.ttf', 'Arial Unicode MS'),
        # Linux
        ('/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc', 'WenQuanYi Zen Hei'),
        ('/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc', 'Noto Sans CJK'),
        # macOS
        ('/System/Library/Fonts/PingFang.ttc', 'PingFang SC'),
        ('/Library/Fonts/Arial Unicode.ttf', 'Arial Unicode MS'),
    ]
    
    for path, name in font_paths:
        if os.path.exists(path):
            return name
    return 'sans-serif'


def export_pdf(title: str, content: str, output_path: str, data_source: str = "") -> str:
    """将 Markdown 内容导出为 PDF"""

    # 获取中文字体
    chinese_font = get_default_font()

    # 获取当前时间
    from datetime import datetime
    generate_time = datetime.now().strftime("%Y-%m-%d %H:%M")

    # Markdown 转 HTML
    md = markdown.Markdown(extensions=[
        'tables',
        'fenced_code',
        'toc',
        'nl2br',
    ])
    html_body = md.convert(content)

    # 处理 H3 标题：如果已有序号（如 "1. "、"2. "），添加标记
    import re
    def mark_numbered_h3(match):
        h3_content = match.group(1)
        # 检查是否以数字+点开头
        if re.match(r'^\d+\.', h3_content.strip()):
            return f'<h3 data-has-number="true">{h3_content}</h3>'
        return match.group(0)

    html_body = re.sub(r'<h3>(.*?)</h3>', mark_numbered_h3, html_body, flags=re.DOTALL)

    # 构建完整 HTML 文档 - 参考样式：蓝色标题、简洁专业
    html_template = f'''<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{title}</title>
    <style>
        @page {{
            size: A4;
            margin: 2.5cm 2cm;
            @bottom-center {{
                content: "以上内容由 ECclaw 生成";
                font-size: 9pt;
                color: #666;
            }}
        }}

        body {{
            font-family: "{chinese_font}", "Noto Sans CJK", "WenQuanYi Zen Hei", sans-serif;
            font-size: 11pt;
            line-height: 1.8;
            color: #333;
        }}

        /* 主标题样式 - 蓝色居中 */
        .title {{
            font-size: 22pt;
            text-align: center;
            font-weight: bold;
            color: #2c5282;
            margin-bottom: 30pt;
            padding-bottom: 10pt;
        }}

        /* H1 作为文档主标题 */
        h1 {{
            font-size: 22pt;
            text-align: center;
            font-weight: bold;
            color: #2c5282;
            margin-bottom: 25pt;
            padding-bottom: 10pt;
        }}

        /* H2 作为一级标题 - 蓝色带下划线 */
        h2 {{
            font-size: 14pt;
            font-weight: bold;
            color: #2c5282;
            margin-top: 25pt;
            margin-bottom: 12pt;
            padding-bottom: 6pt;
            border-bottom: 2pt solid #2c5282;
        }}

        /* H3 作为二级标题 - 无序号时带圆点标记 */
        h3 {{
            font-size: 12pt;
            font-weight: bold;
            color: #2c5282;
            margin-top: 18pt;
            margin-bottom: 8pt;
            position: relative;
            padding-left: 12pt;
        }}

        /* 为没有序号的 H3 添加圆点 */
        h3:not([data-has-number])::before {{
            content: "●";
            position: absolute;
            left: 0;
            color: #2c5282;
            font-size: 8pt;
            top: 50%;
            transform: translateY(-50%);
        }}

        /* 已有序号的 H3 不需要圆点和左边距 */
        h3[data-has-number] {{
            padding-left: 0;
        }}

        /* H4 作为三级标题 */
        h4 {{
            font-size: 11pt;
            font-weight: bold;
            color: #333;
            margin-top: 12pt;
            margin-bottom: 6pt;
        }}

        /* 段落 */
        p {{
            margin: 10pt 0;
            text-align: justify;
            text-indent: 0;
        }}

        /* 粗体 */
        strong, b {{
            font-weight: bold;
            color: #333;
        }}

        /* 斜体 */
        em, i {{
            font-style: italic;
        }}

        /* 行内代码 */
        code {{
            font-family: "Courier New", Consolas, monospace;
            background-color: #f5f5f5;
            padding: 2pt 4pt;
            border-radius: 3pt;
            font-size: 10pt;
            color: #c7254e;
        }}

        /* 代码块 */
        pre {{
            background-color: #f8f9fa;
            padding: 12pt;
            border-radius: 4pt;
            overflow-x: auto;
            margin: 12pt 0;
            border-left: 3pt solid #2c5282;
        }}

        pre code {{
            background-color: transparent;
            padding: 0;
            color: #333;
        }}

        /* 表格 - 简洁样式，内容居中 */
        table {{
            width: 100%;
            border-collapse: collapse;
            margin: 12pt 0;
            font-size: 10.5pt;
        }}

        th, td {{
            border: 0.5pt solid #ccc;
            padding: 8pt 10pt;
            text-align: center;
            vertical-align: middle;
        }}

        th {{
            background-color: #f0f4f8;
            font-weight: bold;
            color: #2c5282;
        }}

        tr:nth-child(even) {{
            background-color: #fafbfc;
        }}

        /* 表格第一列左对齐 */
        td:first-child, th:first-child {{
            text-align: left;
        }}

        /* 列表 */
        ul, ol {{
            margin: 10pt 0;
            padding-left: 25pt;
        }}

        li {{
            margin: 6pt 0;
        }}

        /* 列表中的粗体 */
        li strong, li b {{
            color: #2c5282;
        }}

        /* 引用块 - 蓝色底纹概览样式 */
        blockquote {{
            margin: 12pt 0;
            padding: 12pt 15pt;
            border-left: 4pt solid #2c5282;
            background-color: #e8f0f8;
            color: #2c5282;
            border-radius: 0 4pt 4pt 0;
        }}

        blockquote p {{
            margin: 6pt 0;
            color: #2c5282;
        }}

        blockquote strong, blockquote b {{
            color: #1a365d;
        }}

        /* 分隔线 */
        hr {{
            border: none;
            border-top: 0.5pt solid #ddd;
            margin: 20pt 0;
        }}

        /* 链接 */
        a {{
            color: #2c5282;
            text-decoration: none;
        }}

        /* 文档信息区域 */
        .doc-info {{
            margin-top: 30pt;
            padding-top: 15pt;
            border-top: 1pt solid #ddd;
            font-size: 9pt;
            color: #666;
            text-align: center;
        }}

        .doc-info p {{
            margin: 4pt 0;
            text-align: center;
        }}
    </style>
</head>
<body>
    <div class="title">{title}</div>
    {html_body}
    <div class="doc-info">
        <p>报告生成时间：{generate_time}</p>
        {f'<p>数据来源：{data_source}</p>' if data_source else '<p>数据来源：系统自动生成</p>'}
    </div>
</body>
</html>'''
    
    # 确保输出目录存在
    os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
    
    # HTML 转 PDF
    HTML(string=html_template).write_pdf(output_path)
    
    return output_path


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='导出 PDF 文档（支持完整 Markdown）')
    parser.add_argument('--title', required=True, help='文档标题')
    parser.add_argument('--content', required=True, help='文档正文（Markdown 格式）')
    parser.add_argument('--output', required=True, help='输出 .pdf 文件路径')
    parser.add_argument('--data-source', default='', help='数据来源说明（可选）')
    args = parser.parse_args()

    output = export_pdf(args.title, args.content, args.output, args.data_source)
    print(f'output_path: {output}')
    print('PDF 文档导出成功')
