import os
import json
import glob

# Your Nginx domain
CDN_BASE = "https://colorwall-repo.periodicbrake.fr"

header = "# Wallpaper Archive\n\nAutomated archive of wallpapers.\n\n## Gallery\n\n| Preview | Title | Tags |\n| --- | --- | --- |\n"
rows = []

# Scans the mapped /app/assets folder
for json_file in sorted(glob.glob("/hdd/colorwall-mirror/*.json")):
    try:
        with open(json_file, "r", encoding="utf-8") as f:
            item = json.load(f)
            
            item_id = item.get("id", "unknown")
            title = item.get("title", "Wallpaper")
            tags = ", ".join(item.get("tags", []))
            
            # Assuming files are named <id>.png or <id>.jpg in the same folder
            ext = "png" if ".png" in item.get("download_url", "").lower() else "jpg"
            filename = f"{item_id}.{ext}"
            cdn_url = f"{CDN_BASE}/{filename}"
            
            row = f'| <img src="{cdn_url}" width="200"> | **{title}**<br>[Download]({cdn_url}) | {tags} |\n'
            rows.append((item_id, row))
    except Exception as e:
        print(f"Skipping {json_file}: {e}")

with open("README.md", "w", encoding="utf-8") as f:
    f.write(header)
    for _, row in rows:
        f.write(row)

print("README.md has been successfully generated.")
