"""Google Photos data models."""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any


@dataclass
class GooglePhotosMediaItem:
    """A media item from the Google Photos Library API."""

    id: str
    filename: str
    mime_type: str
    created_at: str  # mediaMetadata.creationTime (ISO 8601)
    base_url: str  # temporary download URL (expires ~60 min)
    product_url: str  # permanent link to Google Photos UI
    width: int | None = None
    height: int | None = None
    description: str = ""
    is_video: bool = False

    @property
    def is_processed(self) -> bool:
        """A media item is considered processed if it has a base_url."""
        return bool(self.base_url)

    @classmethod
    def from_api_response(cls, data: dict[str, Any]) -> GooglePhotosMediaItem:
        """Parse a mediaItem response from the Google Photos API."""
        metadata = data.get("mediaMetadata", {})
        mime_type = data.get("mimeType", "")
        is_video = mime_type.startswith("video/") or "video" in metadata

        width = None
        height = None
        if "width" in metadata:
            try:
                width = int(metadata["width"])
            except (ValueError, TypeError):
                pass
        if "height" in metadata:
            try:
                height = int(metadata["height"])
            except (ValueError, TypeError):
                pass

        return cls(
            id=data["id"],
            filename=data.get("filename", ""),
            mime_type=mime_type,
            created_at=metadata.get("creationTime", ""),
            base_url=data.get("baseUrl", ""),
            product_url=data.get("productUrl", ""),
            width=width,
            height=height,
            description=data.get("description", ""),
            is_video=is_video,
        )


@dataclass
class GooglePhotosAlbumData:
    """Full album data assembled from Google Photos API responses."""

    id: str
    name: str
    asset_count: int
    product_url: str
    is_shared: bool
    cover_photo_id: str | None = None
    share_info: dict[str, Any] = field(default_factory=dict)
    asset_ids: set[str] = field(default_factory=set)
    assets: dict[str, GooglePhotosMediaItem] = field(default_factory=dict)

    @property
    def photo_count(self) -> int:
        return sum(1 for a in self.assets.values() if not a.is_video)

    @property
    def video_count(self) -> int:
        return sum(1 for a in self.assets.values() if a.is_video)

    @classmethod
    def from_api_response(
        cls, album_data: dict[str, Any], media_items: list[GooglePhotosMediaItem],
    ) -> GooglePhotosAlbumData:
        """Build album data from album metadata + fetched media items."""
        asset_ids: set[str] = set()
        assets: dict[str, GooglePhotosMediaItem] = {}
        for item in media_items:
            asset_ids.add(item.id)
            assets[item.id] = item

        share_info = album_data.get("shareInfo", {})

        return cls(
            id=album_data["id"],
            name=album_data.get("title", "Untitled"),
            asset_count=int(album_data.get("mediaItemsCount", len(asset_ids))),
            product_url=album_data.get("productUrl", ""),
            is_shared=bool(share_info),
            cover_photo_id=album_data.get("coverPhotoMediaItemId"),
            share_info=share_info,
            asset_ids=asset_ids,
            assets=assets,
        )
