import re
import urllib.request
import unicodedata
import xml.etree.ElementTree as ET

TVG_URL = "https://epg-sw.duckdns.org/sledovani.xml"

INPUT_M3U = "/opt/epg/playlist.m3u"
OUTPUT_M3U = "/opt/epg/playlist_epg.m3u"


def normalize(name):
    name = name.upper().strip()

    # odstránenie diakritiky
    name = unicodedata.normalize("NFKD", name)
    name = "".join(
        c for c in name
        if not unicodedata.combining(c)
    )

    # odstráni prefix krajiny
    name = re.sub(r'^[A-Z]{2,3}\s*\|\s*', '', name)

    # odstráni .CZ .SK .TR
    name = re.sub(r'\.[A-Z]{2,3}$', '', name)

    # odstráni HD/FHD/UHD/SD/4K/HEVC/H265/H264
    name = re.sub(
        r'(HD|FHD|UHD|SD|4K|HEVC|H265|H264|ᴴᴰ)',
        '',
        name
    )

    # odstráni +1
    name = re.sub(r'\+1', '', name)

    # odstráni CZ/SK
    name = re.sub(r'\b(CZ|SK)\b', '', name)

    # iba písmená a čísla
    name = re.sub(r'[^A-Z0-9]', '', name)

    return name.lower()


print("Downloading EPG...")

xml_data = urllib.request.urlopen(TVG_URL).read()

root = ET.fromstring(xml_data)

channels = {}

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

    tvg_id = channel.get("id")

    display_name = channel.findtext("display-name")

    if not tvg_id or not display_name:
        continue

    key = normalize(display_name)

    channels[key] = tvg_id

print(f"Loaded {len(channels)} channels from EPG.")


matched = 0
not_found = 0


with open(INPUT_M3U, encoding="utf-8", errors="ignore") as f:
    lines = f.readlines()


out = []


for line in lines:

    if line.startswith("#EXTINF"):

        if "," in line:

            title = line.split(",", 1)[1].strip()

            key = normalize(title)

            if key in channels:

                cid = channels[key]

                if 'tvg-id="' in line:

                    line = re.sub(
                        r'tvg-id="[^"]*"',
                        f'tvg-id="{cid}"',
                        line
                    )

                else:

                    line = line.replace(
                        "#EXTINF:-1",
                        f'#EXTINF:-1 tvg-id="{cid}"'
                    )

                matched += 1

            else:

                print("Not found:", title)
                not_found += 1

    out.append(line)


with open(OUTPUT_M3U, "w", encoding="utf-8") as f:
    f.writelines(out)


print()
print(f"Matched {matched} channels.")
print(f"Not found {not_found} channels.")
print(f"Output: {OUTPUT_M3U}")
print("Finished.")