import os
import requests
from time import sleep

# --- Configuration ---
TCGDEX_API = "https://api.tcgdex.net/v2/de/cards"
OUTPUT_FOLDER = "cards"
REQUEST_DELAY = 0.1  # seconds between requests to avoid rate limiting

# Create output folder if not exists
os.makedirs(OUTPUT_FOLDER, exist_ok=True)

# Fetch card list from TCGdex
print("Fetching card list...")
resp = requests.get(TCGDEX_API)
if resp.status_code != 200:
    raise Exception(f"Failed to fetch card list: {resp.status_code}")
cards = resp.json()
print(f"Total cards fetched: {len(cards)}")

# Download each card image
for card in cards:
    card_id = card.get("id", None)
    image_base = card.get("image", None)

    if not card_id:
        print("Skipping card with missing ID:", card)
        continue

    if not image_base:
        print(f"No image URL for {card_id}, skipping...")
        continue

    image_url = image_base + "/high.png"
    output_path = os.path.join(OUTPUT_FOLDER, f"{card_id}.png")

    # Skip if already downloaded
    if os.path.exists(output_path):
        print(f"Already exists: {card_id}")
        continue

    try:
        r = requests.get(image_url, stream=True)
        if r.status_code == 200:
            with open(output_path, "wb") as f:
                for chunk in r.iter_content(1024):
                    f.write(chunk)
            print(f"Downloaded: {card_id}")
        else:
            print(f"Failed to download {card_id}: HTTP {r.status_code}")
    except Exception as e:
        print(f"Error downloading {card_id}: {e}")

    sleep(REQUEST_DELAY)  # small delay to be polite

print("All done!")
