#!/usr/bin/env python3
# ============================================
# Markdown 转 HTML 脚本
# 自动转换目录下所有md文件为带样式的HTML
# ============================================

import os
import markdown
from pathlib import Path

# HTML模板
HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title}</title>
    <style>
        * {{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }}

        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 40px 20px;
        }}

        .container {{
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            padding: 60px;
        }}

        h1, h2, h3, h4, h5, h6 {{
            color: #2d3748;
            margin-top: 1.5em;
            margin-bottom: 0.8em;
            line-height: 1.3;
        }}

        h1 {{
            font-size: 32px;
            color: #667eea;
            text-align: center;
            padding-bottom: 20px;
            border-bottom: 3px solid #667eea;
            margin-top: 0;
        }}

        h2 {{
            font-size: 24px;
            color: #764ba2;
            padding-left: 15px;
            border-left: 4px solid #764ba2;
        }}

        h3 {{
            font-size: 20px;
            color: #4a5568;
        }}

        p {{
            color: #4a5568;
            line-height: 1.8;
            margin-bottom: 1em;
        }}

        ul, ol {{
            margin: 1em 0;
            padding-left: 2em;
        }}

        li {{
            color: #4a5568;
            line-height: 1.8;
            margin-bottom: 0.5em;
        }}

        table {{
            width: 100%;
            border-collapse: collapse;
            margin: 1.5em 0;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }}

        th {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 15px;
            text-align: left;
            font-weight: 600;
        }}

        td {{
            padding: 12px 15px;
            border-bottom: 1px solid #e2e8f0;
            color: #4a5568;
        }}

        tr:hover {{
            background: #f7fafc;
        }}

        code {{
            background: #f7fafc;
            padding: 2px 8px;
            border-radius: 4px;
            font-family: 'Monaco', 'Menlo', monospace;
            color: #e53e3e;
            font-size: 0.9em;
        }}

        pre {{
            background: #1a202c;
            color: #e2e8f0;
            padding: 20px;
            border-radius: 10px;
            overflow-x: auto;
            margin: 1.5em 0;
        }}

        pre code {{
            background: none;
            color: #9ae6b4;
            padding: 0;
        }}

        hr {{
            border: none;
            height: 2px;
            background: linear-gradient(90deg, transparent, #e2e8f0, transparent);
            margin: 2em 0;
        }}

        blockquote {{
            border-left: 4px solid #667eea;
            padding: 15px 20px;
            background: #f8f9ff;
            margin: 1.5em 0;
            border-radius: 0 8px 8px 0;
        }}

        blockquote p {{
            margin: 0;
            color: #667eea;
        }}

        strong {{
            color: #2d3748;
        }}

        em {{
            color: #718096;
        }}

        a {{
            color: #667eea;
            text-decoration: none;
            border-bottom: 1px dashed #667eea;
        }}

        a:hover {{
            color: #764ba2;
            border-bottom-style: solid;
        }}

        .toc {{
            background: #f7fafc;
            padding: 25px;
            border-radius: 12px;
            margin-bottom: 2em;
        }}

        .toc h3 {{
            margin-top: 0;
            color: #667eea;
        }}

        .toc ul {{
            margin: 0;
        }}

        @media print {{
            body {{
                background: white;
                padding: 0;
            }}
            .container {{
                box-shadow: none;
                padding: 40px;
            }}
        }}

        @media (max-width: 768px) {{
            .container {{
                padding: 30px 20px;
            }}
            h1 {{
                font-size: 24px;
            }}
            h2 {{
                font-size: 20px;
            }}
        }}

        /* Mermaid 图表样式 */
        .mermaid {{
            text-align: center;
            margin: 2em 0;
            padding: 20px;
            background: #fafafa;
            border-radius: 12px;
        }}
    </style>
    <!-- Mermaid 图表库 -->
    <script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
    <script>
        mermaid.initialize({{
            startOnLoad: true,
            theme: 'default',
            themeVariables: {{
                primaryColor: '#667eea',
                primaryTextColor: '#fff',
                primaryBorderColor: '#764ba2',
                lineColor: '#667eea',
                secondaryColor: '#f093fb',
                tertiaryColor: '#4facfe'
            }}
        }});
    </script>
</head>
<body>
    <div class="container">
        {content}
    </div>
</body>
</html>
"""

def convert_md_to_html(md_path, output_dir=None):
    """转换单个markdown文件为HTML"""
    md_path = Path(md_path)
    
    # 读取md文件
    with open(md_path, 'r', encoding='utf-8') as f:
        md_content = f.read()
    
    # 提取标题（第一行）
    title = md_path.stem
    first_line = md_content.split('\n')[0]
    if first_line.startswith('# '):
        title = first_line[2:].strip()
    
    # 转换markdown为HTML
    html_content = markdown.markdown(
        md_content,
        extensions=[
            'tables',
            'fenced_code',
            'codehilite',
            'toc',
            'nl2br'
        ]
    )
    
    # 生成完整HTML
    full_html = HTML_TEMPLATE.format(
        title=title,
        content=html_content
    )
    
    # 确定输出路径
    if output_dir:
        output_path = Path(output_dir) / (md_path.stem + '.html')
    else:
        output_path = md_path.parent / (md_path.stem + '.html')
    
    # 写入文件
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(full_html)
    
    return output_path

def convert_directory(base_dir):
    """批量转换目录下所有md文件"""
    base_path = Path(base_dir)
    
    # 查找所有md文件
    md_files = list(base_path.rglob('*.md'))
    
    print(f"找到 {len(md_files)} 个 Markdown 文件")
    
    for md_file in md_files:
        print(f"  转换: {md_file.relative_to(base_path)}")
        output_path = convert_md_to_html(md_file)
        print(f"    → {output_path.relative_to(base_path)}")
    
    return len(md_files)

if __name__ == '__main__':
    import sys
    
    # 检查是否安装了markdown库
    try:
        import markdown
    except ImportError:
        print("安装 markdown 库...")
        os.system('pip install markdown')
        import markdown
    
    # 转换课程目录（绝对路径）
    target_dir = "/home/damo/workspace/AIGC_class/2026-2/docs/superpowers/course"
    
    if len(sys.argv) > 1:
        target_dir = sys.argv[1]
    
    print("=" * 60)
    print("  Markdown → HTML 批量转换工具")
    print("=" * 60)
    print()
    
    count = convert_directory(target_dir)
    
    print()
    print("=" * 60)
    print(f"  ✅ 转换完成！共转换 {count} 个文件")
    print("=" * 60)
