#!/usr/bin/env python3
import os
import re
import functools
import hashlib
from http.server import HTTPServer, SimpleHTTPRequestHandler
import markdown

PORT = 333
DIR = "/mnt/week.futurefashion.de"
MD_FILE = os.path.join(DIR, "index.md")
LOGOS_DIR = os.path.join(DIR, "assets", "logos")
PROGRAM_CSV = os.path.join(DIR, "program.csv")
STYLE_FILE = os.path.join(DIR, "style.css")
LOGO_URL = "assets/logos"
BG_IMG = "assets/bg.jpg"
FAVICON = "assets/favicon/favicon.ico"

MD_EXTENSIONS = ["tables", "nl2br", "fenced_code", "sane_lists"]


def md_inline(text):
    return markdown.markdown(text, extensions=MD_EXTENSIONS).replace("<p>", "").replace("</p>", "")


def read_text(path):
    try:
        with open(path, "r", encoding="utf-8", errors="replace") as f:
            return f.read()
    except FileNotFoundError:
        return ""


LOGO_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".gif", ".svg"}


def build_program_table():
    text = read_text(PROGRAM_CSV)
    if not text.strip():
        return ""
    headers = ["Shows", "Education", "Showrooms"]
    lists = {}
    current = None
    for line in text.split("\n"):
        line = line.rstrip()
        if line.strip() in headers:
            current = line.strip()
            lists[current] = []
            continue
        if current is None:
            continue
        entry = line.strip()
        if entry:
            lists[current].append(entry)
    out = ['<table class="program">', "<thead><tr>"]
    for h in headers:
        out.append(f"<th>{h}</th>")
    out.append("</tr></thead><tbody><tr>")
    for h in headers:
        out.append("<td>")
        entries = lists.get(h, [])
        for i, entry in enumerate(entries):
            out.append(f'<div class="entry">{md_inline(entry)}</div>')
        out.append("</td>")
    out.append("</tr></tbody></table>")
    return "\n".join(out)


def file_url(path):
    try:
        import subprocess
        return subprocess.run(
            ["getfattr", "--only-values", "-n", "user.url", path],
            capture_output=True, text=True, timeout=5
        ).stdout.strip() or "#"
    except Exception:
        return "#"


def scan_logos():
    try:
        entries = sorted(os.listdir(LOGOS_DIR), key=lambda s: s.lower())
    except OSError:
        return []
    logos = []
    for name in entries:
        ext = os.path.splitext(name)[1].lower()
        if ext in LOGO_EXTS:
            url = file_url(os.path.join(LOGOS_DIR, name))
            alt = os.path.splitext(name)[0].replace("_", " ").replace("-", " ")
            logos.append((name, alt, url))
    return logos


def build_logos_html():
    logos = scan_logos()
    if not logos:
        return ""
    items = []
    for name, alt, url in logos:
        items.append(
            f'    <a href="{url}" target="_blank" rel="noopener">'
            f'<img src="{LOGO_URL}/{name}" alt="{alt}"></a>'
        )
    return "<div class=\"logos\">\n" + "\n".join(items) + "\n</div>"


ARCHIV_DIR = os.path.join(DIR, "assets", "archiv_web")
RECAP2026_DIR = os.path.join(DIR, "assets", "recap_2026")


def _recap_grid(urlroot, vids, pics, caption):
    fig_style = (
        "border:3px solid #0b0206;border-radius:18px 14px 20px 12px;"
        "overflow:hidden;background:#f48fb1;box-shadow:1px 2px 5px rgba(11,2,6,0.20);"
        "margin:0;"
    )
    cap_style = (
        "padding:8px 10px;font-weight:900;text-transform:uppercase;"
        "font-size:12px;letter-spacing:0.06em;color:#0b0206;background:#f48fb1;"
    )
    med_style = "width:100%;height:150px;object-fit:cover;display:block;border-bottom:2px solid #0b0206;"
    figures = []
    for i, n in enumerate(vids):
        figures.append(
            f'<figure style="{fig_style}">'
            f'<video muted loop playsinline preload="auto" style="{med_style}">'
            f'<source src="{urlroot}{n}" type="video/mp4"></video>'
            f'<figcaption style="{cap_style}">{caption("film", i)}</figcaption></figure>'
        )
    for i, n in enumerate(pics):
        figures.append(
            f'<figure style="{fig_style}">'
            f'<img src="{urlroot}{n}" loading="eager" decoding="sync" style="{med_style}" alt="recap">'
            f'<figcaption style="{cap_style}">{caption("pic", i)}</figcaption></figure>'
        )
    return (
        '<div class="recap" style="display:grid;grid-template-columns:repeat(4,1fr);'
        'gap:16px;margin:28px 0;">' + "".join(figures) + "</div>"
    )


RECAP_CAPS = [
    "runway lights",
    "the walk",
    "future silhouettes",
    "backstage",
    "press pit",
    "hands & fabric",
    "the crowd",
    "after hours",
    "studio",
    "front row",
    "the look",
    "together",
    "spotlight",
    "last walk",
]


def build_archive_html():
    if not os.path.isdir(ARCHIV_DIR):
        return ""
    names = sorted(os.listdir(ARCHIV_DIR))
    pics = [n for n in names if n.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))]
    vids = [n for n in names if n.lower().endswith((".mp4", ".webm"))]
    def caption(kind, i):
        return f"recap film {i + 1:02d}" if kind == "film" else RECAP_CAPS[i % len(RECAP_CAPS)]
    return _recap_grid("assets/archiv_web/", vids, pics, caption)


def build_recap2026_html():
    if not os.path.isdir(RECAP2026_DIR):
        return ""
    names = sorted(os.listdir(RECAP2026_DIR))
    pics = [n for n in names if n.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))]
    vids = [n for n in names if n.lower().endswith((".mp4", ".webm"))]
    if not pics and not vids:
        return ""
    def caption(kind, i):
        return f"recap 2026 film {i + 1:02d}" if kind == "film" else RECAP_CAPS[i % len(RECAP_CAPS)]
    return _recap_grid("assets/recap_2026/", vids, pics, caption)


def content_version():
    h = hashlib.md5()
    for path in (MD_FILE, STYLE_FILE, PROGRAM_CSV):
        h.update(path.encode())
        h.update(read_text(path).encode())
    for name, _, _ in scan_logos():
        path = os.path.join(LOGOS_DIR, name)
        h.update(path.encode())
        h.update(read_text(path).encode())
    return h.hexdigest()


PAGE_TEMPLATE = """<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=1000, maximum-scale=1, user-scalable=no">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<meta name="mobile-web-app-capable" content="yes">
<title>Future Fashion Week</title>
<link rel="icon" type="image/x-icon" href="{favicon}">
<style>__STYLE_INLINE__</style>
<script defer src="assets/cursor.js"></script>
<script>
let v = "{version}";
setInterval(function () {{
  fetch('/__md_version', {{cache: 'no-store'}}).then(function (r) {{ return r.text(); }}).then(function (n) {{
    if (n.trim() !== v) location.reload();
  }}).catch(function () {{}});
}}, 1500);
function startVideos() {{
  var vids = document.querySelectorAll('video');
  if (!('IntersectionObserver' in window)) {{
    vids.forEach(function (vid) {{
      vid.muted = true;
      vid.setAttribute('preload', 'auto');
      var p = vid.play();
      if (p && p.catch) p.catch(function () {{}});
    }});
    return;
  }}
  var io = new IntersectionObserver(function (entries) {{
    entries.forEach(function (en) {{
      var vid = en.target;
      vid.muted = true;
      if (en.isIntersecting) {{
        vid.setAttribute('preload', 'auto');
        var p = vid.play();
        if (p && p.catch) p.catch(function () {{}});
      }} else {{
        vid.pause();
      }}
    }});
  }}, {{ rootMargin: '300px 0px' }});
  vids.forEach(function (vid) {{
    vid.setAttribute('preload', 'auto');
    vid.play().catch(function() {{}});
  }});
}}
function unifyMarquees() {{
  var SPEED = 70;
  document.querySelectorAll('.marquee span').forEach(function (sp) {{
    var w = sp.scrollWidth || 1;
    sp.style.animationDuration = (w / SPEED) + 's';
  }});
}}
document.addEventListener("DOMContentLoaded", function () {{ startVideos(); unifyMarquees(); }});
window.addEventListener("load", function () {{ startVideos(); unifyMarquees(); }});
</script>
</head>
<body class="grain">
<div class="book-wrap">
  <button class="nav-btn prev" id="prevBtn" onclick="flip(-1)">&#10094;</button>
  {book}
  <button class="nav-btn next" id="nextBtn" onclick="flip(1)">&#10095;</button>
</div>
<script>
let cur = 0;
const pages = document.querySelectorAll('.page');
const perSpread = 2;
function totalSpreads() {{ return Math.ceil(pages.length / perSpread); }}
function showSpread(i) {{
  const start = i * perSpread;
  pages.forEach((p, idx) => {{
    p.classList.remove('active');
    if (idx >= start && idx < start + perSpread) p.classList.add('active');
  }});
  document.getElementById('prevBtn').disabled = (i === 0);
  document.getElementById('nextBtn').disabled = (i === totalSpreads() - 1);
  cur = i;
}}
function flip(d) {{ const book = document.getElementById('book'); book.classList.add('flipping'); setTimeout(() => {{ showSpread(Math.max(0, Math.min(totalSpreads()-1, cur + d))); book.classList.remove('flipping'); }}, 300); }}
showSpread(0);
document.addEventListener('keydown', e => {{
  if (e.key === 'ArrowLeft') flip(-1);
  if (e.key === 'ArrowRight') flip(1);
}});
</script>
</body>
</html>"""


SPALTE2 = "<!-- spalte2 -->"
LIVE_URL = "https://youtube.com/live/G-qleBSswc0"
LOGO_RE = re.compile(
    r'<p><img[^>]*src="assets/Logo_chrome_ffw\.png"[^>]*></p>'
)


STICKER_DIR = os.path.join(DIR, "assets", "sticker")


def sticker_html(name, fn):
    return (
        f'<div class="sticker-anchor sticker-{name}">'
        f'<img src="assets/sticker/{fn}" alt=""></div>'
    )


def insert_stickers(body):
    if not os.path.isdir(STICKER_DIR):
        return body
    out = body
    if os.path.isfile(os.path.join(STICKER_DIR, "mochis.png")):
        out = out.replace(
            '<section class="plate plate-indigo">',
            sticker_html("mochi", "mochis.png")
            + '<section class="plate plate-indigo">',
            1,
        )
    if os.path.isfile(os.path.join(STICKER_DIR, "queen.png")):
        out = out.replace(
            "<!--sticker-t1-->",
            "<!--sticker-t1-->" + sticker_html("queen", "queen.png"),
            1,
        )
    if os.path.isfile(os.path.join(STICKER_DIR, "waving-cat.png")):
        out = out.replace(
            '<div class="logos">',
            sticker_html("cat", "waving-cat.png")
            + '<div class="logos">',
            1,
        )
    if os.path.isfile(os.path.join(STICKER_DIR, "hamster.png")):
        m = re.search(r'<section class="plate plate-magenta">', out)
        if m:
            out = out[: m.start()] + sticker_html("hamster", "hamster.png") + out[m.start() :]
    return out


def wrap_hero(body):
    m = LOGO_RE.search(body)
    if not m:
        return body
    logo = m.group(0)
    after_logo = m.end()
    video_pos = body.find("<video", after_logo)
    if video_pos == -1:
        return body
    text = body[after_logo:video_pos]
    close_boxes = ""
    mt = re.search(r"((?:\s*<!--\s*/box\s*-->\s*)+)$", text)
    if mt:
        close_boxes = mt.group(1).strip()
        text = text[: mt.start()]
    if os.path.isfile(os.path.join(STICKER_DIR, "spongebob.png")):
        sticker = sticker_html("sponge", "spongebob.png")
    else:
        sticker = ""
    hero = (
        '<div class="hero-block">'
        f'<div class="hero-left">{logo}</div>'
        f'<div class="hero-right">{text}</div>'
        f"{sticker}</div>"
        + (close_boxes if close_boxes else "")
    )
    return body[: m.start()] + hero + body[video_pos:]


def spalte2_pairs(body):
    positions = [m.start() for m in re.finditer(re.escape(SPALTE2), body)]
    if len(positions) < 2 or len(positions) % 2 != 0:
        return body
    out = ""
    prev = 0
    colors = ["magenta", "teal", "indigo", "gold", "denim", "rose"]
    for idx, i in enumerate(range(0, len(positions), 2)):
        a, b = positions[i], positions[i + 1]
        segment = body[prev:a]
        if idx == 0:
            h1 = segment.rfind("<h1")
            if h1 != -1:
                out += segment[:h1]
                left = segment[h1:]
            else:
                left = segment
        else:
            left = segment
        mid = body[a + len(SPALTE2) : b]
        cls = "eventcols equal" if idx > 0 else "eventcols"
        marker = "sticker-t1" if idx == 0 else "sticker-t2"
        if idx == 0:
            cell_left, cell_right = mid, left
        else:
            cell_left, cell_right = left, mid
        color = colors[idx % len(colors)]
        out += (
            f'<section class="plate plate-{color}"><span class="seam"></span>'
            f'<div class="plate-inner">'
            f'<table class="{cls}"><tr>'
            f'<td valign="top">{cell_left}</td>'
            f'<td valign="top">{cell_right}</td>'
            f"</tr></table></div></section><!--{marker}-->"
        )
        prev = b + len(SPALTE2)
    out += body[prev:]
    return out


def link_glitch(body):
    v = re.search(
        r"<video[^>]*>\s*<source src=\"assets/glitch-ffw\.mp4\"[^>]*>\s*<img[^>]*>\s*</video>",
        body,
        re.S,
    )
    if not v:
        return body
    return (
        body[: v.start()]
        + f'<a class="glitch-link" href="{LIVE_URL}" target="_blank" rel="noopener">{v.group(0)}</a>'
        + body[v.end() :]
    )


PLATE_COLORS = ["magenta", "indigo", "denim", "night", "gold", "teal", "rose"]


SECTION_COLORS = {"section1": "gold", "section2": "rose", "section3": "denim", "section4": "teal"}


def wrap_sections(body):
    def open_box(m):
        key = m.group(1)
        color = SECTION_COLORS.get(key, key)
        return f'<section class="plate plate-{color}"><span class="seam"></span><div class="plate-inner">'
    body = re.sub(r"<!--\s*box:([a-z]+)\s*-->", open_box, body)
    body = re.sub(r"<!--\s*(section[0-9]+)\s*-->", open_box, body)
    body = body.replace("<!-- /box -->", "</div></section>")
    for n in ("1", "2", "3", "4", "5", "6"):
        body = body.replace(f"<!-- /section{n} -->", "</div></section>")
    return body


def force_link_style(body):
    idx = body.find('<div class="logos">')
    head = body if idx == -1 else body[:idx]
    tail = "" if idx == -1 else body[idx:]
    link_style = (
        ' style="background:#fce433 !important;color:#0b0206 !important;'
        'padding:2px 8px !important;border:2px solid #0b0206 !important;'
        'border-radius:10px 14px 8px 16px !important;'
        'text-decoration:underline !important;text-decoration-color:#e91e8c !important;'
        'text-decoration-thickness:3px !important;text-underline-offset:3px !important;'
        'font-weight:900 !important;box-shadow:1px 2px 4px rgba(11,2,6,0.2) !important;'
        'display:inline-block;line-height:1.25;"'
    )
    head = re.sub(
        r'<a(?![^>]*class="glitch-link")(?![^>]*\sstyle=)([^>]*)>',
        lambda m: '<a' + m.group(1) + link_style + '>',
        head,
    )
    return head + tail


def render_index():
    md = read_text(MD_FILE)
    logos = build_logos_html()
    program = build_program_table()
    body = markdown.markdown(md, extensions=MD_EXTENSIONS)
    body = body.replace("{{logos}}", logos)
    body = body.replace("{{program}}", program)
    body = body.replace("{{archiv}}", build_archive_html())
    body = body.replace("{{recap2026}}", build_recap2026_html())
    body = body.replace("<p></p>", "")
    body = re.sub(
        r"<p>(<table class=\"program\">.*?</table>)</p>", r"\1", body, flags=re.S
    )
    body = re.sub(
        r"<p>(<div class=\"logos\">.*?</div>)</p>", r"\1", body, flags=re.S
    )
    body = wrap_hero(body)
    body = spalte2_pairs(body)
    body = wrap_sections(body)
    body = link_glitch(body)
    body = insert_stickers(body)
    body = re.sub(
        r'<a(?![^>]*\btarget=)([^>]*)>',
        lambda m: '<a' + m.group(1) + ' target="_blank" rel="noopener">',
        body,
    )
    body = force_link_style(body)
    # Split body into pages by <section> elements (each section = one page)
    import re as _re
    page_sections = _re.findall(r'<section class="plate[^"]*">.*?</section>', body, _re.S)
    if not page_sections:
        page_sections = [body]
    pages_html = "".join(
        f'<div class="page"><div class="page-inner">{sec}</div><div class="page-num">{i+1}</div></div>'
        for i, sec in enumerate(page_sections)
    )
    book = f'<div class="book" id="book">{pages_html}</div>'
    page = PAGE_TEMPLATE.format(
        book=book,
        version=content_version(),
        cssv=content_version(),
        favicon=FAVICON,
    )
    return page.replace("__STYLE_INLINE__", read_text(STYLE_FILE))


class Handler(SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
        super().end_headers()

    def do_GET(self):
        path = self.path.split("?")[0]
        if path in ("/", "/index.md", "/index.html"):
            page = render_index()
            self.send_response(200)
            self.send_header("Content-type", "text/html; charset=utf-8")
            self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
            self.end_headers()
            self.wfile.write(page.encode())
            return
        if path == "/__md_version":
            self.send_response(200)
            self.send_header("Content-type", "text/plain")
            self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
            self.end_headers()
            self.wfile.write(content_version().encode())
            return
        return super().do_GET()


if __name__ == "__main__":
    HTTPServer(("0.0.0.0", PORT), functools.partial(Handler, directory=DIR)).serve_forever()
