import nanoid

from konabot.common.path import ASSETS_PATH
from konabot.plugins.kona_ph.core.path import KONAPH_IMAGE_BASE


class PuzzleImageManager:
    def read_puzzle_image(self, img_name: str) -> bytes:
        fp = KONAPH_IMAGE_BASE / img_name
        if fp.exists():
            return fp.read_bytes()
        return (ASSETS_PATH / "img" / "other" / "boom.jpg").read_bytes()

    def upload_puzzle_image(self, data: bytes, suffix: str = ".png") -> str:
        id = nanoid.generate(
            "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",
            21,
        )
        img_name = f"{id}{suffix}"
        (KONAPH_IMAGE_BASE / img_name).write_bytes(data)
        return img_name

    def remove_puzzle_image(self, img_name: str):
        if img_name:
            (KONAPH_IMAGE_BASE / img_name).unlink(True)


def get_image_manager() -> PuzzleImageManager:
    return PuzzleImageManager()
