from __future__ import annotations

import html
import re
import shutil
from pathlib import Path


ROOT = Path("/var/xuda/tmp/codex-test/boaz-wiki")
SOURCE = ROOT / "boaz_avrahami_updated_with_academic_recognition.md"
IMAGE = ROOT / "BOAZ_AVRAHAMI_67.png"
PDF = Path("/var/xuda/tmp/codex-test/boaz-wiki-attachments/Boaz_Globes_CRM_2004.pdf")
OUT = Path("/tmp/boaz-wiki-site")


def slugify(index: int) -> str:
    return f"section-{index:02d}"


def inline_markup(text: str) -> str:
    text = html.unescape(text)
    links: list[tuple[str, str]] = []

    def replace_link(match: re.Match[str]) -> str:
        token = f"__LINK_{len(links)}__"
        label = html.escape(match.group(1), quote=False)
        url = html.escape(match.group(2), quote=True)
        links.append(
            (
                token,
                f'<a class="inline-link" href="{url}" target="_blank" rel="noopener noreferrer">{label}</a>',
            )
        )
        return token

    text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", replace_link, text)
    text = html.escape(text, quote=False)
    text = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", text)
    text = re.sub(r"`(.+?)`", r"<code>\1</code>", text)
    for token, anchor in links:
        text = text.replace(token, anchor)
    return text


def paragraph(lines: list[str]) -> str:
    return f"<p>{inline_markup(' '.join(line.strip() for line in lines))}</p>"


def markdown_to_html(markdown: str) -> tuple[str, list[dict[str, str]]]:
    lines = markdown.splitlines()
    first_title = next((i for i, line in enumerate(lines) if line.strip().startswith("# ")), 0)
    lines = lines[first_title:]

    html_parts: list[str] = []
    headings: list[dict[str, str]] = []
    paragraph_lines: list[str] = []
    list_items: list[str] = []
    section_index = 0

    def flush_paragraph() -> None:
        nonlocal paragraph_lines
        if paragraph_lines:
            html_parts.append(paragraph(paragraph_lines))
            paragraph_lines = []

    def flush_list() -> None:
        nonlocal list_items
        if list_items:
            html_parts.append("<ul>" + "".join(f"<li>{item}</li>" for item in list_items) + "</ul>")
            list_items = []

    for raw in lines:
        line = raw.strip()

        if not line:
            flush_paragraph()
            flush_list()
            continue

        heading = re.match(r"^(#{1,4})\s+(.+)$", line)
        bullet = re.match(r"^\*\s+(.+)$", line)

        if heading:
            flush_paragraph()
            flush_list()
            level = len(heading.group(1))
            title = html.unescape(heading.group(2)).strip()
            if level == 1:
                html_parts.append(f'<h1 id="top">{inline_markup(title)}</h1>')
            else:
                section_index += 1
                sid = slugify(section_index)
                if level in (2, 3):
                    headings.append({"level": str(level), "title": title, "id": sid})
                html_parts.append(f'<h{level} id="{sid}">{inline_markup(title)}</h{level}>')
            continue

        if bullet:
            flush_paragraph()
            list_items.append(inline_markup(bullet.group(1)))
            continue

        flush_list()
        paragraph_lines.append(line)

    flush_paragraph()
    flush_list()
    return "\n".join(html_parts), headings


def build() -> None:
    OUT.mkdir(parents=True, exist_ok=True)
    assets = OUT / "assets"
    assets.mkdir(exist_ok=True)
    shutil.copyfile(IMAGE, assets / "boaz-avrahami.png")
    shutil.copyfile(PDF, assets / "boaz-globes-crm-2004.pdf")

    source = SOURCE.read_text(encoding="utf-8")
    note = ""
    body_lines = []
    for line in source.splitlines():
        if line.startswith(">"):
            note = line[1:].strip()
        else:
            body_lines.append(line)

    article_html, headings = markdown_to_html("\n".join(body_lines))
    toc_items = "\n".join(
        f'<a class="toc-link level-{item["level"]}" href="#{item["id"]}">{html.escape(item["title"])}</a>'
        for item in headings
    )

    (assets / "styles.css").write_text(CSS, encoding="utf-8")
    (assets / "site.js").write_text(JS, encoding="utf-8")

    page = HTML_TEMPLATE.format(
        article=article_html,
        toc=toc_items,
        note=inline_markup(note),
    )
    (OUT / "index.html").write_text(page, encoding="utf-8")


HTML_TEMPLATE = """<!doctype html>
<html lang="he" dir="ltr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>בועז אברהמי | ערך ויקי</title>
  <meta name="description" content="ערך ביוגרפי בסגנון ויקי על בועז אברהמי: יזמות טכנולוגית, מערכות מידע, מוזיקה, XUDA, NewDeal ופעילות מקצועית.">
  <meta property="og:title" content="בועז אברהמי | ערך ויקי">
  <meta property="og:description" content="ביוגרפיה אנציקלופדית של בועז אברהמי ופעילותו בתחומי התוכנה, היזמות, המוזיקה והבינה המלאכותית.">
  <meta property="og:image" content="/assets/boaz-avrahami.png">
  <link rel="stylesheet" href="/assets/styles.css">
  <script src="/assets/site.js" defer></script>
</head>
<body>
  <div class="progress" aria-hidden="true"><span></span></div>
  <header class="site-header">
    <a class="brand" href="#top" aria-label="בועז אברהמי">
      <span class="brand-mark">BA</span>
      <span>בועז אברהמי</span>
    </a>
    <nav aria-label="ניווט ראשי">
      <a href="#section-04">טכנולוגיה</a>
      <a href="#section-13">XUDA</a>
      <a href="#section-18">השפעה</a>
    </nav>
  </header>

  <main class="page-shell">
    <aside class="toc-panel" aria-label="תוכן עניינים">
      <div class="toc-tools">
        <label for="toc-search">חיפוש בערך</label>
        <input id="toc-search" type="search" placeholder="חפש נושא, חברה או שנה">
      </div>
      <div class="toc-list">
        {toc}
      </div>
    </aside>

    <article class="article">
      <div class="source-note">{note}</div>
      {article}
    </article>

    <aside class="infobox" aria-label="פרטים ביוגרפיים">
      <img src="/assets/boaz-avrahami.png" alt="בועז אברהמי">
      <h2>בועז אברהמי</h2>
      <dl>
        <div><dt>נולד</dt><dd>7 במרץ 1967, ירושלים</dd></div>
        <div><dt>תחומי פעילות</dt><dd>תוכנה, מערכות מידע, יזמות, מוזיקה, AI</dd></div>
        <div><dt>חברות מרכזיות</dt><dd>שיגרה, CouchYou, DocxSite, Ioshka Media, XUDA</dd></div>
        <div><dt>מומחיות</dt><dd>CRM, Workflow, אוטומציית תהליכים, Enterprise AI</dd></div>
        <div><dt>הכרה מקצועית</dt><dd>Seattle Pacific University, 2011</dd></div>
      </dl>
    </aside>
  </main>
</body>
</html>
"""


CSS = """
:root {
  --ink: #202225;
  --muted: #5d6672;
  --line: #d8dee7;
  --paper: #fbfbf8;
  --panel: #ffffff;
  --blue: #245f8f;
  --red: #9b3c32;
  --green: #406d54;
  --gold: #a2772c;
  --shadow: 0 18px 45px rgba(32, 34, 37, .08);
}

* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body {
  margin: 0;
  background: var(--paper);
  color: var(--ink);
  font-family: Arial, "Noto Sans Hebrew", "Segoe UI", sans-serif;
  line-height: 1.72;
  overflow-x: hidden;
  direction: ltr;
}

.progress {
  position: fixed;
  inset: 0 0 auto;
  height: 4px;
  z-index: 20;
  background: transparent;
}
.progress span {
  display: block;
  width: 0;
  height: 100%;
  background: linear-gradient(90deg, var(--blue), var(--green), var(--gold));
}

.site-header {
  direction: rtl;
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 24px;
  padding: 12px 32px;
  border-bottom: 1px solid var(--line);
  background: rgba(251, 251, 248, .95);
  backdrop-filter: blur(12px);
}
.brand {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  color: var(--ink);
  text-decoration: none;
  font-weight: 700;
}
.brand-mark {
  direction: ltr;
  display: grid;
  place-items: center;
  width: 38px;
  height: 38px;
  border: 1px solid var(--ink);
  background: var(--ink);
  color: #fff;
  font-size: 13px;
}
.site-header nav {
  display: flex;
  gap: 18px;
  flex-wrap: wrap;
}
.site-header nav a {
  color: var(--muted);
  text-decoration: none;
  font-size: 14px;
}
.site-header nav a:hover { color: var(--blue); }

.page-shell {
  direction: rtl;
  display: grid;
  grid-template-columns: minmax(210px, 280px) minmax(0, 860px) minmax(260px, 330px);
  gap: 28px;
  align-items: start;
  max-width: 1540px;
  margin: 0 auto;
  padding: 28px 28px 64px;
}

.toc-panel,
.infobox {
  position: sticky;
  top: 86px;
  border: 1px solid var(--line);
  background: var(--panel);
  box-shadow: var(--shadow);
}

.toc-panel {
  max-height: calc(100vh - 108px);
  overflow: auto;
  padding: 16px;
}
.toc-tools label {
  display: block;
  margin-bottom: 8px;
  color: var(--muted);
  font-size: 13px;
  font-weight: 700;
}
.toc-tools input {
  width: 100%;
  border: 1px solid var(--line);
  padding: 10px 11px;
  background: #f7f8fa;
  color: var(--ink);
  font: inherit;
}
.toc-list {
  display: grid;
  gap: 2px;
  margin-top: 14px;
}
.toc-link {
  border-right: 3px solid transparent;
  padding: 7px 9px;
  color: var(--ink);
  text-decoration: none;
  font-size: 14px;
}
.toc-link.level-3 {
  padding-right: 22px;
  color: var(--muted);
  font-size: 13px;
}
.toc-link:hover,
.toc-link.active {
  border-color: var(--blue);
  background: #eef4f8;
  color: var(--blue);
}

.article {
  min-width: 0;
  border: 1px solid var(--line);
  background: var(--panel);
  padding: 38px 48px 52px;
  box-shadow: var(--shadow);
}
.source-note {
  border-right: 4px solid var(--gold);
  margin-bottom: 24px;
  padding: 10px 14px;
  background: #faf6ec;
  color: #65502a;
  font-size: 14px;
}
.article h1 {
  margin: 0 0 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--line);
  font-size: 42px;
  line-height: 1.15;
}
.article h2 {
  margin: 42px 0 14px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--line);
  color: var(--blue);
  font-size: 26px;
  line-height: 1.3;
}
.article h3 {
  margin: 30px 0 10px;
  color: var(--red);
  font-size: 20px;
  line-height: 1.35;
}
.article p,
.article li {
  font-size: 17px;
}
.article a {
  color: var(--blue);
  text-decoration: underline;
  text-underline-offset: 2px;
  text-decoration-thickness: 1px;
}
.article a:hover {
  color: var(--red);
}
.article p {
  margin: 0 0 15px;
}
.article ul {
  margin: 0 0 18px;
  padding: 0 24px 0 0;
}
.article strong { color: #14171a; }

.infobox {
  overflow: hidden;
}
.infobox img {
  display: block;
  width: 100%;
  max-width: 100%;
  aspect-ratio: 4 / 5;
  object-fit: cover;
  object-position: center top;
  border-bottom: 1px solid var(--line);
}
.infobox h2 {
  margin: 0;
  padding: 16px 18px 6px;
  font-size: 22px;
}
.infobox dl {
  margin: 0;
  padding: 8px 18px 18px;
}
.infobox div {
  display: grid;
  grid-template-columns: 82px minmax(0, 1fr);
  gap: 12px;
  padding: 10px 0;
  border-top: 1px solid #eef1f4;
}
.infobox dt {
  color: var(--muted);
  font-weight: 700;
  font-size: 13px;
}
.infobox dd {
  margin: 0;
  font-size: 14px;
  min-width: 0;
  overflow-wrap: anywhere;
}

mark {
  background: #ffe28a;
  color: var(--ink);
  padding: 0 2px;
}

@media (max-width: 1180px) {
  .page-shell {
    grid-template-columns: minmax(0, 1fr) minmax(250px, 310px);
  }
  .toc-panel {
    position: relative;
    top: 0;
    grid-column: 1 / -1;
    max-height: none;
  }
  .toc-list {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 820px) {
  .site-header {
    display: grid;
    grid-template-columns: 1fr;
    align-items: flex-start;
    padding: 10px 72px 10px 16px;
    overflow: hidden;
  }
  .brand {
    justify-self: start;
  }
  .brand-mark {
    display: none;
  }
  .site-header nav {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    width: 100%;
    gap: 8px;
  }
  .site-header nav a {
    min-width: 0;
    text-align: center;
  }
  .page-shell {
    display: flex;
    flex-direction: column;
    width: 100%;
    max-width: 100%;
    padding: 16px 72px 42px 14px;
    overflow: hidden;
    direction: ltr;
  }
  .article,
  .toc-panel,
  .infobox {
    width: auto;
    min-width: 0;
    max-width: 100%;
    align-self: stretch;
    position: static;
    direction: rtl;
  }
  .article {
    order: 3;
    padding: 26px 20px 34px;
  }
  .infobox {
    order: 1;
  }
  .infobox div {
    grid-template-columns: 1fr;
    gap: 3px;
  }
  .toc-panel {
    order: 2;
  }
  .toc-list {
    grid-template-columns: 1fr;
  }
  .article h1 {
    font-size: 34px;
  }
  .article h2 {
    font-size: 23px;
  }
}
"""


JS = """
const progress = document.querySelector('.progress span');
const links = [...document.querySelectorAll('.toc-link')];
const headings = links
  .map(link => document.querySelector(link.getAttribute('href')))
  .filter(Boolean);

function updateProgress() {
  const height = document.documentElement.scrollHeight - window.innerHeight;
  const percent = height > 0 ? (window.scrollY / height) * 100 : 0;
  progress.style.width = `${percent}%`;

  let current = headings[0];
  for (const heading of headings) {
    if (heading.getBoundingClientRect().top < 140) current = heading;
  }
  links.forEach(link => {
    link.classList.toggle('active', current && link.getAttribute('href') === `#${current.id}`);
  });
}

function clearMarks() {
  document.querySelectorAll('mark').forEach(mark => {
    mark.replaceWith(document.createTextNode(mark.textContent));
  });
}

document.getElementById('toc-search').addEventListener('input', event => {
  clearMarks();
  const query = event.target.value.trim();
  const article = document.querySelector('.article');
  links.forEach(link => {
    link.hidden = query && !link.textContent.includes(query);
  });
  if (!query) return;

  const walker = document.createTreeWalker(article, NodeFilter.SHOW_TEXT);
  const matches = [];
  while (walker.nextNode()) {
    const node = walker.currentNode;
    const index = node.nodeValue.indexOf(query);
    if (index >= 0 && matches.length < 20) matches.push([node, index]);
  }
  for (const [node, index] of matches) {
    const range = document.createRange();
    range.setStart(node, index);
    range.setEnd(node, index + query.length);
    const mark = document.createElement('mark');
    range.surroundContents(mark);
  }
  document.querySelector('mark')?.scrollIntoView({ block: 'center', behavior: 'smooth' });
});

window.addEventListener('scroll', updateProgress, { passive: true });
updateProgress();
"""


if __name__ == "__main__":
    build()
