#!/usr/bin/env python3
"""
markdown_to_html.py

A CLI tool to convert markdown files to styled HTML with syntax highlighting, table of contents, and responsive design.
"""

import argparse
import os
import sys
import re
import json
from typing import List, Dict, Optional
from pathlib import Path
import subprocess
import tempfile
import base64
import urllib.parse

try:
    import markdown
    import pygments
    from pygments.lexers import get_lexer_by_name
    from pygments.formatters import HtmlFormatter
    from pygments import highlight
except ImportError as e:
    print(f"Error: {e}. Please install required packages: markdown, pygments")
    sys.exit(1)

def generate_toc(content: str) -> str:
    """
    Generate table of contents from markdown content.

    Args:
        content (str): Markdown content

    Returns:
        str: Table of contents HTML
    """
    toc = []
    headings = re.findall(r'^(#{1,6})\s+(.*)', content, re.MULTILINE)

    for level, title in headings:
        heading_level = len(level)
        anchor = re.sub(r'\W+', '-', title.lower()).strip('-')
        toc.append(f'<li class="toc-level-{heading_level}"><a href="#{anchor}">{title}</a></li>')

    if toc:
        return f'<div class="toc"><h2>Table of Contents</h2><ul>{"".join(toc)}</ul></div>'
    return ''

def highlight_code(content: str) -> str:
    """
    Highlight code blocks in markdown content using Pygments.

    Args:
        content (str): Markdown content

    Returns:
        str: Content with highlighted code blocks
    """
    def highlight_match(match):
        lang = match.group(1)
        code = match.group(2)
        try:
            lexer = get_lexer_by_name(lang, stripall=True)
        except:
            lexer = get_lexer_by_name('text', stripall=True)
        formatter = HtmlFormatter()
        highlighted = highlight(code, lexer, formatter)
        return f'<pre class="code-block"><code>{highlighted}</code></pre>'

    pattern = re.compile(r'```(\w+)\n(.*?)\n```', re.DOTALL)
    return pattern.sub(highlight_match, content)

def add_responsive_design(html: str) -> str:
    """
    Add responsive design CSS to HTML.

    Args:
        html (str): HTML content

    Returns:
        str: HTML with responsive design CSS
    """
    css = """
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            background: #fff;
            color: #333;
        }
        .toc {
            background: #f5f5f5;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .toc ul {
            list-style: none;
            padding-left: 0;
        }
        .toc a {
            color: #0066cc;
            text-decoration: none;
        }
        .toc a:hover {
            text-decoration: underline;
        }
        .toc-level-2 { padding-left: 10px; }
        .toc-level-3 { padding-left: 20px; }
        .toc-level-4 { padding-left: 30px; }
        .toc-level-5 { padding-left: 40px; }
        .toc-level-6 { padding-left: 50px; }
        pre {
            background: #f8f8f8;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 10px;
            overflow-x: auto;
            margin: 15px 0;
        }
        code {
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        }
        @media (max-width: 768px) {
            body {
                padding: 10px;
                font-size: 14px;
            }
            .toc {
                padding: 10px;
            }
        }
    </style>
    """
    return css + html

def convert_markdown_to_html(input_file: str, output_file: Optional[str] = None) -> str:
    """
    Convert markdown file to styled HTML.

    Args:
        input_file (str): Path to input markdown file
        output_file (Optional[str]): Path to output HTML file (None for stdout)

    Returns:
        str: HTML content
    """
    if not os.path.exists(input_file):
        raise FileNotFoundError(f"Input file '{input_file}' not found")

    with open(input_file, 'r', encoding='utf-8') as f:
        content = f.read()

    # Generate TOC
    toc = generate_toc(content)

    # Highlight code blocks
    content = highlight_code(content)

    # Convert markdown to HTML
    html_content = markdown.markdown(content)

    # Add TOC to HTML
    html_content = f'<div class="markdown-body">{toc}{html_content}</div>'

    # Add responsive design
    html_content = add_responsive_design(html_content)

    # Wrap in basic HTML structure
    html = f"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>{os.path.basename(input_file)}</title>
    </head>
    <body>
        {html_content}
    </body>
    </html>
    """

    if output_file:
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(html)
        print(f"Successfully converted '{input_file}' to '{output_file}'")
    else:
        print(html)

    return html

def main():
    parser = argparse.ArgumentParser(
        description='Convert markdown files to styled HTML with syntax highlighting, table of contents, and responsive design.'
    )
    parser.add_argument('input', help='Input markdown file')
    parser.add_argument('-o', '--output', help='Output HTML file (default: stdout)')
    parser.add_argument('--version', action='version', version='1.0.0')

    args = parser.parse_args()

    try:
        convert_markdown_to_html(args.input, args.output)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == '__main__':
    main()