#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
set_cover.py — Insert or update podcast artwork tags in feed.xml

Usage:
    python set_cover.py --cover-url "https://HOST/cover.png" [--feed "D:/TTS Podcast/feed.xml"] [--title "TTS Feed"]
"""
import argparse, os, sys, xml.etree.ElementTree as ET

ITUNES_NS = "http://www.itunes.com/dtds/podcast-1.0.dtd"

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--cover-url", required=True)
    ap.add_argument("--feed", default=r"D:\TTS Podcast\feed.xml")
    ap.add_argument("--title", default="TTS Feed")
    args = ap.parse_args()

    feed_path = args.feed
    cover_url = args.cover_url
    podcast_title = args.title

    if not os.path.exists(feed_path):
        print(f"[ERROR] feed.xml not found at: {feed_path}")
        sys.exit(1)

    try:
        tree = ET.parse(feed_path)
    except ET.ParseError as e:
        print(f"[ERROR] XML parse error: {e}")
        sys.exit(1)

    root = tree.getroot()
    channel = root.find("channel")
    if channel is None:
        print("[ERROR] <channel> not found under <rss> in feed.xml")
        sys.exit(1)

    ET.register_namespace("itunes", ITUNES_NS)

    # Remove existing itunes:image
    for child in list(channel):
        tag = child.tag
        if tag.endswith('}image') and tag.startswith('{'+ITUNES_NS+'}'):
            channel.remove(child)

    # Add fresh itunes:image after <title> if present
    it_el = ET.Element(f"{{{ITUNES_NS}}}image")
    it_el.set("href", cover_url)
    title_el = channel.find("title")
    if title_el is not None:
        kids = list(channel)
        idx = kids.index(title_el)
        channel.insert(idx+1, it_el)
    else:
        channel.insert(0, it_el)

    # Replace/append <image> block
    for child in list(channel):
        if child.tag == "image":
            channel.remove(child)

    img = ET.Element("image")
    url = ET.SubElement(img, "url"); url.text = cover_url
    ttl = ET.SubElement(img, "title"); ttl.text = podcast_title
    base_link = cover_url.rsplit("/", 1)[0] + "/"
    lnk = ET.SubElement(img, "link"); lnk.text = base_link
    channel.append(img)

    tree.write(feed_path, encoding="utf-8", xml_declaration=True)
    print("[OK] Updated artwork tags.")
    print("itunes:image:", cover_url)
    print("image/url    :", cover_url)
    print("image/link   :", base_link)

if __name__ == "__main__":
    main()
