import requests

API_KEY = "d85013dd87557388778607b0440721c0"
BASE_URL = "https://api.themoviedb.org/3"
IMAGE_BASE = "https://image.tmdb.org/t/p/w1280"

def download_tmdb_backdrop(imdb_id, save_as="tmdb_backdrop.jpg"):
    try:
        # پیدا کردن TMDB ID
        find_url = f"{BASE_URL}/find/{imdb_id}?api_key={API_KEY}&external_source=imdb_id"
        find_data = requests.get(find_url).json()

        if find_data["movie_results"]:
            tmdb_id = find_data["movie_results"][0]["id"]
            media_type = "movie"
        elif find_data["tv_results"]:
            tmdb_id = find_data["tv_results"][0]["id"]
            media_type = "tv"
        else:
            print("🎬 فیلم یا سریال پیدا نشد.")
            return

        # گرفتن لیست تصاویر
        img_url = f"{BASE_URL}/{media_type}/{tmdb_id}/images?api_key={API_KEY}"
        img_data = requests.get(img_url).json()

        if not img_data.get("backdrops"):
            print("❌ تصویر بک‌دراپ موجود نیست.")
            return

        image_path = img_data["backdrops"][0]["file_path"]
        full_url = IMAGE_BASE + image_path

        # دانلود فایل تصویر
        img_response = requests.get(full_url, stream=True)
        with open(save_as, "wb") as f:
            for chunk in img_response.iter_content(1024):
                f.write(chunk)

        print(f"✅ تصویر ذخیره شد: {save_as}")

    except Exception as e:
        print("⛔ خطا:", e)

# تست دانلود
download_tmdb_backdrop("tt0111161")
