import os
from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError

# ===== パス設定（/mnt に統一）=====
BASE_DIR = "/mnt/ssd1_128G/html/home/images"
OUTPUT_DIR = os.path.join(BASE_DIR, "with_filenames")

# ディレクトリ作成
os.makedirs(OUTPUT_DIR, exist_ok=True)

# フォント設定
FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
font = ImageFont.truetype(FONT_PATH, 20)

# ===== 画像処理 =====
for img_name in os.listdir(BASE_DIR):
    if not img_name.lower().endswith((".jpg", ".jpeg", ".png")):
        continue

    img_path = os.path.join(BASE_DIR, img_name)
    output_img_path = os.path.join(OUTPUT_DIR, img_name)

    try:
        # 画像チェック
        with Image.open(img_path) as img:
            img.verify()

        # 再オープンして描画
        with Image.open(img_path).convert("RGB") as img:
            draw = ImageDraw.Draw(img)
            draw.text((10, 10), img_name, fill=(255, 255, 255), font=font)
            img.save(output_img_path)

    except (UnidentifiedImageError, OSError) as e:
        print(f"SKIP: 読み込めない画像 → {img_name} ({e})")

print("画像にファイル名を追加しました！")

# ===== HTML生成 =====
html_content = """<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>写真ギャラリー</title>
</head>
<body>
<h1>写真ギャラリー</h1>
"""

for img_name in sorted(os.listdir(OUTPUT_DIR)):
    if img_name.lower().endswith((".jpg", ".jpeg", ".png")):
        html_content += f'<img src="with_filenames/{img_name}" alt="{img_name}"><br>\n'

html_content += """
</body>
</html>
"""

# HTML保存
html_path = os.path.join(BASE_DIR, "index.html")
with open(html_path, "w", encoding="utf-8") as f:
    f.write(html_content)

print("HTMLファイルを生成しました！")
