#!/usr/bin/env python3
"""Convert MD book to HTML using markdown library. Uses system Python 3.12+."""

import markdown
import sys
import os

md_path = os.path.expanduser("~/Desktop/ФЕНИКС-1_v5_ПОЛНАЯ_КНИГА.md")
css_path = os.path.expanduser("~/.hermes/skills/devops/md-to-html-book/references/style.css")

with open(md_path, 'r') as f:
    md = f.read()

with open(css_path, 'r') as f:
    css = f.read()

h = markdown.markdown(md, extensions=[
    'tables', 'fenced_code', 'codehilite', 'toc', 'nl2br'
], extension_configs={
    'codehilite': {'css_class': 'highlight'},
    'toc': {'permalink': True}
})

title = "Компиляторы — Инженерный журнал одного сознания"

js = """
<!-- Прогресс-бар -->
<div id="progress-bar" style="
  position: fixed; top: 0; left: 0; height: 3px;
  background: #e67e22; width: 0%; z-index: 9999;
  transition: width 0.1s;
"></div>

<!-- Кнопка наверх -->
<div id="top-btn" onclick="window.scrollTo({top:0,behavior:'smooth'})" style="
  position: fixed; bottom: 30px; right: 24px;
  background: #e67e22; color: #000; border-radius: 50%;
  width: 44px; height: 44px; font-size: 20px;
  display: none; align-items: center; justify-content: center;
  cursor: pointer; z-index: 9999;
">↑</div>

<script>
// Прогресс + кнопка наверх
window.addEventListener('scroll', () => {
  const scrolled = window.scrollY;
  const total = document.body.scrollHeight - window.innerHeight;
  document.getElementById('progress-bar').style.width = (scrolled / total * 100) + '%';
  document.getElementById('top-btn').style.display = scrolled > 300 ? 'flex' : 'none';
});

// Сохранение позиции
const BOOK_KEY = 'kompilatory_scroll';

window.addEventListener('scroll', () => {
  localStorage.setItem(BOOK_KEY, window.scrollY);
});

window.addEventListener('load', () => {
  const saved = localStorage.getItem(BOOK_KEY);
  if (saved && parseInt(saved) > 100) {
    const banner = document.createElement('div');
    banner.innerHTML = `📖 Продолжить с места где остановился? 
      <button onclick="window.scrollTo({top:${saved},behavior:'smooth'});this.parentNode.remove()" 
        style="margin-left:12px;background:#e67e22;border:none;padding:6px 14px;
        border-radius:6px;cursor:pointer;color:#000;font-weight:bold">Да</button>
      <button onclick="localStorage.removeItem('${BOOK_KEY}');this.parentNode.remove()" 
        style="margin-left:8px;background:#333;border:none;padding:6px 14px;
        border-radius:6px;cursor:pointer;color:#e0e0e0">Сначала</button>`;
    banner.style.cssText = `position:fixed;bottom:24px;left:50%;transform:translateX(-50%);
      background:#1a1a1a;border:1px solid #e67e22;padding:14px 20px;border-radius:10px;
      z-index:9999;color:#e0e0e0;font-family:Georgia,serif;font-size:14px;
      box-shadow:0 4px 20px rgba(0,0,0,0.5);white-space:nowrap`;
    document.body.appendChild(banner);
    setTimeout(() => banner.remove(), 8000);
  }
});
</script>
"""

html = """<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=yes">
<title>""" + title + """</title>
""" + css + """
</head>
<body>
""" + h + """
""" + js + """
</body>
</html>"""

html_path = os.path.expanduser("~/Desktop/ФЕНИКС-1_v5_ПОЛНАЯ_КНИГА.html")
with open(html_path, 'w') as f:
    f.write(html)

size_kb = os.path.getsize(html_path) / 1024
print(f"HTML written: {html_path} ({size_kb:.0f} KB)")
print(f"Lines: {len(html.splitlines())}")
