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_BACK = 7

EPG_URL_TEMPLATE = (
    "https://staticeu.sweet.tv/tv/epg/v3/"
    "{cid}/{date}/{lang}.json"
)


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"
    elif upper_name.endswith("HU"):
        lang = "hu"
    elif upper_name.endswith("PL"):
        lang = "pl"
    elif upper_name.endswith("UA"):
        lang = "uk"
    else:
        lang = "sk"


    # 7 dní dozadu + dnes
    for d in range(-DAYS_BACK, 1):

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

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

        url = EPG_URL_TEMPLATE.format(
            cid=cid,
            date=date,
            lang=lang
        )

        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


        if not isinstance(data, list):
            continue


        print(
            "PROGRAMS:",
            len(data)
        )


        for item in data:

            start = item.get("time_start")
            stop = item.get("time_stop")

            if not start or not stop:
                continue


            prog = ET.SubElement(
                tv,
                "programme",
                {
                    "start": ts(start),
                    "stop": ts(stop),
                    "channel": cid
                }
            )


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


            # EPG ID
            epg_id = (
                item.get("epg_id")
                or item.get("id")
                or item.get("epgId")
            )

            if epg_id:

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


            # TV SHOW ID, ak existuje
            tv_show_id = item.get(
                "tv_show_id"
            )

            if tv_show_id:

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


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

os.replace(
    TEMP,
    OUTPUT
)

print()
print("EPG DONE")
print(
    f"Výstup: {OUTPUT}"
)