#!/usr/bin/env python3

import os
import html
from pathlib import Path
from datetime import datetime

DIRECTORY = "."
OUTPUT = "index.html"

# Extensions to show
SHOW_EXTENSIONS = {
    ".html",
    ".html.br",
    ".txt",
    ".pdf",
    ".md",
    ".jpg",
    ".jpeg",
    ".png",
    ".gif",
    ".webp",
}

files = []

for entry in sorted(os.listdir(DIRECTORY)):

    if entry == OUTPUT:
        continue

    path = Path(entry)

    if not path.is_file():
        continue

    # Show all .br files
    if entry.endswith(".br"):
        files.append(entry)
        continue

    # Show selected normal files
    if path.suffix.lower() in SHOW_EXTENSIONS:
        files.append(entry)

cards = []

for filename in files:

    display_name = filename

    # Clean display for .html.br
    if filename.endswith(".html.br"):
        display_name = filename[:-3]

    size = os.path.getsize(filename)

    if size > 1024 * 1024:
        size_text = f"{size / (1024*1024):.1f} MB"
    elif size > 1024:
        size_text = f"{size / 1024:.1f} KB"
    else:
        size_text = f"{size} B"

    modified = datetime.fromtimestamp(
        os.path.getmtime(filename)
    ).strftime("%Y-%m-%d %H:%M")

    href = display_name if filename.endswith(".br") else filename

    card = f"""
    <a class="card" href="{html.escape(href)}">
        <div class="title">{html.escape(display_name)}</div>
        <div class="meta">
            <div>{html.escape(size_text)}</div>
            <div>{html.escape(modified)}</div>
        </div>
    </a>
    """

    cards.append(card)

html_page = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Archive Index</title>

<style>

body {{
    margin: 0;
    padding: 30px;
    background: #f4f4f4;
    font-family: system-ui, sans-serif;
}}

h1 {{
    margin-top: 0;
    margin-bottom: 24px;
}}

.grid {{
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 16px;
}}

.card {{
    display: block;
    background: white;
    padding: 18px;
    border-radius: 14px;
    text-decoration: none;
    color: #111;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    transition: transform 0.15s ease,
                box-shadow 0.15s ease;
}}

.card:hover {{
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0,0,0,0.12);
}}

.title {{
    font-weight: 600;
    margin-bottom: 10px;
    word-break: break-word;
}}

.meta {{
    color: #666;
    font-size: 13px;
    display: flex;
    justify-content: space-between;
    gap: 10px;
}}

</style>
</head>

<body>

<h1>Archive Index</h1>

<div class="grid">
{''.join(cards)}
</div>

</body>
</html>
"""

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

print(f"Generated: {OUTPUT}")
print(f"Files indexed: {len(files)}")
