#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Markdown 转 PDF 脚本 - 简化版
"""

import sys
from pathlib import Path

try:
    from weasyprint import HTML
    import markdown
except ImportError as e:
    print(f"缺少依赖：{e}")
    print("请运行：pip3 install markdown weasyprint")
    sys.exit(1)

def md_to_pdf(md_path, pdf_path):
    """将 Markdown 转换为 PDF"""
    
    with open(md_path, 'r', encoding='utf-8') as f:
        md_content = f.read()
    
    html_content = markdown.markdown(
        md_content,
        extensions=['tables', 'fenced_code', 'codehilite']
    )
    
    html_template = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>散户心理分析</title>
    <style>
        @page {{ size: A4; margin: 2cm; }}
        body {{ 
            font-family: "Microsoft YaHei", Arial, sans-serif; 
            line-height: 1.6; 
            color: #333;
            font-size: 11pt;
        }}
        h1 {{ color: #2c3e50; border-bottom: 3px solid #3498db; padding-bottom: 10px; }}
        h2 {{ color: #34495e; border-left: 4px solid #3498db; padding-left: 10px; margin-top: 25px; }}
        h3 {{ color: #7f8c8d; margin-top: 20px; }}
        table {{ width: 100%; border-collapse: collapse; margin: 15px 0; }}
        th {{ background-color: #3498db; color: white; padding: 10px; text-align: left; }}
        td {{ border: 1px solid #ddd; padding: 8px; }}
        tr:nth-child(even) {{ background-color: #f9f9f9; }}
        code {{ background-color: #f4f4f4; padding: 2px 5px; border-radius: 3px; }}
        pre {{ background-color: #2c3e50; color: #ecf0f1; padding: 15px; border-radius: 5px; overflow-x: auto; }}
        blockquote {{ border-left: 4px solid #3498db; margin: 15px 0; padding: 10px 15px; background-color: #f8f9fa; }}
        hr {{ border: none; border-top: 1px solid #ddd; margin: 20px 0; }}
    </style>
</head>
<body>
    {html_content}
</body>
</html>"""
    
    HTML(string=html_template).write_pdf(pdf_path)
    return True

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("用法：python3 md2pdf.py <input.md> <output.pdf>")
        sys.exit(1)
    
    md_file, pdf_file = sys.argv[1], sys.argv[2]
    print(f"正在转换：{md_file} → {pdf_file}")
    
    try:
        md_to_pdf(md_file, pdf_file)
        print(f"✅ PDF 生成成功：{pdf_file}")
    except Exception as e:
        print(f"❌ 转换失败：{e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
