"""Local staging for blog images (uploaded to Shopify at publish time)."""

from pathlib import Path
from urllib.parse import urljoin

from django.conf import settings

SHOPIFY_CDN_HOST = "cdn.shopify.com"


def is_shopify_cdn_url(url: str) -> bool:
    return SHOPIFY_CDN_HOST in (url or "")


class BlogImageStorage:
    SUBDIR = "blog_images"

    @classmethod
    def media_root(cls) -> Path:
        return Path(getattr(settings, "MEDIA_ROOT", settings.BASE_DIR / "media"))

    @classmethod
    def staging_dir(cls) -> Path:
        dest = cls.media_root() / cls.SUBDIR
        dest.mkdir(parents=True, exist_ok=True)
        return dest

    @classmethod
    def save(cls, article_id: int, position: str, image_bytes: bytes) -> str:
        """Save PNG bytes; return relative path from MEDIA_ROOT."""
        safe_position = position.replace("/", "-")
        filename = f"article_{article_id}_{safe_position}.png"
        path = cls.staging_dir() / filename
        path.write_bytes(image_bytes)
        return f"{cls.SUBDIR}/{filename}"

    @classmethod
    def resolve_path(cls, relative_path: str) -> Path:
        return cls.media_root() / relative_path

    @classmethod
    def preview_url(cls, relative_path: str) -> str:
        media_url = getattr(settings, "MEDIA_URL", "/media/")
        if not media_url.endswith("/"):
            media_url += "/"
        relative = f"{media_url}{relative_path}"
        host = (getattr(settings, "HOST_URL", None) or "").strip().rstrip("/")
        if host:
            return urljoin(f"{host}/", relative.lstrip("/"))
        return relative

    @classmethod
    def delete(cls, relative_path: str) -> None:
        if not relative_path:
            return
        path = cls.resolve_path(relative_path)
        if path.is_file():
            path.unlink()

    @classmethod
    def read_bytes(cls, relative_path: str) -> bytes:
        path = cls.resolve_path(relative_path)
        if not path.is_file():
            raise FileNotFoundError(f"Staged image missing: {relative_path}")
        return path.read_bytes()
