"""
将 Markdown 文件转换为 HTML 格式
适用于 Python 3.7 及以上版本
"""
import os
import sys
import codecs
from bs4 import BeautifulSoup
import markdown
import re
import importlib.util

# 检查并安装必要的依赖
required_packages = ['pygments']
for package in required_packages:
    if importlib.util.find_spec(package) is None:
        print(f"正在安装必要的依赖: {package}")
        os.system(f"pip3 install {package}")

from pygments import highlight
from pygments.lexers import get_lexer_by_name, TextLexer
from pygments.formatters import HtmlFormatter

def md_to_html(md_file_path, html_file_path=None, css_file_path=None, title=None):
    """
    将 Markdown 文件转换为 HTML 文件
    
    参数:
        md_file_path (str): Markdown 文件路径
        html_file_path (str, optional): 输出的 HTML 文件路径，默认为与 md 文件同名但扩展名为 .html
        css_file_path (str, optional): CSS 文件路径，用于美化 HTML
        title (str, optional): HTML 文档的标题，默认使用文件名
        
    返回:
        str: 生成的 HTML 文件路径
    """
    # 检查 Markdown 文件是否存在
    if not os.path.exists(md_file_path):
        print(f"错误: Markdown 文件不存在: {md_file_path}")
        return None
    
    # 如果未指定 HTML 文件路径，则使用与 md 文件同名但扩展名为 .html 的路径
    if html_file_path is None:
        html_file_path = os.path.splitext(md_file_path)[0] + '.html'
    
    # 如果未指定标题，则使用文件名作为标题
    if title is None:
        title = os.path.basename(os.path.splitext(md_file_path)[0])
    
    try:
        # 读取 Markdown 文件内容
        with codecs.open(md_file_path, 'r', encoding='utf-8') as md_file:
            md_content = md_file.read()
        
        # 检查是否包含 [TOC] 标记
        has_toc = '[TOC]' in md_content or '[toc]' in md_content
        
        # 预处理 Markdown 内容，处理引用块中的代码块
        md_content = preprocess_markdown(md_content)
        
        # 移除 [TOC] 标记，避免在内容中显示
        md_content = re.sub(r'\[TOC\]|\[toc\]', '', md_content)
        
        # 转换 Markdown 为 HTML
        html_content = markdown.markdown(
            md_content,
            extensions=[
                'markdown.extensions.tables',
                'markdown.extensions.fenced_code',
                'markdown.extensions.codehilite',
                'markdown.extensions.toc',
                'markdown.extensions.nl2br',
                'markdown.extensions.sane_lists'
            ],
            extension_configs={
                'markdown.extensions.codehilite': {
                    'use_pygments': True,
                    'noclasses': False,
                    'css_class': 'highlight'
                },
                'markdown.extensions.toc': {
                    'permalink': True,
                    'baselevel': 1,
                    'title': '目录',
                    'toc_depth': 3
                }
            }
        )
        
        # 后处理 HTML 内容，为代码块添加语法高亮
        html_content = postprocess_html(html_content)
        
        # 获取 Pygments 样式
        pygments_css = HtmlFormatter(style='default').get_style_defs('.highlight')
        
        # 创建完整的 HTML 文档
        html_template = f"""<!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>
    {'<link rel="stylesheet" href="' + css_file_path + '">' if css_file_path else ''}
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            line-height: 1.6;
            padding: 0;
            margin: 0;
            color: #333;
            display: flex;
        }}
        
        /* 目录样式 */
        .toc-container {{
            width: 320px;
            height: 100vh;
            overflow-y: auto;
            position: sticky;
            top: 0;
            padding: 20px;
            background-color: #f8f9fa;
            border-right: 1px solid #e1e4e8;
            box-sizing: border-box;
        }}
        
        .toc-container .toc {{
            margin: 0;
            padding: 0;
        }}
        
        .toc-container .toc ul {{
            list-style-type: none;
            padding-left: 20px;
        }}
        
        .toc-container .toc > ul {{
            padding-left: 0;
        }}
        
        .toc-container .toc li {{
            margin: 8px 0;
        }}
        
        .toc-container .toc a {{
            color: #4a86e8;
            text-decoration: none;
            font-size: 14px;
            display: block;
            padding: 3px 0;
            border-left: 2px solid transparent;
            padding-left: 10px;
            transition: all 0.2s ease;
        }}
        
        .toc-container .toc a:hover {{
            border-left-color: #4a86e8;
            background-color: rgba(74, 134, 232, 0.1);
        }}
        
        /* 顶部链接样式 */
        .toc-container .toc .toc-top-link {{
            font-weight: bold;
            font-size: 16px;
            color: #333;
            padding: 5px 0;
            margin-bottom: 10px;
            border-bottom: 1px solid #e1e4e8;
        }}
        
        .toc-container .toc .toc-top-link:hover {{
            color: #4a86e8;
        }}
        
        /* 内容样式 */
        .content-container {{
            flex: 1;
            padding: 20px;
            max-width: 950px;
            margin: 0 auto;
            box-sizing: border-box;
        }}
        
        /* 响应式布局 */
        @media (max-width: 768px) {{
            body {{
                flex-direction: column;
            }}
            
            .toc-container {{
                width: 100%;
                height: auto;
                max-height: 300px;
                position: relative;
            }}
            
            .content-container {{
                width: 100%;
            }}
        }}
        
        pre {{
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 5px;
            overflow-x: auto;
        }}
        
        code {{
            font-family: Consolas, Monaco, 'Andale Mono', monospace;
            background-color: #f5f5f5;
            padding: 2px 4px;
            border-radius: 3px;
        }}
        
        table {{
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 20px;
        }}
        
        th, td {{
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }}
        
        th {{
            background-color: #f2f2f2;
        }}
        
        img {{
            max-width: 100%;
            height: auto;
        }}
        
        blockquote {{
            border-left: 4px solid #ddd;
            padding-left: 16px;
            margin-left: 0;
            color: #666;
        }}
        
        blockquote pre {{
            background-color: #f0f0f0;
            border-left: 3px solid #ccc;
        }}
        
        /* 标题样式优化 */
        h2 {{
            font-size: 1.5em;
            border-bottom: 1px solid #eaecef;
            padding-bottom: 0.3em;
            text-decoration: underline;  /* 为 h2 添加下划线 */
        }}
        
        /* 超链接颜色优化 */
        a {{
            color: #4a86e8;  /* 更淡的浅蓝色 */
            text-decoration: none;
        }}
        
        a:hover {{
            text-decoration: underline;
        }}
        
        /* 代码高亮样式 */
        {pygments_css}
        
        .highlight {{
            background: #f8f8f8;
            border-radius: 5px;
            margin: 10px 0;
        }}
        
        .highlight pre {{
            background: transparent;
            margin: 0;
            padding: 10px;
            border: none;
            font-size: 0.85em;  /* 缩小代码块字体 */
            line-height: 1.5;  /* 增加代码块行间距 */
        }}
        
        .highlight code {{
            line-height: 1.5;  /* 增加代码行间距 */
        }}
        
        /* 代码行样式 */
        .highlight .line {{
            line-height: 1.5;  /* 增加代码行间距 */
            margin-bottom: 2px;  /* 行之间添加间距 */
            display: block;  /* 确保每行都是块级元素 */
        }}
        
        /* 减弱蓝色代码的强度 */
        .highlight .n, .highlight .na, .highlight .nb, .highlight .bp, .highlight .nc, .highlight .no, .highlight .nd, .highlight .ni, .highlight .ne, .highlight .nf, .highlight .nl, .highlight .nn, .highlight .nx, .highlight .py, .highlight .nt, .highlight .nv, .highlight .ow, .highlight .o, .highlight .oi, .highlight .om {{
            color: #5c8db8 !important;  /* 减弱蓝色代码的强度 */
        }}
        
        /* Objective-C 语法高亮 */
        .language-objectivec .highlight .k, .language-objectivec .highlight .kt {{
            color: #008 !important;  /* 关键字 - 深蓝色 */
        }}
        
        .language-objectivec .highlight .nc {{
            color: #b06 !important;  /* 类名 - 紫色 */
        }}
        
        .language-objectivec .highlight .mi {{
            color: #099 !important;  /* 数字 - 青色 */
        }}
        
        .language-objectivec .highlight .s, .language-objectivec .highlight .s1, .language-objectivec .highlight .s2 {{
            color: #d14 !important;  /* 字符串 - 红色 */
        }}
        
        .language-objectivec .highlight .cp {{
            color: #999 !important;  /* 预处理指令 - 灰色 */
        }}
        
        /* XML 标签颜色 */
        .language-xml .highlight .nt {{
            color: #905 !important;  /* XML标签名称 - 暗红色 */
        }}
        
        .language-xml .highlight .na {{
            color: #690 !important;  /* XML属性名称 - 绿色 */
        }}
        
        .language-xml .highlight .s, .language-xml .highlight .s1, .language-xml .highlight .s2 {{
            color: #07a !important;  /* XML字符串 - 蓝色 */
        }}
        
        /* JSON 语法高亮 */
        .language-json .highlight .p {{
            color: #333 !important;  /* JSON标点符号 */
        }}
        
        .language-json .highlight .s2 {{
            color: #d14 !important;  /* JSON字符串 - 红色 */
        }}
        
        .language-json .highlight .kc {{
            color: #099 !important;  /* JSON关键字(true/false/null) - 青色 */
        }}
        
        .language-json .highlight .mi {{
            color: #099 !important;  /* JSON数字 - 青色 */
        }}
        
        .language-label {{
            display: block;
            background: #e0e0e0;
            padding: 3px 10px;
            font-size: 12px;
            font-family: sans-serif;
            color: #666;
            border-top-left-radius: 5px;
            border-top-right-radius: 5px;
        }}
        
        .language-label {{
            display: block;
            background: #e0e0e0;
            padding: 3px 10px;
            font-size: 12px;
            font-family: sans-serif;
            color: #666;
            border-top-left-radius: 5px;
            border-top-right-radius: 5px;
        }}
        
        /* 引用块中的代码样式 */
        blockquote .highlight {{
            background: #f0f0f0;
        }}
        
        /* 隐藏原始 TOC */
        .content-container .toc {{
            display: none;
        }}
    </style>
</head>
<body>
"""
        
        # 如果有 TOC 标记，添加左侧目录
        if has_toc:
            # 提取标题并生成目录
            toc_html = generate_toc(html_content)
            html_template += f"""
    <div class="toc-container">
        <h2>目录</h2>
        <div class="toc">
            {toc_html}
        </div>
    </div>
    <div class="content-container">
        <div class="markdown-body">
            {html_content}
        </div>
    </div>
</body>
</html>"""
        else:
            # 没有 TOC 标记，使用普通布局
            html_template += f"""
    <div class="content-container">
        <div class="markdown-body">
            {html_content}
        </div>
    </div>
</body>
</html>"""
        
        # 美化 HTML（可选）
        soup = BeautifulSoup(html_template, 'html.parser')
        pretty_html = soup.prettify()
        
        # 写入 HTML 文件
        with codecs.open(html_file_path, 'w', encoding='utf-8') as html_file:
            html_file.write(pretty_html)
        
        print(f"✅ Markdown 文件已成功转换为 HTML: {html_file_path}")
        return html_file_path
        
    except Exception as e:
        print(f"转换过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
        return None

def generate_toc(html_content):
    """
    从 HTML 内容中提取标题并生成目录
    
    参数:
        html_content (str): HTML 内容
        
    返回:
        str: 目录的 HTML 代码
    """
    soup = BeautifulSoup(html_content, 'html.parser')
    headings = soup.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])
    
    if not headings:
        return "<p>没有找到标题</p>"
    
    # 创建目录结构
    toc_html = "<ul>"
    current_level = 1
    stack = []
    
    for heading in headings:
        # 获取标题级别
        level = int(heading.name[1])
        
        # 获取标题文本和 ID
        heading_text = heading.get_text()
        heading_id = heading.get('id')
        
        # 如果没有 ID，生成一个
        if not heading_id:
            heading_id = re.sub(r'[^a-zA-Z0-9_-]', '-', heading_text.lower())
            heading['id'] = heading_id
        
        # 调整目录层级
        if level > current_level:
            # 进入更深层级
            for _ in range(level - current_level):
                toc_html += "<ul>"
                stack.append("</ul>")
        elif level < current_level:
            # 返回更浅层级
            for _ in range(current_level - level):
                toc_html += stack.pop()
        
        # 添加目录项
        toc_html += f'<li><a href="#{heading_id}">{heading_text}</a></li>'
        
        current_level = level
    
    # 关闭所有打开的标签
    while stack:
        toc_html += stack.pop()
    
    toc_html += "</ul>"
    return toc_html

def preprocess_markdown(md_content):
    """
    预处理 Markdown 内容，处理引用块中的代码块
    """
    # 标记引用块中的代码块
    lines = md_content.split('\n')
    in_quote = False
    in_code = False
    code_lang = ''
    result_lines = []
    
    i = 0
    while i < len(lines):
        line = lines[i]
        
        # 检测引用块开始
        if line.startswith('>'):
            if not in_quote:
                in_quote = True
            
            # 检测引用块中的代码块
            if '```' in line:
                # 提取语言
                code_start = line.find('```')
                if code_start + 3 < len(line):
                    code_lang = line[code_start+3:].strip()
                else:
                    code_lang = ''
                
                # 替换为特殊标记
                line = line[:code_start] + '%%CODE_BLOCK_START%%' + code_lang
                in_code = True
            
            result_lines.append(line)
        
        # 检测引用块中的代码块结束
        elif in_quote and in_code and '```' in line:
            result_lines.append('> %%CODE_BLOCK_END%%')
            in_code = False
            i += 1
            continue
        
        # 检测引用块结束
        elif in_quote and not line.startswith('>'):
            in_quote = False
            in_code = False
            result_lines.append(line)
        
        else:
            result_lines.append(line)
        
        i += 1
    
    return '\n'.join(result_lines)

def postprocess_html(html_content):
    """
    后处理 HTML 内容，处理代码块和语法高亮
    """
    # 语言别名映射
    LANGUAGE_ALIASES = {
        'objective-c': 'objectivec',
        'objc': 'objectivec',
        'obj-c': 'objectivec',
        'js': 'javascript',
        'ts': 'typescript',
        'py': 'python',
        'rb': 'ruby',
        'sh': 'bash',
        'zsh': 'bash',
        'c++': 'cpp',
        'html5': 'html',
        'md': 'markdown',
        'pod': 'ruby',       # 添加 pod 作为 ruby 的别名
        'podfile': 'ruby'    # 添加 podfile 作为 ruby 的别名
    }
    
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # 处理第一个 H1 标题，添加居中样式
    first_h1 = soup.find('h1')
    if first_h1:
        first_h1['style'] = 'text-align: center;'
    
    # 处理代码块
    for pre in soup.find_all('pre'):
        code = pre.find('code')  # 这一行在您的代码中缺失
        if code:
            # 检查是否有语言类
            lang = None
            classes = code.get('class', [])
            
            # 尝试从类名中提取语言
            for cls in classes:
                if cls.startswith('language-'):
                    lang = cls[9:]  # 提取语言名称
                    break
            
            # 如果没有检测到语言，尝试从代码内容或其他属性中推断
            if not lang or lang == 'plaintext':
                # 尝试从代码块的第一行推断语言
                code_text = code.get_text()
                first_line = code_text.strip().split('\n')[0] if code_text else ''
                
                # 根据特征推断语言
                if first_line.startswith('#import') or first_line.startswith('@interface'):
                    lang = 'Objective-C'
                elif first_line.startswith('<') and '>' in first_line:
                    lang = 'xml'
                elif first_line.startswith('import ') or first_line.startswith('from '):
                    lang = 'python'
                elif first_line.startswith('{') or first_line.startswith('['):
                    if ('{' in first_line and '}' in code_text) or ('[' in first_line and ']' in code_text):
                        lang = 'json'
                elif first_line.startswith('platform :ios') or 'pod ' in code_text:
                    lang = 'ruby'  # 识别 Podfile 内容
            
            # 应用语言别名映射
            if lang in LANGUAGE_ALIASES:
                print(f'应用语言别名映射: {lang} -> {LANGUAGE_ALIASES[lang]}')
                lang = LANGUAGE_ALIASES[lang]
            
            if lang and lang != 'plaintext':
                try:
                    # 获取对应语言的词法分析器
                    lexer = get_lexer_by_name(lang, stripall=True)
                    # 格式化代码
                    formatter = HtmlFormatter(style='default')
                    code_text = code.get_text()
                    highlighted_code = highlight(code_text, lexer, formatter)
                    
                    # 创建语言标签
                    lang_label = soup.new_tag('div')
                    lang_label['class'] = 'language-label'
                    lang_label.string = lang
                    
                    # 创建高亮容器
                    highlight_div = soup.new_tag('div')
                    highlight_div['class'] = f'highlight language-{lang}'  # 添加语言类名
                    highlight_div.append(lang_label)
                    
                    # 替换原始代码块
                    new_content = BeautifulSoup(highlighted_code, 'html.parser')
                    highlight_div.append(new_content)
                    pre.replace_with(highlight_div)
                except Exception as e:
                    print(f"高亮代码时出错 (语言: {lang}): {e}")
            else:
                print(f'未检测到语言或语言为plaintext')  # 打印未检测到语言的情况
    
    # 处理引用块中的特殊标记
    html_str = str(soup)
    
    # 替换引用块中的代码块标记
    pattern = r'&gt; %%CODE_BLOCK_START%%(.*?)(?:\n&gt; .*?)*?\n&gt; %%CODE_BLOCK_END%%'
    
    def replace_code_block(match):
        block = match.group(0)
        # 提取语言
        lang_match = re.search(r'%%CODE_BLOCK_START%%(.*?)(?:\n|$)', block)
        lang = lang_match.group(1).strip() if lang_match else ''
        
        # 提取代码内容
        code_lines = []
        for line in block.split('\n'):
            if '%%CODE_BLOCK_START%%' in line or '%%CODE_BLOCK_END%%' in line:
                continue
            # 移除引用前缀
            if line.startswith('&gt; '):
                code_lines.append(line[5:])
            else:
                code_lines.append(line)
        
        code_content = '\n'.join(code_lines)
        
        # 创建高亮代码
        try:
            lexer = get_lexer_by_name(lang, stripall=True) if lang else TextLexer()
            formatter = HtmlFormatter(style='default')
            highlighted = highlight(code_content, lexer, formatter)
            
            # 添加语言标签
            return f'<blockquote><div class="language-label">{lang}</div><div class="highlight">{highlighted}</div></blockquote>'
        except Exception as e:
            print(f"处理引用块中的代码高亮时出错 (语言: {lang}): {e}")
            return f'<blockquote><pre><code class="language-{lang}">{code_content}</code></pre></blockquote>'
    
    html_str = re.sub(pattern, replace_code_block, html_str, flags=re.DOTALL)
    
    return html_str

def batch_convert_md_to_html(directory_path, recursive=True, css_file_path=None):
    """
    批量转换目录中的所有 Markdown 文件为 HTML
    
    参数:
        directory_path (str): 目录路径
        recursive (bool, optional): 是否递归处理子目录，默认为 True
        css_file_path (str, optional): CSS 文件路径，用于美化 HTML
        
    返回:
        list: 生成的 HTML 文件路径列表
    """
    if not os.path.isdir(directory_path):
        print(f"错误: 指定的路径不是目录: {directory_path}")
        return []
    
    html_files = []
    
    # 遍历目录
    for root, dirs, files in os.walk(directory_path):
        # 处理当前目录中的 Markdown 文件
        for file in files:
            if file.lower().endswith('.md'):
                md_file_path = os.path.join(root, file)
                html_file_path = md_to_html(md_file_path, css_file_path=css_file_path)
                if html_file_path:
                    html_files.append(html_file_path)
        
        # 如果不递归处理子目录，则跳出循环
        if not recursive:
            break
    
    print(f"✅ 批量转换完成，共生成 {len(html_files)} 个 HTML 文件")
    return html_files

def create_default_css(output_path=None):
    """
    创建默认的 CSS 文件用于美化 HTML
    
    参数:
        output_path (str, optional): CSS 文件输出路径，默认为当前目录下的 markdown.css
        
    返回:
        str: CSS 文件路径
    """
    if output_path is None:
        output_path = os.path.join(os.getcwd(), 'markdown.css')
    
    css_content = """/* Markdown 样式 */
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    line-height: 1.6;
    color: #333;
    background-color: #fff;
    margin: 0;
    padding: 0;
}

/* 布局样式 */
.container {
    display: flex;
    min-height: 100vh;
}

/* 目录侧边栏样式 */
.toc-sidebar {
    width: 280px;
    background-color: #f8f9fa;
    border-right: 1px solid #e9ecef;
    padding: 20px 0;
    position: fixed;
    height: 100vh;
    overflow-y: auto;
}

.toc-container {
    padding: 0 20px;
}

.toc-container h2 {
    margin-top: 0;
    padding-bottom: 10px;
    border-bottom: 1px solid #dee2e6;
    text-decoration: none;
}

.toc-container ul {
    list-style-type: none;
    padding-left: 0;
}

.toc-container ul ul {
    padding-left: 20px;
}

.toc-container li {
    margin-bottom: 8px;
}

.toc-container a {
    color: #495057;
    text-decoration: none;
    display: block;
    padding: 5px 0;
    border-radius: 3px;
    transition: background-color 0.2s;
}

.toc-container a:hover {
    background-color: #e9ecef;
    padding-left: 5px;
}

/* 内容区域样式 */
.content {
    flex: 1;
    padding: 20px;
    margin-left: 280px;
    max-width: 900px;
}

.markdown-body {
    max-width: 900px;
    margin: 0 auto;
}

h1, h2, h3, h4, h5, h6 {
    margin-top: 24px;
    margin-bottom: 16px;
    font-weight: 600;
    line-height: 1.25;
}

h1 {
    font-size: 2em;
    border-bottom: 1px solid #eaecef;
    padding-bottom: 0.3em;
}

h2 {
    font-size: 1.5em;
    border-bottom: 1px solid #eaecef;
    padding-bottom: 0.3em;
    text-decoration: underline;  /* 为 h2 添加下划线 */
}

h3 {
    font-size: 1.25em;
}

h4 {
    font-size: 1em;
}

h5 {
    font-size: 0.875em;
}

h6 {
    font-size: 0.85em;
    color: #6a737d;
}

a {
    color: #4a86e8;  /* 更淡的浅蓝色 */
    text-decoration: none;
}

a:hover {
    text-decoration: underline;
}

pre {
    background-color: #f6f8fa;
    border-radius: 3px;
    padding: 16px;
    overflow: auto;
    font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
    font-size: 80%;  /* 缩小代码块字体 */
    line-height: 1.5;  /* 增加代码块行间距 */
}

code {
    background-color: rgba(27, 31, 35, 0.05);
    border-radius: 3px;
    font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
    font-size: 85%;
    margin: 0;
    padding: 0.2em 0.4em;
}

pre code {
    background-color: transparent;
    padding: 0;
    line-height: 1.5;  /* 增加代码行间距 */
}

blockquote {
    margin: 0;
    padding: 0 1em;
    color: #6a737d;
    border-left: 0.25em solid #dfe2e5;
}

table {
    border-spacing: 0;
    border-collapse: collapse;
    width: 100%;
    overflow: auto;
    margin-bottom: 16px;
}

table th {
    font-weight: 600;
    background-color: #f6f8fa;
}

table th, table td {
    padding: 6px 13px;
    border: 1px solid #dfe2e5;
}

table tr {
    background-color: #fff;
    border-top: 1px solid #c6cbd1;
}

table tr:nth-child(2n) {
    background-color: #f6f8fa;
}

img {
    max-width: 100%;
    box-sizing: content-box;
}

hr {
    height: 0.25em;
    padding: 0;
    margin: 24px 0;
    background-color: #e1e4e8;
    border: 0;
}

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

li + li {
    margin-top: 0.25em;
}

/* 代码高亮样式 */
.highlight {
    background: #f8f8f8;
    border-radius: 5px;
}

.highlight pre {
    background: transparent;
    margin: 0;
    padding: 10px;
    border: none;
    font-size: 0.85em;  /* 缩小代码块字体 */
    line-height: 1.5;  /* 增加代码块行间距 */
}

.highlight code {
    line-height: 1.5;  /* 增加代码行间距 */
}

/* 代码行样式 */
.highlight .line {
    line-height: 1.5;  /* 增加代码行间距 */
    margin-bottom: 2px;  /* 行之间添加间距 */
    display: block;  /* 确保每行都是块级元素 */
}

/* 减弱蓝色代码的强度 */
.highlight .n, .highlight .na, .highlight .nb, .highlight .bp, .highlight .nc, .highlight .no, .highlight .nd, .highlight .ni, .highlight .ne, .highlight .nf, .highlight .nl, .highlight .nn, .highlight .nx, .highlight .py, .highlight .nt, .highlight .nv, .highlight .ow, .highlight .o, .highlight .oi, .highlight .om {{
    color: #5c8db8 !important;  /* 减弱蓝色代码的强度 */
}

/* 引用块中的代码样式 */
blockquote .highlight {
    background: #f0f0f0;
}

/* 任务列表样式 */
.task-list-item {
    list-style-type: none;
}

.task-list-item input {
    margin: 0 0.2em 0.25em -1.6em;
    vertical-align: middle;
}
"""
    
    try:
        with codecs.open(output_path, 'w', encoding='utf-8') as css_file:
            css_file.write(css_content)
        print(f"✅ 已创建默认 CSS 文件: {output_path}")
        return output_path
    except Exception as e:
        print(f"创建 CSS 文件时发生错误: {e}")
        return None

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("用法:")
        print("  单个文件转换: python3 md_to_html.py <path/to/file.md> [output.html] [css_file.css]")
        print("  批量转换目录: python3 md_to_html.py --batch <directory_path> [--no-recursive] [css_file.css]")
        print("  创建默认 CSS: python3 md_to_html.py --create-css [output_path.css]")
        sys.exit(1)
    
    if sys.argv[1] == '--create-css':
        output_css_path = sys.argv[2] if len(sys.argv) > 2 else None
        create_default_css(output_css_path)
    
    elif sys.argv[1] == '--batch':
        if len(sys.argv) < 3:
            print("错误: 请指定目录路径")
            sys.exit(1)
        
        directory_path = sys.argv[2]
        recursive = True
        css_file_path = None
        
        # 解析其他参数
        for i in range(3, len(sys.argv)):
            if sys.argv[i] == '--no-recursive':
                recursive = False
            elif sys.argv[i].endswith('.css'):
                css_file_path = sys.argv[i]
        
        batch_convert_md_to_html(directory_path, recursive, css_file_path)
    
    else:
        md_file_path = sys.argv[1]
        html_file_path = sys.argv[2] if len(sys.argv) > 2 else None
        css_file_path = sys.argv[3] if len(sys.argv) > 3 else None
        
        md_to_html(md_file_path, html_file_path, css_file_path)