import glob
import markdown
from pygments.formatters import HtmlFormatter

# CSS global
html_template = """<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>{title}</title>
<style>
body {{ font-family: sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; line-height: 1.6; color: #333; }}
img {{ max-width: 50%; display: block; margin: 20px auto; border: 1px solid #ccc; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }}
blockquote {{ border-left: 4px solid #ccc; margin: 0; padding-left: 10px; color: #666; font-style: italic; }}
ul, ol {{ padding-left: 30px; margin-bottom: 15px; }}
li {{ margin-bottom: 8px; }}
pre {{ background: #ffffff; padding: 15px; border-radius: 5px; border: 1px solid #ddd; overflow-x: auto; white-space: pre-wrap; overflow-wrap: break-word; font-size: 14px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }}
code {{ font-family: Consolas, monospace; background: #f9f9f9; padding: 2px 4px; border-radius: 3px; font-size: 14px; border: 1px solid #eee; }}
pre code {{ background: transparent; padding: 0; border: none; }}
{pygments_css}
</style>
<script type="module">
  import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
  mermaid.initialize({{ startOnLoad: true }});
</script>
</head>
<body>
{body}
</body>
</html>
"""

# Obtenir le CSS de pygments (thème par défaut: fond blanc, parfait pour l'impression)
pygments_css = HtmlFormatter(style='default').get_style_defs('.codehilite')

# Convertir tous les fichiers
for f in glob.glob('book/*.md'):
    with open(f, 'r', encoding='utf-8') as md_file:
        md_text = md_file.read()
        
    html_body = markdown.markdown(
        md_text, 
        extensions=['fenced_code', 'codehilite']
    )
    
    # Fix for mermaid blocks
    html_body = html_body.replace('<pre><code class="language-mermaid">', '<pre class="mermaid">')
    # the closing tag is just </code></pre>, which is fine as mermaid ignores inner tags or we can strip the </code>
    
    title = f.replace("book/", "").replace(".md", "")
    final_html = html_template.format(title=title, pygments_css=pygments_css, body=html_body)
    
    out_file = f.replace('.md', '.html')
    with open(out_file, 'w', encoding='utf-8') as out:
        out.write(final_html)
        
print("Conversion terminée avec coloration syntaxique !")
