#!/usr/bin/env python3

import http.server
import subprocess
import shutil
import os
import re
import time
import threading
from datetime import datetime
from pathlib import Path
from urllib.parse import unquote, quote

ROOT = Path("/mnt/chvnge.de")
PORT = 8889

TEMPLATE = """<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=1000, maximum-scale=1, user-scalable=no">
<title>CHVNGE</title>
<link rel="icon" type="image/png" sizes="32x32" href="/assets/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/assets/favicon-16x16.png">
<link rel="apple-touch-icon" href="/assets/apple-touch-icon.png">
<link rel="stylesheet" href="/style.css">
</head>
<body>
<div class="layout">
  <aside class="sidebar">
    <div class="stucco-top" aria-hidden="true"><img src="/assets/recraft-cornice.svg" alt=""></div>
    <div class="sidebar-frame">
      <div class="stucco-col" aria-hidden="true"><img src="/assets/recraft-column.svg" alt=""></div>
      <div class="sidebar-core">
        <header>
          <a href="/"><img src="/assets/logo.png" alt="CHVNGE"></a>
        </header>
        <nav>
SIDEBAR_TREE
        </nav>
      </div>
      <div class="stucco-col" aria-hidden="true"><img src="/assets/recraft-column.svg" alt=""></div>
    </div>
    <footer>
      <div class="stucco-pedestral" aria-hidden="true"><img src="/assets/recraft-pedestal.svg" alt=""></div>
      <span class="foot-cont">CHVNGE &copy; 2026</span>
      <span class="foot-links">
        <a href="https://chat.whatsapp.com/KgL5Pd9yj8n9hQou6ZEeyE" target="_blank" rel="noopener">Community</a>
        <a href="https://instagram.com/artstuxff" target="_blank" rel="noopener">Instagram</a>
        <a href="https://youtube.com/@chvngethesystem" target="_blank" rel="noopener">YouTube</a>
      </span>
      <span class="foot-wm">Webmaster <a href="https://marlonivo.com" target="_blank" rel="noopener">email@marlonivo.com</a></span>
    </footer>
  </aside>
  <div class="content-area">
    <main>
CONTENT
    </main>
  </div>
</div>
RELOAD_JS
</body>
</html>
"""

clients = []
lock = threading.Lock()

_html_cache = {}
_html_sig_cache = {}


def _html_sig():
    parts = []
    for p in ROOT.rglob("*.md"):
        try:
            parts.append((str(p), p.stat().st_mtime_ns))
        except OSError:
            pass
    for p in ROOT.rglob("*.jpg"):
        try:
            parts.append((str(p), p.stat().st_mtime_ns))
        except OSError:
            pass
    parts.sort()
    import hashlib as _h
    h = _h.md5()
    for k, t in parts:
        h.update((k + str(t)).encode())
    return h.hexdigest()


def _serve_page(self, path, data):
    _html_cache[path] = data
    self.send_response(200)
    self.send_header("Content-Type", "text/html; charset=utf-8")
    self.send_header("Content-Length", str(len(data)))
    self.end_headers()
    self.wfile.write(data)


def handle_html(self, path, thunk):
    sig = _html_sig()
    if _html_sig_cache.get(path) == sig:
        data = _html_cache.get(path)
        if data is not None:
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)
            return
    data = thunk()
    _html_sig_cache[path] = sig
    _serve_page(self, path, data)

RELOAD_JS = """
<script>
(function(){
  function connect(){
    var es = new EventSource("/events");
    es.onmessage = function(e){
      if(e.data==="reload") location.reload();
    };
    es.onerror = function(){
      es.close();
      setTimeout(connect, 1000);
    };
  }
  connect();
})();
</script>
"""

SKIP_DIRS = {"assets", "_thumbs", "Shop"}
HIDE_PAGES = {"AGB", "Jobs", "Contact"}
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
VIDEO_EXTS = {".mp4", ".webm", ".ogv", ".mov", ".m4v", ".mkv"}
POSTER_DIR = "_thumbs"
MAX_PREVIEW = 30

_have_magick = shutil.which("magick") is not None

ANCHOR_SECTIONS = {
    "About": "about",
    "Blogs": "blogs",
    "Collections": "collections",
    "Projects": "projects",
    "Videos": "videos",
}

SPY_JS = """
<script>
(function(){
  var nav = document.querySelector('.sidebar nav');
  if (!nav) return;
  var links = [];
  nav.querySelectorAll('ul > li > a[data-spy]').forEach(function(a){
    var sec = document.getElementById(a.getAttribute('data-spy'));
    if (sec) links.push({a: a, sec: sec, row: a.closest('summary') || a});
  });
  if (!links.length) return;

  var spy = document.createElement('div');
  spy.className = 'spy';
  nav.appendChild(spy);

  var scroller = window;

  function current(){
    var base = window.scrollY;
    var y = base + 130;
    var cur = null;
    for (var i = 0; i < links.length; i++){
      var top = links[i].sec.getBoundingClientRect().top + base;
      if (top <= y) cur = links[i];
    }
    var doc = document.documentElement;
    if (window.innerHeight + window.scrollY >= doc.scrollHeight - 8) cur = links[links.length - 1];
    return cur;
  }

  function update(){
    var cur = current();
    links.forEach(function(l){ l.a.classList.toggle('active', l === cur); });
    nav.querySelectorAll('details').forEach(function(d){ d.open = false; });
    if (cur){
      var det = cur.a.closest('details');
      if (det) det.open = true;
      spy.style.display = 'block';
      spy.style.top = cur.row.offsetTop + 'px';
    } else {
      spy.style.display = 'none';
    }
  }

  window.addEventListener('scroll', update, {passive: true});
  window.addEventListener('resize', update);
  update();
})();
</script>
"""

CAROUSEL_JS = """
<script>
(function(){
  function init(g){
    if (g.dataset.carousel) return;
    g.dataset.carousel = "1";
    g.classList.add("col-carousel");
    g.style.display = "flex";
    g.style.overflowX = "auto";
    g.style.scrollSnapType = "x mandatory";
    g.style.gap = "8px";
    g.style.scrollBehavior = "smooth";
    g.style.webkitOverflowScrolling = "touch";
    g.style.padding = "4px 0";
    var prev = document.createElement("button");
    var next = document.createElement("button");
    prev.textContent = "\\u2039";
    next.textContent = "\\u203a";
    [prev, next].forEach(function(b){
      b.style.position = "absolute";
      b.style.top = "50%";
      b.style.transform = "translateY(-50%)";
      b.style.zIndex = "3";
      b.style.width = "28px";
      b.style.height = "28px";
      b.style.border = "1px solid #e7e7e7";
      b.style.background = "rgba(255,255,255,0.9)";
      b.style.color = "#222";
      b.style.cursor = "pointer";
      b.style.borderRadius = "50%";
      b.style.lineHeight = "1";
    });
    prev.style.left = "4px";
    next.style.right = "4px";
    var host = g.parentElement;
    host.style.position = "relative";
    host.appendChild(prev);
    host.appendChild(next);
    function step(dir){
      g.scrollBy({left: dir * g.clientWidth, behavior: "smooth"});
    }
    prev.addEventListener("click", function(){ step(-1); });
    next.addEventListener("click", function(){ step(1); });
  }
  function scan(){
    document.querySelectorAll("div.g").forEach(init);
  }
  scan();
  document.addEventListener("DOMContentLoaded", scan);
})();
</script>
"""

FOOTER_SCRIPTS = SPY_JS + CAROUSEL_JS + RELOAD_JS


def md_to_html(text):
    r = subprocess.run(
        ["pandoc", "-f", "markdown", "-t", "html5", "--wrap=preserve"],
        input=text, capture_output=True, text=True, timeout=10,
    )
    return r.stdout



def find_md(url_path):
    p = unquote(url_path).strip("/")
    if not p:
        return ROOT / "index.md"

    direct = ROOT / (p + ".md")
    if direct.is_file():
        return direct

    idx = ROOT / p / "index.md"
    if idx.is_file():
        return idx

    md = ROOT / (p + ".md")
    if md.is_file():
        return md

    return None


def _url_path(fs_path):
    rel = fs_path.relative_to(ROOT)
    parts = [quote(p) for p in rel.parts]
    if fs_path.is_dir():
        return "/" + "/".join(parts) + "/"
    else:
        stem = quote(fs_path.stem)
        if fs_path.stem == "index":
            return "/" + "/".join(parts[:-1]) + "/"
        return "/" + "/".join(parts[:-1] + [stem])


def _anchor_href(name):
    anchor = ANCHOR_SECTIONS.get(name)
    return "/#" + anchor if anchor else None


def _spy_id(url_path):
    parts = [unquote(p) for p in url_path.strip("/").split("/")]
    return "-".join(
        re.sub(r"[^a-z0-9]+", "-", p.lower()).strip("-") for p in parts if p
    )


def _generate_tree(dir_path, current_url):
    items = []
    entries = sorted(dir_path.iterdir(), key=lambda e: (not e.is_file(), e.name.lower()))
    has_index = (dir_path / "index.md").is_file() if dir_path != ROOT else False
    for e in entries:
        name = e.name
        if name.startswith(".") or name in SKIP_DIRS:
            continue
        if e.is_dir():
            children = _generate_tree(e, current_url)
            anchor = _anchor_href(name)
            href = anchor if anchor else _url_path(e)
            spy = f' data-spy="{_spy_id(href)}"' if _spy_id(href) else ""
            if children:
                items.append(f'<li><details><summary><a href="{href}"{spy}>{name}</a></summary><ul>{children}</ul></details></li>')
            else:
                items.append(f'<li><a href="{href}"{spy}>{name}</a></li>')
        elif e.suffix.lower() == ".md":
            if has_index and e.stem == "index":
                continue
            if e.parent == ROOT and e.stem in HIDE_PAGES:
                continue
            href = _url_path(e)
            stem = e.stem
            if stem == "index":
                if e.parent == ROOT:
                    continue
                display = e.parent.name
            else:
                display = stem
            cls = ' class="active"' if href == quote(current_url) else ""
            spy = f' data-spy="{_spy_id(href)}"' if _spy_id(href) else ""
            items.append(f'<li><a{cls} href="{href}"{spy}>{display}</a></li>')
        elif e.suffix.lower() in VIDEO_EXTS:
            if e.stem == "index":
                continue
            href = _url_path(e)
            spy = f' data-spy="{_spy_id(href)}"' if _spy_id(href) else ""
            items.append(f'<li><a href="{href}"{spy}>{e.stem}</a></li>')
    return "\n".join(items)


def sidebar_tree(current_url=""):
    items = []
    for name in ANCHOR_SECTIONS:
        href = "/#" + ANCHOR_SECTIONS[name]
        spy = _spy_id(href)
        items.append(f'<li><a href="{href}" data-spy="{spy}">{name}</a></li>')
    return "<ul>\n" + "\n".join(items) + "\n</ul>"


def render_md(md_path, url_path):
    content = md_path.read_text()
    body = md_to_html(content)
    body = rewrite_imgs(body, md_path.parent)
    html = TEMPLATE.replace("SIDEBAR_TREE", sidebar_tree(url_path))
    html = html.replace("CONTENT", body)
    html = html.replace("RELOAD_JS", FOOTER_SCRIPTS)
    return html.encode()


def dir_listing(dir_path, url_path):
    entries = sorted(dir_path.iterdir(), key=lambda e: (e.is_file(), e.name.lower()))
    items = []
    for e in entries:
        name = e.name
        if e.is_dir():
            href = url_path.rstrip("/") + "/" + quote(name) + "/"
            items.append(f'<li><a href="{href}">{name}/</a></li>')
        elif e.suffix.lower() in (".md",):
            href = url_path.rstrip("/") + "/" + quote(e.stem)
            items.append(f'<li><a href="{href}">{e.stem}</a></li>')
        elif e.suffix.lower() in (".jpg", ".jpeg", ".png", ".gif", ".webp", ".pdf"):
            href = url_path.rstrip("/") + "/" + quote(name)
            items.append(f'<li><a href="{href}">{name}</a></li>')

    body = f"<h1>{dir_path.name}</h1><ul>" + "\n".join(items) + "</ul>"
    html = TEMPLATE.replace("SIDEBAR_TREE", sidebar_tree(url_path))
    html = html.replace("CONTENT", body)
    html = html.replace("RELOAD_JS", FOOTER_SCRIPTS)
    return html.encode()


def page(body, url_path):
    body = rewrite_imgs(body, ROOT)
    html = TEMPLATE.replace("SIDEBAR_TREE", sidebar_tree(url_path))
    html = html.replace("CONTENT", body)
    html = html.replace("RELOAD_JS", FOOTER_SCRIPTS)
    return html.encode()


def _preview(text, limit=200):
    date = ""
    body = text
    if text.startswith("---"):
        end = text.find("---", 3)
        if end != -1:
            fm = text[3:end]
            body = text[end + 3:]
            m = re.search(r"^date:\s*(.+)", fm, re.M)
            if m:
                date = m.group(1).strip()
    lines = body.split("\n")
    title = ""
    body_lines = []
    started = False
    for line in lines:
        s = line.strip()
        if not s:
            continue
        if not title:
            title = s.lstrip("#* ").rstrip("*")
            if title:
                started = True
                continue
        if started and not s.startswith("#") and not re.match(r'^!\[.*\]\(.*\)\s*$', s):
            body_lines.append(s)
    preview = re.sub(r"!\[([^\]]*)\]\([^)]*\)\s*", "", " ".join(body_lines))
    preview = re.sub(r"\*+", "", preview)[:limit]
    if len(preview) >= limit:
        preview = preview[: preview.rfind(" ")] + " …"
    if not date:
        m = re.search(r"\d{2}\.\d{2}\.\d{4}", " ".join(body_lines))
        date = m.group(0) if m else ""
    return title or "Blog", preview, date


def _date_span(date):
    if not date:
        return ""
    try:
        d = datetime.strptime(date, "%d.%m.%Y")
        cls = ' class="fut"' if d > datetime.now() else ""
    except ValueError:
        cls = ""
    return f'<time{cls}>{date}</time>'


def blogs_section():
    dir_path = ROOT / "Blogs"
    mds = sorted(
        [f for f in dir_path.iterdir() if f.suffix.lower() == ".md" and f.stem != "index"],
        key=lambda f: f.name.lower()
    )
    cards = []
    for md in mds:
        title, preview, date = _preview(md.read_text())
        href = "/Blogs/" + quote(md.stem)
        cards.append(
            f'<article id="{_spy_id(href)}">'
            f'<div class="stxt">'
            f'<h2><a href="{href}">{title}</a></h2>'
            f'<p>{preview}</p>'
            f'{_date_span(date)}'
            f'<a href="{href}" aria-label="weiterlesen">→</a>'
            f'</div>'
            f"</article>"
        )
    return '<h1>Blogs</h1>\n<div class="blog-grid">' + "\n".join(cards) + "\n</div>"



def _resize(ip, op, w=260, q=65):
    if _have_magick:
        subprocess.run(
            ["magick", str(ip), "-auto-orient", "-resize", f"{w}x>",
             "-strip", "-quality", str(q), str(op)],
            capture_output=True, timeout=45
        )
    else:
        from PIL import Image
        im = Image.open(ip)
        im.thumbnail((w, w))
        im = im.convert("RGB")
        im.save(op, quality=q, optimize=True)
    return op if op.exists() else None


def _make_thumb(img_path):
    name = img_path.stem + (".jpg" if img_path.suffix.lower() in (".png", ".webp") else img_path.suffix.lower())
    thumb = img_path.parent / POSTER_DIR / name
    if thumb.exists():
        return thumb
    try:
        thumb.parent.mkdir(parents=True, exist_ok=True)
        if not _resize(img_path, thumb, w=260, q=65):
            return None
        return thumb if thumb.exists() else None
    except Exception:
        return None


def _web_img(img_path):
    """Kleine Web-Version fuer Markdown-Bilder (max. 1200px, q80, JPEG)."""
    try:
        thumb = img_path.parent / POSTER_DIR / (img_path.stem + ".w.jpg")
        if thumb.exists():
            return thumb
        thumb.parent.mkdir(parents=True, exist_ok=True)
        if not _resize(img_path, thumb, w=1200, q=80):
            return None
        return thumb if thumb.exists() else None
    except Exception:
        return None


IMG_SRC_RE = re.compile(r'<img src="([^"]+)"([^>]*)>')


def rewrite_imgs(body, base_dir):
    """Ersetzt relative <img>-Pfade durch komprimierte Web-Versionen."""
    def rep(m):
        src = m.group(1)
        if src.startswith(("http://", "https://", "data:", "/")):
            return m.group(0)
        p = (base_dir / unquote(src)).resolve()
        try:
            p.relative_to(ROOT)
        except ValueError:
            return m.group(0)
        if not p.is_file() or p.suffix.lower() not in IMAGE_EXTS:
            return m.group(0)
        web = _web_img(p)
        if not web:
            return m.group(0)
        rel = web.relative_to(ROOT)
        url = "/" + "/".join(quote(seg) for seg in rel.parts)
        return f'<img src="{url}"{m.group(2)}>'
    return IMG_SRC_RE.sub(rep, body)


def _gallery_html(dir_path, url_prefix):
    imgs = sorted(
        [f for f in dir_path.iterdir() if f.suffix.lower() in IMAGE_EXTS],
        key=lambda f: f.name.lower()
    )[:MAX_PREVIEW]

    items = []
    for img in imgs:
        thumb = _make_thumb(img)
        href = url_prefix + "/" + quote(img.name)
        src = url_prefix + "/" + POSTER_DIR + "/" + quote(img.name) if thumb else href
        items.append(f'<a class="gi" href="{href}"><img src="{src}" loading="lazy"></a>')

    if not items:
        return ""

    return (
        '<article>'
        f'<div class="g">{"".join(items)}</div>'
        '</article>'
    )


def collections_section():
    dir_path = ROOT / "Collections"
    years = sorted(
        [d for d in dir_path.iterdir() if d.is_dir() and d.name.isdigit()],
        key=lambda d: d.name
    )
    sections = []
    for year_dir in years:
        year_url = f"/Collections/{year_dir.name}"
        year_id = _spy_id(year_url)

        parts = []

        gal = _gallery_html(year_dir, year_url)
        if gal:
            parts.append(gal)

        subdirs = sorted(
            [d for d in year_dir.iterdir() if d.is_dir() and d.name != POSTER_DIR],
            key=lambda d: d.name.lower()
        )
        for sub in subdirs:
            sub_url = f"{year_url}/{quote(sub.name)}"
            sub_gal = _gallery_html(sub, sub_url)
            if sub_gal:
                parts.append(sub_gal)

        if parts:
            sections.append(f'<h2 id="{year_id}">{year_dir.name}</h2>' + "\n".join(parts))
    return "<h1>Collections</h1>\n" + "\n".join(sections)


def pregen_thumbs():
    import concurrent.futures
    imgs = []
    for root in (ROOT / "Collections", ROOT / "Projects"):
        if not root.is_dir():
            continue
        for entry in root.iterdir():
            if entry.is_dir() and not entry.name.startswith("_"):
                imgs += [f for f in entry.iterdir() if f.suffix.lower() in IMAGE_EXTS]
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
        pool.map(_make_thumb, imgs)



def _project_stripe(proj_dir, cat_url):
    name = proj_dir.name
    pid = _spy_id(f"{cat_url}/{quote(name)}")
    images = sorted(
        [f for f in proj_dir.iterdir() if f.suffix.lower() in IMAGE_EXTS],
        key=lambda f: f.name.lower()
    )
    imgs = ""
    if images:
        thumb = _make_thumb(images[0])
        if thumb:
            url = f"{cat_url}/{quote(name)}/{POSTER_DIR}/{quote(thumb.name)}"
        else:
            url = f"{cat_url}/{quote(name)}/{quote(images[0].name)}"
        imgs = f'<img src="{url}" loading="lazy">'

    text = ""
    upcoming = (proj_dir / ".upcoming").is_file()
    idx = proj_dir / "index.md"
    if idx.is_file():
        title, preview, date = _preview(idx.read_text(), limit=400)
        if date:
            href = f"https://chvnge.com/projects/{quote(name)}.ics"
            try:
                d = datetime.strptime(date, "%d.%m.%Y")
                if d > datetime.now():
                    upcoming = True
                    dt = f'<time class="fut"><a href="{href}">{date}</a></time>'
                else:
                    dt = f'<time><a href="{href}">{date}</a></time>'
            except ValueError:
                dt = f'<time><a href="{href}">{date}</a></time>'
        else:
            dt = ""
        text = f"<h3>{title}</h3><p>{preview}</p>{dt}"
    else:
        text = f"<h3>{name}</h3>"

    href = f"{cat_url}/{quote(name)}/"
    cls = ' class="upcoming"' if upcoming else ""
    return (
        f'<article><table class="tl"><tr{cls} id="{pid}">'
        f'<td class="pimg">{imgs}</td>'
        f'<td class="stxt">{text}<a href="{href}">→</a></td>'
        f'</tr></table></article>'
    )


def projects_section():
    dir_path = ROOT / "Projects"
    projects = sorted(
        [d for d in dir_path.iterdir() if d.is_dir() and d.name != "media"],
        key=lambda d: d.name.lower()
    )
    stripes = "\n".join(_project_stripe(p, "/Projects") for p in projects)
    return "<h1>Projekte</h1>\n" + stripes



def _make_video_poster(video_path):
    poster = video_path.parent / POSTER_DIR / (video_path.stem + ".jpg")
    if poster.exists():
        return poster
    try:
        poster.parent.mkdir(parents=True, exist_ok=True)
        dur = subprocess.run(
            ["ffprobe", "-v", "error", "-show_entries", "format=duration",
             "-of", "default=noprint_wrappers=1:nokey=1", str(video_path)],
            capture_output=True, text=True, timeout=10
        ).stdout.strip()
        try:
            d = float(dur)
        except ValueError:
            d = 0
        seek = 2 if d <= 0 else min(d * 0.2, 60)
        subprocess.run(
            [
                "ffmpeg", "-y", "-loglevel", "error",
                "-ss", f"{seek:.2f}", "-i", str(video_path),
                "-frames:v", "1", "-vf", "scale=480:-1",
                str(poster),
            ],
            capture_output=True, timeout=120
        )
        if poster.exists():
            return poster
    except Exception:
        pass
    return None


def _video_preview(text, limit=140):
    title = ""
    date = ""
    desc = []
    in_desc = False
    for line in text.splitlines():
        s = line.strip()
        if s.startswith("# ") and not title:
            title = s[2:].strip()
        elif s.startswith("- **Veröffentlicht:**"):
            d = s.split("**Veröffentlicht:**", 1)[1].strip()
            if len(d) == 8 and d.isdigit():
                date = f"{d[6:8]}.{d[4:6]}.{d[0:4]}"
        elif s.startswith("## "):
            in_desc = s == "## Beschreibung"
        elif in_desc and s:
            desc.append(s)
    preview = " ".join(desc)
    if len(preview) > limit:
        cut = preview[:limit]
        preview = cut[:cut.rfind(" ")] if " " in cut else cut
        preview = preview.rstrip() + "…"
    return title, preview, date


def _video_card(year_dir, vdir):
    base_url = "/Videos/" + year_dir.name + "/" + quote(vdir.name)
    vids = sorted(
        [f for f in vdir.iterdir() if f.suffix.lower() in VIDEO_EXTS],
        key=lambda f: f.name.lower()
    )[:MAX_PREVIEW]
    if not vids:
        return None
    v = vids[0]
    video_url = base_url + "/" + quote(v.name)
    poster = v.parent / POSTER_DIR / (v.stem + ".jpg")
    if not poster.exists():
        threading.Thread(target=_make_video_poster, args=(v,), daemon=True).start()
    poster_src = base_url + "/" + POSTER_DIR + "/" + quote(poster.name) if poster.exists() else ""

    web = v.parent / POSTER_DIR / "web.mp4"
    if web.exists():
        video_url = base_url + "/" + POSTER_DIR + "/web.mp4"

    title, preview, date = vdir.name, "", ""
    idx = vdir / "index.md"
    if idx.is_file():
        title, preview, date = _video_preview(idx.read_text())
        if not title:
            title = vdir.name

    img = ""
    if video_url:
        img = (
            f'<video class="vplayer" controls preload="none" playsinline'
            + (f' poster="{poster_src}"' if poster_src else '')
            + f' src="{video_url}"></video>'
        )
    dt = f'<time>{date}</time>' if date else ""
    text = f"<h3>{title}</h3>"
    if preview:
        text += f"<p>{preview}</p>"
    text += dt
    vid = _spy_id(base_url)
    return (
        f'<article id="{vid}">'
        f"{img}"
        f'<div class="stxt">{text}'
        f'<a href="{video_url}" target="_blank" rel="noopener" aria-label="Vollbild öffnen">→</a></div>'
        f"</article>"
    )


def videos_section():
    dir_path = ROOT / "Videos"
    years = sorted(
        [d for d in dir_path.iterdir() if d.is_dir() and d.name.isdigit()],
        key=lambda d: d.name, reverse=True
    )
    sections = []
    for year_dir in years:
        year_id = _spy_id("/Videos/" + year_dir.name)
        cards = []
        for vdir in sorted(
            [d for d in year_dir.iterdir() if d.is_dir()],
            key=lambda d: d.name.lower()
        ):
            card = _video_card(year_dir, vdir)
            if card:
                cards.append(card)
        if cards:
            rows = []
            for i in range(0, len(cards), 4):
                cells = "".join(f"<td>{c}</td>" for c in cards[i:i + 4])
                rows.append(f"<tr>{cells}</tr>")
            sections.append(
                f'<h2 id="{year_id}">{year_dir.name}</h2>\n'
                "<table>" + "".join(rows) + "</table>"
            )
    return "<h1>Videos</h1>\n" + "\n".join(sections)


def pregen_videos():
    video_root = ROOT / "Videos"
    if video_root.is_dir():
        import concurrent.futures
        vids = []
        for d in video_root.iterdir():
            if d.is_dir() and d.name.isdigit():
                for vdir in d.iterdir():
                    if vdir.is_dir():
                        vids += [f for f in vdir.iterdir() if f.suffix.lower() in VIDEO_EXTS]
        with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
            pool.map(_make_video_poster, vids)



def index_body():
    parts = [
        md_to_html((ROOT / "index.md").read_text()),
        '<section class="sec" id="blogs">' + blogs_section() + "</section>",
        '<section class="sec" id="collections">' + collections_section() + "</section>",
        '<section class="sec" id="projects">' + projects_section() + "</section>",
        '<section class="sec" id="videos">' + videos_section() + "</section>",
    ]
    return "\n".join(parts)



class Handler(http.server.BaseHTTPRequestHandler):
    def do_HEAD(self):
        raw, _, query = self.path.partition("?")
        fs_path = ROOT / unquote(raw).lstrip("/")
        if not fs_path.is_file():
            self.send_response(404)
            self.end_headers()
            return
        self.command = "HEAD"
        self.do_GET()

    def do_GET(self):
        raw, _, query = self.path.partition("?")
        path = unquote(raw)

        if path == "/events":
            self.send_response(200)
            self.send_header("Content-Type", "text/event-stream")
            self.send_header("Cache-Control", "no-cache")
            self.send_header("Connection", "keep-alive")
            self.end_headers()
            q = []
            with lock:
                clients.append(q)
            try:
                while True:
                    if q:
                        self.wfile.write(b"data: reload\n\n")
                        self.wfile.flush()
                        break
                    time.sleep(0.3)
            except (BrokenPipeError, OSError):
                pass
            finally:
                with lock:
                    if q in clients:
                        clients.remove(q)
            return

        if path.strip("/") == "":
            handle_html(self, path, lambda: page(index_body(), path))
            return

        fs_path = ROOT / path.lstrip("/")

        if fs_path.is_dir():
            if path.strip("/") == "Blogs":
                handle_html(self, path, lambda: page(blogs_section(), path))
            elif path.strip("/") == "Collections":
                handle_html(self, path, lambda: page(collections_section(), path))
            elif path.strip("/") == "Projects":
                handle_html(self, path, lambda: page(projects_section(), path))
            elif path.strip("/") == "Videos":
                handle_html(self, path, lambda: page(videos_section(), path))
            else:
                index = fs_path / "index.md"
                if index.is_file():
                    handle_html(self, path, lambda: render_md(index, path))
                else:
                    handle_html(self, path, lambda: dir_listing(fs_path, path))
            return

        md_path = find_md(path)
        if md_path and md_path.is_file():
            handle_html(self, path, lambda: render_md(md_path, path))
            return

        if fs_path.is_file():
            ext = fs_path.suffix.lower()
            ct = {
                ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
                ".png": "image/png", ".gif": "image/gif",
                ".webp": "image/webp", ".pdf": "application/pdf",
                ".css": "text/css", ".js": "application/javascript",
                ".svg": "image/svg+xml",
                ".mp4": "video/mp4", ".webm": "video/webm",
                ".ogv": "video/ogg", ".mov": "video/quicktime", ".m4v": "video/x-m4v",
            }.get(ext, "application/octet-stream")
            st = fs_path.stat()
            size = st.st_size
            etag = '"%x-%x"' % (st.st_mtime_ns, size)
            inm = self.headers.get("If-None-Match", "")
            if inm == etag:
                self.send_response(304)
                self.end_headers()
                return
            cc = "no-cache"
            if ext not in (".html", ".md"):
                cc = "public, max-age=3600"
            self.send_header("ETag", etag)
            self.send_header("Cache-Control", cc)
            disp = ""
            if ext in VIDEO_EXTS and self.headers.get("Accept", "") == "application/octet-stream":
                disp = f'Content-Disposition: attachment; filename="{fs_path.name}"'
            rng = self.headers.get("Range", "")
            if rng.startswith("bytes="):
                start = end = None
                try:
                    a, b = rng[6:].split("-", 1)
                    start = int(a) if a else 0
                    end = int(b) if b else size - 1
                except ValueError:
                    pass
                if start is None:
                    start, end = 0, size - 1
                if start >= size:
                    self.send_response(416)
                    self.send_header("Content-Range", f"bytes */{size}")
                    self.end_headers()
                    return
                end = min(end, size - 1)
                length = end - start + 1
                self.send_response(206)
                self.send_header("Content-Type", ct)
                self.send_header("Accept-Ranges", "bytes")
                self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
                self.send_header("Content-Length", str(length))
                if disp:
                    self.send_header("Content-Disposition", disp[21:])
                if self.command == "HEAD":
                    self.end_headers()
                    return
                self.end_headers()
                with open(fs_path, "rb") as f:
                    f.seek(start)
                    remaining = length
                    while remaining:
                        chunk = f.read(min(65536, remaining))
                        if not chunk:
                            break
                        self.wfile.write(chunk)
                        remaining -= len(chunk)
                return
            self.send_response(200)
            self.send_header("Content-Type", ct)
            self.send_header("Accept-Ranges", "bytes")
            self.send_header("Content-Length", str(size))
            if disp:
                self.send_header("Content-Disposition", disp[21:])
            if self.command == "HEAD":
                self.end_headers()
                return
            self.end_headers()
            with open(fs_path, "rb") as f:
                while True:
                    chunk = f.read(65536)
                    if not chunk:
                        break
                    self.wfile.write(chunk)
            return

        self.send_error(404)

    def do_POST(self):
        self.send_error(404)

    def log_message(self, fmt, *args):
        print(f"  {args[0]}")


def notify():
    with lock:
        for q in clients:
            try:
                q.append(1)
            except Exception:
                pass


def watch():
    mtimes = {}
    for md in ROOT.rglob("*.md"):
        mtimes[str(md)] = md.stat().st_mtime
    for jpg in ROOT.rglob("*.jpg"):
        mtimes[str(jpg)] = jpg.stat().st_mtime

    while True:
        time.sleep(0.5)
        changed = False
        for md in ROOT.rglob("*.md"):
            key = str(md)
            try:
                t = md.stat().st_mtime
            except OSError:
                continue
            if mtimes.get(key) != t:
                mtimes[key] = t
                print(f"  [reload] {md.relative_to(ROOT)}")
                changed = True
        for jpg in ROOT.rglob("*.jpg"):
            key = str(jpg)
            try:
                t = jpg.stat().st_mtime
            except OSError:
                continue
            if mtimes.get(key) != t:
                mtimes[key] = t
                print(f"  [reload] {jpg.relative_to(ROOT)}")
                changed = True
        if changed:
            notify()


if __name__ == "__main__":
    os.chdir(ROOT)
    t = threading.Thread(target=watch, daemon=True)
    t.start()
    pt = threading.Thread(target=pregen_thumbs, daemon=True)
    pt.start()
    pv = threading.Thread(target=pregen_videos, daemon=True)
    pv.start()
    print("  [thumbs] pre-generating thumbnails…")
    print("  [videos] pre-generating posters…")
    http.server.HTTPServer.allow_reuse_address = True
    server = http.server.ThreadingHTTPServer(("0.0.0.0", PORT), Handler)
    print(f"CHVNGE dev server: http://0.0.0.0:{PORT}")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nStopped.")
