import hashlib
import time

import pytz
import requests
from django.conf import settings
from django.utils import timezone
from scrobbles.utils import timestamp_user_tz_to_utc

PODCASTINDEX_API_KEY = getattr(settings, "PODCASTINDEX_API_KEY")
PODCASTINDEX_API_SECRET = getattr(settings, "PODCASTINDEX_API_SECRET")


def get_auth_headers():
    now = int(time.time())
    hash_data = hashlib.sha1(
        (PODCASTINDEX_API_KEY + PODCASTINDEX_API_SECRET + str(now)).encode("utf-8")
    ).hexdigest()

    return {
        "User-Agent": "MyPodcastApp/1.0",
        "X-Auth-Date": str(now),
        "X-Auth-Key": PODCASTINDEX_API_KEY,
        "Authorization": hash_data,
        "Content-Type": "application/json",
    }


def lookup_podcast_from_podcastindex(
    podcast_name: str, dump_raw_response: bool = False
) -> dict:
    url = "https://api.podcastindex.org/api/1.0/search/byterm"
    headers = get_auth_headers()
    params = {"q": podcast_name}

    response = requests.get(url, headers=headers, params=params)

    if response.status_code == 200:
        data = response.json()
        if dump_raw_response:
            return data.get("feeds")
        if data.get("feeds"):
            try:
                top_feed_dict = data["feeds"][0]

                newest_episode_date = timestamp_user_tz_to_utc(
                    top_feed_dict.get("newestItemPubdate"), pytz.UTC
                )
                days_since_last_episode = ()
                dead_date = None
                if (timezone.now() - newest_episode_date).days > 180:
                    dead_date = newest_episode_date

                return {
                    "podcastindex_id": top_feed_dict.get("id"),
                    "title": top_feed_dict.get("title"),
                    "site_link": top_feed_dict.get("link"),
                    "description": top_feed_dict.get("description"),
                    "owner": top_feed_dict.get("ownerName"),
                    "image_url": top_feed_dict.get("artwork"),
                    "feed_url": top_feed_dict.get("url"),
                    "itunes_id": top_feed_dict.get("itunesId"),
                    "genres": list(top_feed_dict.get("categories").values()),
                    "dead_date": dead_date,
                }
            except IndexError:
                return {}
        else:
            print("No podcasts found.")
            return {}
    else:
        print("Failed to fetch data:", response.status_code, response.text)
        return {}
