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

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

DAYS = 7


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():

    # Povolené kanály
    if cid not in ("953", "954"):
        continue

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

    upper_name = name.upper().strip()

    # Určenie jazyka podľa koncovky názvu
    if upper_name.endswith("CZ"):
        lang = "cs"
    elif upper_name.endswith("SK"):
        lang = "sk"
    elif upper_name.endswith("HU"):
        lang = "hu"
    elif upper_name.endswith("PL"):
        lang = "pl"
    elif upper_name.endswith("UA"):
        lang = "uk"
    else:
        lang = "sk"

    for d in range(-7, 1):

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

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

        url = (
            f"https://staticeu.sweet.tv/tv/epg/v3/"
            f"{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
                }
            )

            # Názov programu
            ET.SubElement(
                prog,
                "title"
            ).text = item.get("text", "")

            # Sweet.tv EPG ID
            epg_id = item.get("id")

            if epg_id:
                ET.SubElement(
                    prog,
                    "episode-num",
                    {
                        "system": "sweet.tv"
                    }
                ).text = str(epg_id)

            # Sweet.tv Show ID, ak existuje
            show_id = item.get("show_id")

            if show_id:
                ET.SubElement(
                    prog,
                    "episode-num",
                    {
                        "system": "sweet.tv-show"
                    }
                ).text = str(show_id)


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

os.replace(TEMP, OUTPUT)

print("EPG DONE")

