# -*- coding: utf-8 -*-
import re

QUALITY_TOKENS = set(["HD", "FHD", "SD", "UHD", "4K", "8K", "HEVC", "H.265", "H265"])

def compute_category(display_name):
    """
    'DE| NEWS 1 HD' -> 'DE NEWS'
    """
    name = display_name.strip()
    lang = ""
    rest  = name

    if "|" in name:
        parts = name.split("|", 1)
        lang  = parts[0].strip()      # DE
        rest  = parts[1].strip()      # NEWS 1 HD

    tokens = rest.split()
    kept = []
    for t in tokens:
        t_upper = t.upper()
        if t.isdigit() or t_upper in QUALITY_TOKENS:
            break
        kept.append(t)

    if kept:
        base = " ".join(kept)
    else:
        base = rest

    if lang:
        return (lang + " " + base).strip()
    else:
        return base


def process_m3u_file(input_file, output_file):
    with open(input_file, "r", encoding="utf-8") as f:
        lines = f.readlines()

    output_lines = ["#EXTM3U\n"]

    i = 0
    while i < len(lines):
        line = lines[i].strip()

        if line.startswith("#EXTINF"):
            if i + 1 < len(lines):
                url_line = lines[i + 1].strip()
                if not (url_line.startswith("http://") or url_line.startswith("https://")):
                    i += 1
                    continue

                # Display-Name aus EXTINF holen (alles nach dem letzten Komma)
                m = re.search(r",(.+)$", line)
                if not m:
                    i += 2
                    continue

                display_name = m.group(1).strip()          # z.B. DE| NEWS 1 HD, EN| CHRISTMAS 1 4K

                # *** Filter: nur DE-Sender ***
                if not display_name.upper().startswith("DE|"):
                    i += 2
                    continue

                category = compute_category(display_name)   # z.B. DE NEWS

                # Anzeigename: "DE NEWS - DE| NEWS 1 HD"
                full_name = "{} - {}".format(category, display_name)

                # Minimal-Format, das bei dir läuft
                output_lines.append("#EXTINF:-1,{}\n".format(full_name))
                output_lines.append(url_line + "\n")

                i += 2
            else:
                i += 1
        else:
            i += 1

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

    print("Fertige Playlist geschrieben nach '{}' mit {} Einträgen.".format(
        output_file, (len(output_lines) - 1) // 2
    ))


if __name__ == "__main__":
    process_m3u_file("streams.txt", "analog.m3u")
