import json
import requests
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta, timezone
import os

INPUT = "/opt/epg/channels_full.json"
OUTPUT = "/opt/epg/epg.xml"
TEMP = "/opt/epg/epg.xml.tmp"

DAYS = 3

def ts(x):
    return datetime.fromtimestamp(x, timezone.utc).strftime("%Y%m%d%H%M%S +0000")

with open(INPUT, "r", encoding="utf-8") as f:
    channels = json.load(f)

tv = ET.Element("tv")

session = requests.Session()

for cid, name in channels.items():

    ch = ET.SubElement(tv, "channel", id=cid)
    ET.SubElement(ch, "display-name").text = name

    upper_name = name.upper().strip()

    if upper_name.endswith("CZ"):
        lang = "cs"
    elif upper_name.endswith("SK"):
        lang = "sk"
    else:
        lang = "sk"

    for d in range(DAYS):

        date = (datetime.now() + timedelta(days=d)).strftime("%d-%m-%Y")

        print(f"{cid} {name} -> {lang} -> {date}")

        url = f"https://static.sweet.tv/tv/epg/v3/{cid}/{date}/{lang}.json"

        try:
            r = session.get(url, timeout=10)

            if r.status_code == 404:
                print(f"EPG pre {date} nie je dostupné")
                continue

            r.raise_for_status()
            data = r.json()

        except Exception as e:
            print(f"Chyba {cid} ({name}): {e}")
            continue

        for item in data:

            prog = ET.SubElement(tv, "programme", {
                "start": ts(item["time_start"]),
                "stop": ts(item["time_stop"]),
                "channel": cid
            })

            ET.SubElement(prog, "title").text = item.get("text", "")

ET.ElementTree(tv).write(
    TEMP,
    encoding="utf-8",
    xml_declaration=True
)

os.replace(TEMP, OUTPUT)

print("EPG DONE")