#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
force_add_one.py — diagnostics + force-add newest audio file to feed.xml
Place in the SAME folder as feed.xml and your audio files, then run:
    python force_add_one.py
"""

import os, sys, datetime, xml.etree.ElementTree as ET
from email.utils import format_datetime

SUPPORTED_EXTS = (".mp3", ".m4a")
MIME_BY_EXT = {
    ".mp3": "audio/mpeg",
    ".m4a": "audio/mp4",
}
BASE_URL = "http://100.91.80.69:8082/"

def rfc2822(dt_utc: datetime.datetime) -> str:
    if dt_utc.tzinfo is None:
        dt_utc = dt_utc.replace(tzinfo=datetime.timezone.utc)
    return format_datetime(dt_utc)

def newest_audio(cwd):
    audio = [f for f in os.listdir(cwd) if os.path.splitext(f.lower())[1] in SUPPORTED_EXTS]
    audio.sort(key=lambda f: os.path.getmtime(os.path.join(cwd, f)), reverse=True)
    return audio[0] if audio else None

def main():
    cwd = os.path.abspath(os.getcwd())
    print("[INFO] Working directory:", cwd)
    files = os.listdir(cwd)
    print("[INFO] Files here:", files)

    feed = os.path.join(cwd, "feed.xml")
    if not os.path.exists(feed):
        print("[ERROR] feed.xml not found here. Make sure you're in the folder with feed.xml")
        sys.exit(1)

    try:
        tree = ET.parse(feed)
        root = tree.getroot()
        channel = root.find("channel")
        if channel is None:
            print("[ERROR] feed.xml missing <channel> element.")
            sys.exit(1)
    except ET.ParseError as e:
        print("[ERROR] XML parse error:", e)
        sys.exit(1)

    newest = newest_audio(cwd)
    if not newest:
        print("[ERROR] No .mp3 or .m4a files found here.")
        sys.exit(1)

    print("[INFO] Will add newest audio file:", newest)

    path = os.path.join(cwd, newest)
    size = os.path.getsize(path)
    mtime = datetime.datetime.utcfromtimestamp(os.path.getmtime(path)).replace(tzinfo=datetime.timezone.utc)
    mime = MIME_BY_EXT.get(os.path.splitext(newest)[1].lower(), "application/octet-stream")

    # Build item
    item = ET.Element("item")
    title_el = ET.SubElement(item, "title"); title_el.text = os.path.splitext(newest)[0]
    enc = ET.SubElement(item, "enclosure")
    enc.set("url", f"{BASE_URL}{newest}")
    enc.set("length", str(size))
    enc.set("type", mime)
    guid = ET.SubElement(item, "guid"); guid.text = f"{BASE_URL}{newest}"
    pub = ET.SubElement(item, "pubDate"); pub.text = rfc2822(mtime)

    # Insert near top
    channel.insert(1, item)

    tree.write(feed, encoding="utf-8", xml_declaration=True)
    print("[OK] Added item and wrote feed.xml successfully.")

if __name__ == "__main__":
    main()
