#!/usr/bin/env python3
"""
Simple HTTP file server for the PKA podcast RSS feed + audio files.
Serves on port 8484, accessible via Tailscale.
"""

import http.server
import os
import socketserver
from pathlib import Path

BASE_DIR = Path("/mnt/storage/nzbdav/pka-podcast")
PORT = 8484


class PodcastHandler(http.server.SimpleHTTPRequestHandler):
    """Serve files from BASE_DIR with proper MIME types for RSS + audio."""
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=str(BASE_DIR), **kwargs)
    
    def end_headers(self):
        # Set proper content type for RSS feed
        if self.path.endswith('.xml'):
            self.send_header('Content-Type', 'application/rss+xml; charset=utf-8')
        elif self.path.endswith('.mp4'):
            self.send_header('Content-Type', 'video/mp4')
        elif self.path.endswith('.mp3'):
            self.send_header('Content-Type', 'audio/mpeg')
        # Allow access from any app/device
        self.send_header('Access-Control-Allow-Origin', '*')
        super().end_headers()
    
    def log_message(self, format, *args):
        # Minimal logging
        print(f"[{self.log_date_time_string()}] {format % args}")


class ThreadingHTTPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    """Multi-threaded server so feed + large video downloads don't block each other."""
    daemon_threads = True
    allow_reuse_address = True


def main():
    os.chdir(str(BASE_DIR))
    with ThreadingHTTPServer(("0.0.0.0", PORT), PodcastHandler) as httpd:
        print(f"Serving PKA podcast feed on http://0.0.0.0:{PORT}")
        print(f"  Feed URL: http://100.125.84.21:{PORT}/pka_feed.xml")
        print(f"  Directory: {BASE_DIR}")
        httpd.serve_forever()


if __name__ == "__main__":
    main()
