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


@dataclass
class Track:
    identifier: str = ""
    title: str = ""
    length: int = 0
    uri: str = ""
    artworkUrl: str = ""
    author: str = ""
    encryptedMediaUrl: str = ""
    albumUrl: str = ""
    artistUrl: str = ""
    albumName: str = ""
    artistArtworkUrl: str = ""
    previewUrl: str = ""
    _raw: Dict[str, Any] = field(default_factory=dict, repr=False)

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "Track":
        if not data or not isinstance(data, dict):
            return cls()
        return cls(
            identifier=str(data.get("identifier", "")),
            title=str(data.get("title", "")),
            length=int(data.get("length", 0)),
            uri=str(data.get("uri", "") or ""),
            artworkUrl=str(data.get("artworkUrl", "") or ""),
            author=str(data.get("author", "") or ""),
            encryptedMediaUrl=str(data.get("encryptedMediaUrl", "") or ""),
            albumUrl=str(data.get("albumUrl", "") or ""),
            artistUrl=str(data.get("artistUrl", "") or ""),
            albumName=str(data.get("albumName", "") or ""),
            artistArtworkUrl=str(data.get("artistArtworkUrl", "") or ""),
            previewUrl=str(data.get("previewUrl", "") or ""),
            _raw=data,
        )

    @property
    def duration(self) -> int:
        return self.length // 1000

    @property
    def duration_ms(self) -> int:
        return self.length

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

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