import glob
import markdown
import os
import subprocess
from pygments.formatters import HtmlFormatter

# Liste des fichiers
files = [f"book/cha{i}.md" for i in range(1, 10)]

projet_annexes = ["book/annexe_0_developpement.md"]
core_annexes = sorted(glob.glob("book/annexe_core_*.md"))
app_annexes = sorted(glob.glob("book/annexe_app_*.md"))

files.extend(projet_annexes)
files.extend(core_annexes)
files.extend(app_annexes)

combined_md = ""

# Ajouter l'introduction de index.md sans sa table des matières manuelle
if os.path.exists("book/index.md"):
    with open("book/index.md", "r", encoding="utf-8") as f:
        index_content = f.read()
        # Ne garder que la partie avant "## Table des Matières"
        intro = index_content.split("## Table des Matières")[0]
        combined_md += intro + "\n\n## Table des Matières\n\n[TOC]\n\n<div style='page-break-after: always;'></div>\n\n"

for f in files:
    if os.path.exists(f):
        with open(f, 'r', encoding='utf-8') as file:
            content = file.read()
            # Replace image paths to be absolute so Chrome can find them
            # or just run Chrome from the book directory
            combined_md += content + "\n\n<div style='page-break-after: always;'></div>\n\n"

# CSS global for PDF
html_template = """<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Le Livre de GrimOS</title>
<style>
body {{ font-family: sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; line-height: 1.6; color: #333; }}
img {{ max-width: 80%; 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: 12px; 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: 12px; border: 1px solid #eee; word-break: break-word; }}
pre code {{ background: transparent; padding: 0; border: none; }}
@media print {{
    body {{ max-width: 100%; margin: 0; padding: 0; }}
    pre, code {{ font-size: 10px; }}
    @page {{ margin: 2cm; }}
}}
{pygments_css}
</style>
</head>
<body>
{body}
</body>
</html>
"""

pygments_css = HtmlFormatter(style='default').get_style_defs('.codehilite')

html_body = markdown.markdown(
    combined_md, 
    extensions=['fenced_code', 'codehilite', 'toc']
)

# Fix mermaid blocks just in case
html_body = html_body.replace('<pre><code class="language-mermaid">', '<pre class="mermaid">')

final_html = html_template.format(pygments_css=pygments_css, body=html_body)

with open("book/GrimOS_Book_Combined.html", "w", encoding="utf-8") as out:
    out.write(final_html)

print("Fichier HTML combiné généré. Lancement de la conversion PDF via Google Chrome...")

# Generate PDF with Chrome headless
abs_path = os.path.abspath("book/GrimOS_Book_Combined.html")
pdf_path = os.path.abspath("book/GrimOS_Book.pdf")

try:
    subprocess.run([
        "google-chrome", 
        "--headless", 
        "--disable-gpu", 
        "--no-sandbox", 
        f"--print-to-pdf={pdf_path}", 
        f"file://{abs_path}"
    ], check=True)
    print(f"PDF généré avec succès : {pdf_path}")
except Exception as e:
    print(f"Erreur lors de la génération PDF : {e}")
