import os

OUTPUT_DIR = "/home/o11/iptv"

VERSIONS = {
    "V1_Italia": {
        "path": "/mnt/nas/Daten/M3u Mapped/V3",
        "epg": "https://epgshare01.online/epgshare01/epg_ripper_IT1.xml.gz",
    },
    "V2_o11v2": {
        "path": "/mnt/nas/Daten/M3u Mapped/V2",
        "epg": "https://extras.vip-arena.net/smiley/epg/epg.xml.gz https://epg.ovh/pltv.xml https://epgshare01.online/epgshare01/epg_ripper_IT1.xml.gz",
    },
    "V3_Polen": {
        "path": "/mnt/nas/Daten/M3u Mapped/V1",
        "epg": "https://epg.ovh/pltv.xml",
    },
    "V4_DACH": {
        "path": "/mnt/nas/Daten/M3u Mapped/V4",
        "epg": "https://extras.vip-arena.net/smiley/epg/epg.xml.gz",
    },
}


def merge_m3u_folder(folder):
    merged = []

    for root, _, files in os.walk(folder):
        for file in sorted(files):
            if not file.endswith(".m3u"):
                continue

            full = os.path.join(root, file)

            with open(full, encoding="utf-8", errors="ignore") as f:
                for line in f:
                    if line.startswith("#EXTM3U"):
                        continue
                    if line.strip():
                        merged.append(line.strip())

    return merged


def write_version(name, folder, epg):
    print(f"\nBAUE {name}")

    lines = merge_m3u_folder(folder)
    out = os.path.join(OUTPUT_DIR, f"{name}.m3u")

    with open(out, "w", encoding="utf-8") as f:
        f.write(f'#EXTM3U x-tvg-url="{epg}"\n')
        f.write("\n".join(lines))

    print(f"OK: {out}")


def main():
    for name, cfg in VERSIONS.items():
        write_version(name, cfg["path"], cfg["epg"])

    print("\nFERTIG ENIGMA")


if __name__ == "__main__":
    main()

