"""File-backed storage helpers for the homepage content."""

from __future__ import annotations

from pathlib import Path

HOME_PAGE_DIR = Path(__file__).resolve().parents[3] / "data" / "homepage"
HOME_PAGE_MARKDOWN_PATH = HOME_PAGE_DIR / "homepage.md"
SUPPORTED_IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff"}


def ensure_homepage_storage() -> None:
    """Create the homepage storage directory when needed."""
    HOME_PAGE_DIR.mkdir(parents=True, exist_ok=True)


def read_homepage_markdown() -> str:
    """Read the saved homepage markdown text."""
    ensure_homepage_storage()
    if not HOME_PAGE_MARKDOWN_PATH.exists():
        return ""
    return HOME_PAGE_MARKDOWN_PATH.read_text(encoding="utf-8")


def save_homepage_markdown(markdown_text: str) -> None:
    """Persist the homepage markdown text."""
    ensure_homepage_storage()
    HOME_PAGE_MARKDOWN_PATH.write_text(markdown_text, encoding="utf-8")


def store_homepage_image(*, filename: str, file_bytes: bytes) -> Path:
    """Persist an uploaded homepage image in the shared homepage folder."""
    ensure_homepage_storage()

    safe_name = Path(filename).name
    if not safe_name:
        msg = "Homepage image filename is required"
        raise ValueError(msg)

    stored_path = HOME_PAGE_DIR / safe_name
    stored_path.write_bytes(file_bytes)
    return stored_path


def list_homepage_images() -> list[Path]:
    """List stored homepage images in the order they were last updated."""
    ensure_homepage_storage()

    image_paths = [
        path
        for path in HOME_PAGE_DIR.iterdir()
        if path.is_file() and path.suffix.lower() in SUPPORTED_IMAGE_SUFFIXES
    ]
    return sorted(image_paths, key=lambda path: (path.stat().st_mtime, path.name))


def latest_homepage_image() -> Path | None:
    """Return the most recently updated homepage image, if one exists."""
    image_paths = list_homepage_images()
    if not image_paths:
        return None
    return image_paths[-1]