#!/usr/bin/env python3
"""Genera un _index.html per ogni cartella del sito, con l'elenco dei file
ordinato per data di ultima modifica (più recenti in cima).

Va rilanciato prima di ogni deploy: i file generati SONO la homepage e le
pagine-indice di ogni cartella. Non modificarli a mano, vengono sovrascritti
a ogni esecuzione.

Uso:
    python3 scripts/generate-index.py
"""
import os
from datetime import datetime

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Cartelle mai indicizzate né deployate (lavoro interno, chiavi, backup locali)
EXCLUDE_DIRS = {
    ".claude", ".git", "ssh-deploy-key", "_backup-locali",
    "__pycache__", "node_modules",
}
# File specifici mai indicizzati né deployati
EXCLUDE_FILES = {"REMOTE.md"}
EXCLUDE_SUFFIXES = (".zip", ".pyc")
INDEX_NAME = "_index.html"


def human_size(n):
    size = float(n)
    for unit in ("B", "KB", "MB", "GB"):
        if size < 1024:
            return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
        size /= 1024
    return f"{size:.1f} TB"


def should_skip_file(name):
    return (
        name == INDEX_NAME
        or name in EXCLUDE_FILES
        or name.startswith(".")
        or name.endswith(EXCLUDE_SUFFIXES)
    )


def build_index(dirpath):
    entries = []
    with os.scandir(dirpath) as it:
        for e in it:
            if e.is_dir(follow_symlinks=False):
                if e.name in EXCLUDE_DIRS or e.name.startswith("."):
                    continue
                st = e.stat()
                entries.append((e.name + "/", st.st_mtime, None, True))
            else:
                if should_skip_file(e.name):
                    continue
                st = e.stat()
                entries.append((e.name, st.st_mtime, st.st_size, False))

    # Ordine richiesto: per data di ultima modifica, più recenti in cima.
    entries.sort(key=lambda x: x[1], reverse=True)

    rel = os.path.relpath(dirpath, ROOT)
    title = "San Marco Vision — indice" if rel == "." else f"San Marco Vision — {rel}/"

    rows = []
    if rel != ".":
        rows.append('<tr><td><a href="../">.. (cartella superiore)</a></td><td></td><td></td></tr>')
    for name, mtime, size, is_dir in entries:
        dt = datetime.fromtimestamp(mtime).strftime("%d/%m/%Y %H:%M")
        size_str = "" if is_dir else human_size(size)
        rows.append(
            f'<tr><td><a href="{name}">{name}</a></td>'
            f'<td>{dt}</td><td>{size_str}</td></tr>'
        )

    html = f"""<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
<meta name="robots" content="noindex">
<style>
  :root {{ --paper:#fff; --ink:#0a2540; --accent:#0090ff; --muted:#5b6b80; --hairline:#c9d6e5; }}
  * {{ box-sizing: border-box; }}
  body {{ margin:0; padding:40px clamp(20px,5vw,64px); background:var(--paper); color:var(--ink);
          font-family:"Inter",system-ui,sans-serif; }}
  h1 {{ font-family:"Space Grotesk",system-ui,sans-serif; font-size:1.6rem; letter-spacing:-.02em; margin:0 0 6px; }}
  .eyebrow {{ font-family:ui-monospace,"IBM Plex Mono",monospace; font-size:11px; letter-spacing:.16em;
              text-transform:uppercase; color:var(--muted); margin:0 0 28px; }}
  table {{ width:100%; border-collapse:collapse; font-size:.95rem; }}
  th {{ text-align:left; font-family:ui-monospace,monospace; font-size:11px; letter-spacing:.1em;
        text-transform:uppercase; color:var(--muted); border-bottom:1px solid var(--hairline); padding:8px 10px; }}
  td {{ padding:9px 10px; border-bottom:1px solid var(--hairline); }}
  td:nth-child(2), td:nth-child(3), th:nth-child(2), th:nth-child(3) {{
    color:var(--muted); font-size:.85rem; white-space:nowrap; }}
  a {{ color:var(--ink); text-decoration:none; }}
  a:hover {{ color:var(--accent); text-decoration:underline; }}
  tr:hover td {{ background:#eef4ff; }}
</style>
</head>
<body>
  <p class="eyebrow">San Marco Vision · indice cartella</p>
  <h1>{title}</h1>
  <table>
    <thead><tr><th>Nome</th><th>Ultima modifica</th><th>Dimensione</th></tr></thead>
    <tbody>
      {''.join(rows)}
    </tbody>
  </table>
</body>
</html>
"""
    with open(os.path.join(dirpath, INDEX_NAME), "w", encoding="utf-8") as f:
        f.write(html)


def walk_and_build():
    count = 0
    for dirpath, dirnames, _filenames in os.walk(ROOT):
        dirnames[:] = sorted(d for d in dirnames if d not in EXCLUDE_DIRS and not d.startswith("."))
        build_index(dirpath)
        count += 1
    return count


if __name__ == "__main__":
    n = walk_and_build()
    print(f"Generati {n} file {INDEX_NAME} (uno per cartella), ordinati per ultima modifica.")
