import os

# 限定根目錄為此 Python 腳本所在資料夾
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))

def generate_index_html(directory):
    items = sorted(os.listdir(directory))
    relative_path = os.path.relpath(directory, ROOT_DIR)
    title_text = "mokuri's space" if relative_path == "." else relative_path
    html_lines = [
    "<!DOCTYPE html>",
    "<html lang=\"zh-Hant\">",
    "<head>",
    "  <meta charset=\"UTF-8\">",
    f"  <title>{title_text}</title>",
    ]
    # ✅ 加上原本的文字與 Email
    if relative_path == ".":
        html_lines += [
            "  <h1>我還沒想好要在這放啥</h1>",
            "  <h3>給點建議: <a href=\"mailto:mokuri410@gmail.com\">mokuri410@gmail.com</a></h3>",
            "  <hr>",
            "  <h2>📁 自動列出的項目：</h2>",
        ]
    else:
        html_lines += [
            f"  <h1>📁 {relative_path}</h1>",
            "  <a href=\"../\">🔙 回上一層</a>",
            "  <hr>",
            "  <h2>📁 項目：</h2>",
        ]

    html_lines.append("  <ul>")

    for item in items:
        full_path = os.path.join(directory, item)
        if item in {"index.html", "__pycache__"} or item.startswith("."):
            continue
        display = f"📁 {item}" if os.path.isdir(full_path) else f"📄 {item}"
        href = item + "/" if os.path.isdir(full_path) else item
        html_lines.append(f'    <li><a href="{href}" target="_blank">{display}</a></li>')

    html_lines += [
        "  </ul>",
        "</body>",
        "</html>"
    ]

    # 寫入 index.html
    with open(os.path.join(directory, "index.html"), "w", encoding="utf-8") as f:
        f.write("\n".join(html_lines))

    print(f"✅ 已產生 {os.path.relpath(directory, ROOT_DIR)}/index.html")

    # 遞迴處理子目錄
    for item in items:
        sub_path = os.path.join(directory, item)
        if os.path.isdir(sub_path) and os.path.commonpath([ROOT_DIR, sub_path]) == ROOT_DIR:
            generate_index_html(sub_path)

# 執行
generate_index_html(ROOT_DIR)
