from PIL import ImageDraw, ImageFont
import importlib.resources as res
import textwrap

def load_font(name: str, size: int) -> ImageFont.FreeTypeFont:
    """Load a font from the assets."""
    font_path = str(res.files('musicard.assets') / name)
    return ImageFont.truetype(font_path, size)

def draw_text_centered(draw: ImageDraw.ImageDraw, text: str, font: ImageFont.FreeTypeFont, color: str, position: tuple[int, int]):
    """Draw text centered at the given position."""
    bbox = draw.textbbox((0, 0), text, font=font)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]
    x = position[0] - text_width // 2
    y = position[1] - text_height // 2
    draw.text((x, y), text, font=font, fill=color)

def draw_text_with_shadow(draw: ImageDraw.ImageDraw, text: str, font: ImageFont.FreeTypeFont, color: str, shadow_color: str, position: tuple[int, int], shadow_offset: tuple[int, int] = (2, 2)):
    """Draw text with a shadow."""
    draw.text((position[0] + shadow_offset[0], position[1] + shadow_offset[1]), text, font=font, fill=shadow_color)
    draw.text(position, text, font=font, fill=color)

def wrap_text(text: str, font: ImageFont.FreeTypeFont, max_width: int) -> str:
    """Wrap text to fit within max_width."""
    lines = []
    words = text.split()
    current_line = ""
    for word in words:
        test_line = current_line + " " + word if current_line else word
        bbox = font.getbbox(test_line)
        if bbox[2] - bbox[0] <= max_width:
            current_line = test_line
        else:
            if current_line:
                lines.append(current_line)
            current_line = word
    if current_line:
        lines.append(current_line)
    return "\n".join(lines)