import Parser from "rss-parser";

import type { ContentItem } from "../content/types";

export async function fetchPodcastRss(rssUrl: string, limit = 50): Promise<ContentItem[]> {
  const parser = new Parser();
  const feed = await parser.parseURL(rssUrl);
  return normalizePodcastFeedItems(feed.items || [], limit);
}

function stripHtml(s: string) {
  return (s || "")
    .replace(/<[^>]+>/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

function truncate(s: string, n: number) {
  const t = stripHtml(s);
  if (!t) return "";
  if (t.length <= n) return t;
  return `${t.slice(0, Math.max(0, n - 1)).trimEnd()}…`;
}

export function normalizePodcastFeedItems(items: any[], limit: number): ContentItem[] {
  const out = (items || []).slice(0, limit).map((it) => {
    const url = it.link || "";
    const id = (it.guid || it.id || url).toString();
    const audioUrl = (it.enclosure?.url || "").toString();
    const publishedAt = (it.isoDate || it.pubDate || new Date(0).toISOString()).toString();
    const summary = truncate(
      (it.contentSnippet ||
        it.summary ||
        it.content ||
        it["content:encoded"] ||
        it.itunes?.subtitle ||
        "").toString(),
      240,
    );
    return {
      id,
      source: "podcast" as const,
      url,
      title: (it.title || "").toString(),
      summary: summary || undefined,
      publishedAt: new Date(publishedAt).toISOString(),
      thumbnailUrl: (it.itunes?.image || undefined) as string | undefined,
      audioUrl: audioUrl || undefined,
    };
  });

  return out.filter((x) => x.url && x.title);
}
