
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta
import json
import re

INPUT = "/opt/epg/sweet_archiv_epg.xml"
ARCHIV_JSON = "/opt/epg/archiv.json"
OUTPUT = "/opt/epg/catchup.m3u"
BASE_URL = "https://epg-sw.duckdns.org/archive"

# Archív: posledné 3 dni + dnes
DAYS_BACK = 3


# ==========================================
# Načítanie názvov kanálov z archiv.json
# ==========================================

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


# Vytvorí napríklad:
# 952 -> "Catch-up/Markiza HD"
# 954 -> "Catch-up/Doma HD"

GROUPS = {}

for cid, name in channels.items():

    # odstráni časť "(952) SK"
    channel_name = re.sub(r"\s*\(\d+\)\s*[A-Z]{2}\s*$", "", name).strip()

    GROUPS[str(cid)] = f"Catch-up/{channel_name}"


# ==========================================
# Načítanie EPG
# ==========================================

tree = ET.parse(INPUT)
root = tree.getroot()

now = datetime.now()
oldest_date = (now - timedelta(days=DAYS_BACK)).strftime("%Y%m%d")


# ==========================================
# Vytvorenie catchup.m3u
# ==========================================

with open(OUTPUT, "w", encoding="utf-8") as f:

    f.write("#EXTM3U\n\n")

    for programme in root.findall("programme"):

        cid = programme.get("channel")
        start = programme.get("start", "")[:14]

        title = programme.findtext("title") or "Unknown"

        if not cid or len(start) != 14:
            continue

        # iba posledné 3 dni + dnešok
        if start[:8] < oldest_date:
            continue

        url = f"{BASE_URL}/{cid}/{start}"

        # Automatická skupina podľa archiv.json
        group = GROUPS.get(cid, "Catch-up")

        f.write(
            f'#EXTINF:-1 tvg-id="{cid}" '
            f'tvg-name="{title}" '
            f'group-title="{group}",{title}\n'
        )

        f.write(f"{url}\n\n")


print(f"Catch-up M3U vytvorené: {OUTPUT}")
