import subprocess
from flask import Flask, request, jsonify
from lxml import etree
from datetime import datetime, timedelta

app = Flask(__name__)

EPG_FILE = "sky_epg.xml"

@app.route('/update_sky', methods=['POST'])
def update_sky():
    data = request.json
    channel_name = data.get('channel', 'Unbekannt')
    content_title = data.get('content', 'Keine Information')
    
    # Zeitstempel für XMLTV (Start jetzt, Ende in 1 Std als Platzhalter)
    now = datetime.now()
    start_time = now.strftime("%Y%m%d%H%M%S +0100")
    stop_time = (now + timedelta(hours=12)).strftime("%Y%m%d%H%M%S +0100")

    # XML Struktur aufbauen
    root = etree.Element("tv")
    
    # Kanal Info
    channel = etree.SubElement(root, "channel", id="cftv")
    etree.SubElement(channel, "display-name").text = "cftv" #+ channel_name
    
    # Programm Info
    prog = etree.SubElement(root, "programme", 
                            start=start_time, 
                            stop=stop_time, 
                            channel="cftv") #channel_name.replace(" ", ""))
    etree.SubElement(prog, "title").text = content_title
    if data.get('image'):
        etree.SubElement(prog, "icon", src=data['image'])

    # Datei speichern
    tree = etree.ElementTree(root)
    tree.write(EPG_FILE, pretty_print=True, xml_declaration=True, encoding="utf-8")
    
    print(f"EPG aktualisiert: {channel_name} - {content_title}")

    script_path = "/home/sandro/m3u/aktualisiere_epg.py"
    
    try:
        # Wir rufen es asynchron auf, damit die API sofort "success" an HA zurückgeben kann
        subprocess.Popen(["python3", script_path])
        print(f"Externes Skript gestartet: {script_path}")
    except Exception as e:
        print(f"Fehler beim Aufruf des EPG-Skripts: {e}")

    return jsonify({"status": "XML erstellt, Sync gestartet"}), 200

    return jsonify({"status": "xml_updated"}), 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
