# -*- coding: utf-8 -*-
import os
from urllib.parse import quote
from datetime import datetime

# --- Konfiguration ---
BASE_DIR = r"Y:\KUNDENDATEN\CIMPCS\Intern\Arbeitsunterlagen\Schulungsvideos"
BASE_URL = "https://video.prodat-sql.de"

# Externes Ausgabe-Verzeichnis (existiert bereits)
OUTPUT_DIR = r"Y:\ProdatSQL\ProdatSRV_Develop\Help.Git\PRODAT\HTML"
OUTPUT_FILE = os.path.join(OUTPUT_DIR, "Video.html")  # Groß-/Kleinschreibung wie gewünscht

VIDEO_EXTENSIONS = [".mp4", ".mov", ".avi", ".mkv", ".webm"]
EXCLUDE_DIRS = {"CIMPCS"}           # Ordner, die vollständig übersprungen werden
EXCLUDE_DIRS_CI = {d.lower() for d in EXCLUDE_DIRS}


def is_video_file(filename: str) -> bool:
    return any(filename.lower().endswith(ext) for ext in VIDEO_EXTENSIONS)


def generate_html():
    sections = []
    nav_links = []
    total_videos = 0
    date_str = datetime.now().strftime("%d.%m.%Y")

    for root, dirs, files in os.walk(BASE_DIR):
        # Ordner beim Parsen ausschließen (case-insensitive)
        dirs[:] = [d for d in dirs if d.lower() not in EXCLUDE_DIRS_CI]

        rel_path = os.path.relpath(root, BASE_DIR)
        if rel_path == ".":
            section_title = "Wurzelebene"
            section_id = "wurzel"
            display_path = "/"
        else:
            section_title = rel_path.replace("\\", " / ")
            section_id = rel_path.lower().replace("\\", "-").replace(" ", "-")
            display_path = "/" + rel_path.replace("\\", "/")

        video_items = []
        for file in sorted(files):
            if is_video_file(file):
                file_path = os.path.join(rel_path, file).replace("\\", "/")
                url = f"{BASE_URL}/{quote(file_path)}"
                video_items.append(
                    f'''
<li data-name="{file.lower()}" class="transition">
  <a href="{url}" class="block rounded-xl border border-gray-200 p-3 hover:shadow-md focus:outline-none focus:ring-2 focus:ring-indigo-500">
    <div class="flex items-center gap-2">
      <span aria-hidden="true">🎬</span>
      <span class="font-medium truncate">{file}</span>
    </div>
    <div class="text-xs text-gray-500 mt-1 truncate">{display_path}</div>
  </a>
</li>'''
                )

        if video_items:
            count = len(video_items)
            total_videos += count

            nav_links.append(
                f'''
<li>
  <a href="#{section_id}" class="flex items-center justify-between rounded-lg border border-gray-200 px-3 py-2 hover:bg-gray-50">
    <span class="truncate">{section_title}</span>
    <span class="text-xs tabular-nums bg-gray-100 rounded px-2 py-0.5">{count}</span>
  </a>
</li>'''
            )

            section_html = f'''
<section id="{section_id}" data-section class="scroll-mt-24">
  <details open class="group">
    <summary class="flex items-center justify-between cursor-pointer list-none select-none rounded-xl bg-white border border-gray-200 px-4 py-3 shadow-sm hover:shadow">
      <div class="flex items-center gap-2">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 opacity-70 group-open:rotate-90 transition-transform" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M9 5l7 7-7 7"/></svg>
        <h2 class="font-semibold">{section_title}</h2>
      </div>
      <span class="js-count text-xs tabular-nums bg-gray-100 rounded px-2 py-0.5">{count} Videos</span>
    </summary>
    <div class="mt-3">
      <ul class="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
        {''.join(video_items)}
      </ul>
      <div class="mt-3 text-right">
        <a href="#top" class="text-sm text-indigo-600 hover:underline">Nach oben ↑</a>
      </div>
    </div>
  </details>
</section>
'''
            sections.append(section_html)

    html_output = f'''<!DOCTYPE html>
<html lang="de" class="h-full">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Schulungsvideos</title>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="h-full bg-gray-50 text-gray-900">
  <a id="top"></a>
  <header class="sticky top-0 z-10 backdrop-blur border-b border-gray-200 bg-white/70">
    <div class="mx-auto max-w-7xl px-4 py-3 flex items-center justify-between gap-4">
      <div>
        <h1 class="text-lg sm:text-xl font-semibold">Schulungsvideos Inhaltsverzeichnis</h1>
        <p class="text-xs text-gray-600">Stand: {date_str}</p>
      </div>
    </div>
  </header>

  <main class="mx-auto max-w-7xl px-4 py-6 grid gap-6 lg:grid-cols-[280px,1fr]">
    <!-- Seitenleiste -->
    <aside class="order-2 lg:order-1">
      <div class="rounded-xl border border-gray-200 p-3 bg-white">
        <div class="flex items-center justify-between">
          <h2 class="font-semibold">Ordner</h2>
          <span class="text-xs tabular-nums bg-gray-100 rounded px-2 py-0.5" id="total-count">{total_videos}</span>
        </div>
        <div class="mt-3">
          <label for="search" class="sr-only">Suche</label>
          <input id="search" type="search" placeholder="Suchen…" class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" />
        </div>
        <nav class="mt-3">
          <ul class="flex flex-col gap-2 max-h-[55vh] overflow-auto pr-1">
            {''.join(nav_links)}
          </ul>
        </nav>
      </div>
    </aside>

    <!-- Inhalt -->
    <section class="order-1 lg:order-2 space-y-4">
      {''.join(sections)}
    </section>
  </main>

  <footer class="mx-auto max-w-7xl px-4 pb-10">
    <div class="rounded-xl border border-gray-200 p-4 text-sm text-gray-600 bg-white">
      Hinweis: Diese Übersicht wird bei Änderungen im Video-Ordner aktualisiert werden. 
    </div>
  </footer>

  <script>
    // Live-Suche und Zähler
    const searchInput = document.getElementById('search');
    const totalCountEl = document.getElementById('total-count');

    function applyFilter() {{
      const q = (searchInput.value || '').toLowerCase().trim();
      let totalVisible = 0;

      document.querySelectorAll('section[data-section]').forEach(sec => {{
        let visibleInSection = 0;
        sec.querySelectorAll('li[data-name]').forEach(li => {{
          const name = li.getAttribute('data-name') || '';
          const show = !q || name.includes(q);
          li.classList.toggle('hidden', !show);
          if (show) visibleInSection += 1;
        }});
        const countEl = sec.querySelector('.js-count');
        if (countEl) countEl.textContent = (visibleInSection + ' Videos');
        sec.classList.toggle('hidden', q && visibleInSection === 0);
        totalVisible += visibleInSection;
      }});

      totalCountEl.textContent = totalVisible;
    }}

    searchInput.addEventListener('input', applyFilter);
  </script>
</body>
</html>
'''

    # Sicherstellen, dass nicht versucht wird, das Verzeichnis anzulegen
    if not os.path.isdir(OUTPUT_DIR):
        raise FileNotFoundError(f"Ausgabeverzeichnis existiert nicht: {OUTPUT_DIR}")

    with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
        f.write(html_output)


if __name__ == "__main__":
    generate_html()
