from src.lib.post import (
    get_all_posts_by_artist,
)
from src.pages.artists_types import (
    ArtistDisplayData,
)
from src.types.paysites import Paysite, Paysites
from src.utils.utils import offset_list, sort_dict_list_by, take


def do_artist_post_search(artist_id, service, search, o, limit):
    posts = get_all_posts_by_artist(artist_id, service)
    search = search.lower()

    matches = []
    for post in posts:
        if (
            search in post["content"].lower()
            or search in post["title"].lower()
            or search in " ".join(post["tags"] or []).lower()
        ):
            matches.append(post)

    matches = sort_dict_list_by(matches, "published", True)

    return take(limit, offset_list(o, matches)), len(matches)


def make_artist_display_data(artist: dict) -> ArtistDisplayData:
    service_name: str = artist["service"]
    pay_site: Paysite | None = getattr(Paysites, service_name, None)

    if pay_site:
        return ArtistDisplayData(service=pay_site.title, href=pay_site.user.profile(artist))
    raise Exception("Service not found in Paysites")
