from pathlib import Path

import requests


class MemeNotFoundError(Exception):
    """Raised when a meme is not found at buz.info.pl"""

    pass


class Meme:
    def __init__(self, meme_index: int):
        """Creates a new meme by buz.info.pl index"""
        self.url = f"https://szkola.buz.info.pl/graf/linux{meme_index}.jpg"

    def fetch_image(self) -> bytes:
        """Fetches this meme and returns the JPG bytes"""
        res = requests.get(self.url)
        if res.status_code != 200:
            raise MemeNotFoundError(f"Could not fetch meme from {self.url}")
        return res.content

    def save_meme(self, save_path: Path):
        """Fetches this meme and saves it as a jpg to a file"""
        with open(save_path, "wb") as f:
            f.write(self.fetch_image())
