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

from .track import Track


@dataclass
class SearchResult:
    results: 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]) -> "SearchResult":
        if not data or not isinstance(data, dict):
            return cls()
        raw_results = data.get("results", [])
        return cls(
            results=[Track.from_dict(t) for t in raw_results if isinstance(t, dict)],
            _raw=data,
        )

    @property
    def total(self) -> int:
        return len(self.results)

    @property
    def is_empty(self) -> bool:
        return len(self.results) == 0

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

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

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


@dataclass
class RecommendationResult:
    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]) -> "RecommendationResult":
        if not data or not isinstance(data, dict):
            return cls()
        raw_tracks = data.get("tracks", [])
        return cls(
            tracks=[Track.from_dict(t) for t in raw_tracks if isinstance(t, dict)],
            _raw=data,
        )

    @property
    def total(self) -> int:
        return len(self.tracks)

    @property
    def is_empty(self) -> bool:
        return len(self.tracks) == 0

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

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

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