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

class WordImg:
    """
    A class to generate images with custom text on a background.

    Example usage:
    
    ```python
    from wordimg import WordImg

    wordimg = WordImg()
    image_path = wordimg.make_image("img.jpg", "Hello", "@username")
    print(f"Image saved at: {image_path}")
    ```
    """

    def __init__(self):
        self.font_path = pkg_resources.resource_filename('wordimg', 'fonts/font.ttf')
        os.makedirs('saved_images', exist_ok=True)

    def make_image(self, background: str, text: str, username: str) -> str:
        text = text.strip().capitalize()
        formatted_text = text.replace(" ", "_").lower()
        save_path = f'saved_images/{formatted_text}.jpg'

        if os.path.exists(save_path):
            return save_path

        try:
            img = Image.open(background)
            img = img.resize((2560, 1440))

            draw = ImageDraw.Draw(img)
            font_main = ImageFont.truetype(self.font_path, 360)
            font_username = ImageFont.truetype(self.font_path, 60)

            wi, he = img.size
            w, h = draw.textbbox((0, 0), text, font=font_main)[2:]
            new_w, new_h = (wi - w) / 2, (he - h) / 2

            draw.text((new_w, new_h), text, fill="black", font=font_main)
            draw.text((50, 50), username, fill="black", font=font_username)

            img.save(save_path)
            return save_path

        except Exception as e:
            print(f"Error: {e}")
            return None