#!/usr/bin/env python3

import os
import html
from pathlib import Path


def create_index(directory):
    directory = Path(directory)

    if (directory / "index.html").exists() or (directory / "index.htm").exists():
        print(f"Skipping: {directory}")
        return

    print(f"Creating: {directory / 'index.html'}")

    entries = sorted(
        directory.iterdir(),
        key=lambda p: (not p.is_dir(), p.name.lower())
    )

    items = []

    for entry in entries:
        if entry.name.lower() in ("index.html", "index.htm"):
            continue

        name = entry.name

        if entry.is_dir():
            name += "/"

        items.append(
            f"""
            <div class="box">
                <a href="{html.escape(entry.name)}">
                    {html.escape(name)}
                </a>
            </div>
            """
        )

    page = f"""<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

<title>Index of {html.escape(str(directory))}</title>

<style>

body {{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 24px;
    line-height: 1.9;
    margin: 40px;
    background: #fafafa;
}}

h1 {{
    font-size: 36px;
    margin-bottom: 35px;
}}

.container {{
    display: flex;
    flex-direction: column;
    gap: 18px;
    max-width: 900px;
}}

.box {{
    background: white;
    border: 2px solid #ddd;
    border-radius: 14px;
    padding: 22px;
    box-shadow: 0 3px 8px rgba(0,0,0,0.12);
}}

.box:hover {{
    box-shadow: 0 6px 14px rgba(0,0,0,0.18);
}}

a {{
    text-decoration: none;
    color: #0057b8;
    display: block;
}}

a:hover {{
    text-decoration: underline;
}}

</style>

</head>

<body>

<h1>Index of {html.escape(str(directory))}</h1>

<div class="container">

{''.join(items)}

</div>

</body>
</html>
"""

    (directory / "index.html").write_text(page, encoding="utf-8")


def process_tree(start):
    for root, dirs, files in os.walk(start):
        create_index(root)


if __name__ == "__main__":
    process_tree(Path.cwd())
    print("Done.")