from sqlalchemy.orm import Mapped, mapped_column, relationship

from advanced_alchemy.base import BigIntAuditBase
from advanced_alchemy.mixins import SlugKey

from typing import TYPE_CHECKING, Optional

if TYPE_CHECKING:
    from .book import Book


class Library(BigIntAuditBase, SlugKey):
    __tablename__ = "libraries"

    name: Mapped[str] = mapped_column(unique=True)
    root_path: Mapped[str]
    # Which structure to save the files in the filesystem (i.e {author_name}/{title}.{ext})
    path_template: Mapped[str]
    description: Mapped[Optional[str]]
    icon: Mapped[str] = mapped_column(default="library")
    read_only: Mapped[bool] = mapped_column(nullable=False, default=False)

    books: Mapped[list["Book"]] = relationship(back_populates="library")

    @property
    def total(self) -> int | None:
        """Return count of books if books is loaded, None otherwise."""
        try:
            return len(self.books) if self.books else 0
        except Exception:
            return None

    def __repr__(self) -> str:
        return f"Library({self.name=!r})"
