"""
Podcast Favorites — store, check for new episodes, and return briefing data.

Favorites are stored at ~/.familiar/data/podcast_favorites.json:
{
  "feeds": [
    {
      "name": "Darknet Diaries",
      "feed_url": "https://feeds.megaphone.fm/darknetdiaries",
      "last_seen_guid": "ep-123",
      "last_seen_date": "2026-03-10T00:00:00"
    }
  ]
}
"""

from __future__ import annotations

import json
import logging
from datetime import datetime, timezone
from pathlib import Path

from familiar.skills.media.podcasts import get_episodes

logger = logging.getLogger(__name__)


def _favorites_path() -> Path:
    try:
        from familiar.core.paths import DATA_DIR

        return DATA_DIR / "podcast_favorites.json"
    except ImportError:
        return Path.home() / ".familiar" / "data" / "podcast_favorites.json"


def load_favorites() -> list[dict]:
    path = _favorites_path()
    if not path.exists():
        return []
    try:
        return json.loads(path.read_text()).get("feeds", [])
    except Exception:
        return []


def save_favorites(feeds: list[dict]) -> None:
    path = _favorites_path()
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps({"feeds": feeds}, indent=2))


def add_favorite(feed_url: str, name: str = "") -> str:
    feeds = load_favorites()
    if any(f["feed_url"] == feed_url for f in feeds):
        return f"Already in favorites: {feed_url}"
    # Fetch to get real name if not provided
    if not name:
        episodes = get_episodes(feed_url, limit=1)
        name = feed_url  # fallback
    feeds.append({"name": name, "feed_url": feed_url, "last_seen_guid": "", "last_seen_date": ""})
    save_favorites(feeds)
    return f"Added to podcast favorites: {name}"


def remove_favorite(feed_url: str) -> str:
    feeds = load_favorites()
    before = len(feeds)
    feeds = [f for f in feeds if f["feed_url"] != feed_url]
    if len(feeds) == before:
        return "Not found in favorites."
    save_favorites(feeds)
    return "Removed from podcast favorites."


def check_new_episodes() -> list[dict]:
    """Return list of {name, feed_url, new_episodes: [{title, published, duration}]}
    for any favorite with episodes newer than last_seen_date."""
    feeds = load_favorites()
    if not feeds:
        return []

    results = []
    updated_feeds = list(feeds)

    for i, fav in enumerate(feeds):
        try:
            episodes = get_episodes(fav["feed_url"], limit=5)
            if not episodes:
                continue

            last_seen = fav.get("last_seen_date", "")
            new_eps = []

            for ep in episodes:
                pub = ep.get("published", "")
                if not pub:
                    continue
                # If we have a last_seen_date, only include newer episodes
                if last_seen:
                    try:
                        from email.utils import parsedate_to_datetime

                        ep_dt = parsedate_to_datetime(pub)
                        seen_dt = datetime.fromisoformat(last_seen)
                        if seen_dt.tzinfo is None:
                            seen_dt = seen_dt.replace(tzinfo=timezone.utc)
                        if ep_dt.tzinfo is None:
                            ep_dt = ep_dt.replace(tzinfo=timezone.utc)
                        if ep_dt <= seen_dt:
                            continue
                    except Exception:
                        pass
                new_eps.append(
                    {
                        "title": ep["title"],
                        "published": pub,
                        "duration": ep.get("duration", ""),
                    }
                )

            if new_eps:
                results.append(
                    {
                        "name": fav.get("name", fav["feed_url"]),
                        "feed_url": fav["feed_url"],
                        "new_episodes": new_eps,
                    }
                )
                # Update last_seen_date to the latest episode's date
                try:
                    from email.utils import parsedate_to_datetime

                    latest_dt = parsedate_to_datetime(episodes[0]["published"])
                    updated_feeds[i] = dict(fav)
                    updated_feeds[i]["last_seen_date"] = latest_dt.isoformat()
                except Exception:
                    pass

        except Exception as e:
            logger.debug("Podcast check failed for %s: %s", fav.get("name", "?"), e)

    if results:
        save_favorites(updated_feeds)

    return results
