"""Build CaseTurn podcast RSS feed (Podcast 2.0)"""
import json
import hashlib
import os
import mimetypes
from pathlib import Path
from datetime import datetime, timezone
from xml.sax.saxutils import escape

BASE = Path("/home/workspace/ManimVideos/case-turn-podcast")

# Load metadata
pod = json.load(open(BASE / "podcast.json"))["podcast"]
ep = json.load(open(BASE / "episode_01.json"))["episode"]

# Determine cover path
COVER = BASE / "art" / ep["artwork"]

# Get audio file size
audio_file = BASE / "episodes" / ep["audio_file"]
audio_size = os.path.getsize(audio_file)
audio_duration = ep["duration_seconds"]

# Build enclosure URL (placeholder - will be replaced when hosted)
ENCLOSURE_URL = ep["enclosure_url"]

# Build GUIDs
EPISODE_GUID = ep["guid"]
PODCAST_GUID = pod["feed_id"]

# Now date
NOW = datetime.now(timezone.utc).strftime("%a, %d %b %Y %H:%M:%S +0000")
PUB_DATE = ep["published"]

# Begin XML
out = []
out.append("<?xml version="1.0" encoding="UTF-8"?>")
out.append("<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:podcast="https://podcastindex.org/namespace/1.0">")
out.append("<channel>")
out.append("<title>" + escape(pod["name"]) + "</title>")
out.append("<description>" + escape(pod["description"]["long"]) + "</description>")
out.append("<itunes:summary>" + escape(pod["description"]["short"]) + "</itunes:summary>")
out.append("<link>" + escape(pod["website"]) + "</link>")
out.append("<language>" + pod["language"] + "</language>")
out.append("<itunes:author>" + escape(pod["author"]) + "</itunes:author>")
out.append("<itunes:owner>")
out.append("<itunes:name>" + escape(pod["author"]) + "</itunes:name>")
out.append("<itunes:email>" + pod["editor_email"] + "</itunes:email>")
out.append("</itunes:owner>")
out.append("<copyright>" + escape(pod["copyright"]) + "</copyright>")
out.append("<lastBuildDate>" + NOW + "</lastBuildDate>")
out.append("<pubDate>" + PUB_DATE + "</pubDate>")
out.append("<atom:link href=\" + pod["feed_url"] + \" rel="self" type="application/rss+xml" />")
out.append("<itunes:image href=\" + pod["cover_art_url"] + \" />")
out.append("<itunes:category text="Education" />")
out.append("<itunes:category text="Education" />")
out.append("<itunes:category text="News" />")
out.append("<itunes:explicit>" + pod["explicit"] + "</itunes:explicit>")
out.append("<itunes:type>" + pod["show_type"] + "</itunes:type>")
out.append("<itunes:new-feed-url>" + pod["feed_url"] + "</itunes:new-feed-url>")
out.append("<podcast:locked>" + pod["locked"] + "</podcast:locked>")
out.append("<podcast:guid>" + PODCAST_GUID + "</podcast:guid>")

# Item: episode 1
out.append("<item>")
out.append("<title>" + escape(ep["title"]) + "</title>")
out.append("<description><![CDATA[" + ep["show_notes"] + "]]></description>")
out.append("<itunes:summary><![CDATA[" + ep["short_summary"] + "]]></itunes:summary>")
out.append("<itunes:subtitle><![CDATA[" + ep["subtitle"] + "]]></itunes:subtitle>")
out.append("<content:encoded><![CDATA[" + ep["show_notes"] + "]]></content:encoded>")
out.append("<guid isPermaLink="false">" + EPISODE_GUID + "</guid>")
out.append("<pubDate>" + PUB_DATE + "</pubDate>")
out.append("<enclosure url=\" + ENCLOSURE_URL + \" length=\" + str(audio_size) + \" type="audio/mpeg" />")
out.append("<itunes:duration>" + ep["duration_iso"] + "</itunes:duration>")
out.append("<itunes:image href=\" + pod["cover_art_url"] + \" />")
out.append("<itunes:explicit>" + pod["explicit"] + "</itunes:explicit>")
out.append("<itunes:episode>" + str(ep["episode_number"]) + "</itunes:episode>")
out.append("<itunes:season>1</itunes:season>")
out.append("<itunes:episodeType>full</itunes:episodeType>")

# Chapters
out.append("<podcast:chapters version="1.2">")
for ch in ep["chapters"]:
    out.append("<podcast:chapter start=\" + str(ch["start"]) + \" title=\" + escape(ch["title"]) + \" />")
out.append("</podcast:chapters>")

# Transcript
out.append("<podcast:transcript url=\" + ep["transcript_url"] + \" type="text/plain" />")
out.append("</item>")

out.append("</channel>")
out.append("</rss>")

with open(BASE / "feed.rss.xml", "w") as f:
    f.write(chr(10).join(out))
print("RSS feed written:", BASE / "feed.rss.xml")
