from dataclasses import dataclass, field
from typing import Any, Dict, List

from .track import Track


@dataclass
class Album:
    id: str = ""
    name: str = ""
    uri: str = ""
    artworkUrl: str = ""
    author: str = ""
    totalSongs: int = 0
    tracks: List[Track] = field(default_factory=list)
    _raw: Dict[str, Any] = field(default_factory=dict, repr=False)

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "Album":
        if not data or not isinstance(data, dict):
            return cls()
        album_data = data.get("album", data)
        raw_tracks = album_data.get("tracks", [])
        tracks = [Track.from_dict(t) if isinstance(t, dict) else t for t in raw_tracks]
        return cls(
            id=str(album_data.get("id", "")),
            name=str(album_data.get("name", "")),
            uri=str(album_data.get("uri", "") or ""),
            artworkUrl=str(album_data.get("artworkUrl", "") or ""),
            author=str(album_data.get("author", "") or ""),
            totalSongs=int(album_data.get("totalSongs", len(tracks))),
            tracks=tracks,
            _raw=data,
        )

    @property
    def url(self) -> str:
        return self.uri

    @property
    def track_count(self) -> int:
        return self.totalSongs or len(self.tracks)

    def __str__(self) -> str:
        return f"{self.name} - {self.author}" if self.author else self.name

    def __len__(self) -> int:
        return len(self.tracks)

    def __iter__(self):
        return iter(self.tracks)

    def __getitem__(self, index):
        return self.tracks[index]
