import re
import json
from unidecode import unidecode

m3u_file = "vodafone.m3u"
server_nm3u8dl = "tvh_server_nm3u8dl:8080"
channels = {}

tvg_id_regex = re.compile(r'#EXTINF:-1.*tvg-id="([^"]*)"')
tvg_logo_regex = re.compile(r'#EXTINF:-1.*tvg-logo="([^"]*)"')
group_title_regex = re.compile(r'#EXTINF:-1.*group-title="([^"]*)"')
license_key_regex = re.compile(r'#KODIPROP:inputstream.adaptive.license_key=([^:]+):([^ ]+)')
url_regex = re.compile(r'^(https?://.*)')

def clean_string(s):
    s = s.lower()
    s = s.replace(" ", "_")
    s = re.sub(r'[^\w\s]', '', s)
    s = unidecode(s)
    
    return s

with open(m3u_file, 'r') as f:
    for line in f:
        # Search tvg-id
        match_tvg_id = tvg_id_regex.search(line)
        if match_tvg_id:
            tvg_id = match_tvg_id.group(1)

        # Search tvg-logo
        match_tvg_logo = tvg_logo_regex.search(line)
        if match_tvg_logo:
            tvg_logo = match_tvg_logo.group(1)

        # Search group-title
        match_group_title =group_title_regex.search(line)
        if match_group_title:
            group_title = match_group_title.group(1)
        
        # Search license_key
        match_license_key = license_key_regex.search(line)
        if match_license_key:
            provider_key = match_license_key.group(1)
            content_key = match_license_key.group(2)
        
        # Search URL
        match_url = url_regex.search(line)
        if match_url:
            url = match_url.group(0)
        
            channels[tvg_id] = {
                'group_title': group_title,
                'tvg_logo': tvg_logo,
                'license_key': f'{provider_key}:{content_key}'.strip(),
                'url': url
            }

channels_json = {}
tvheadend_m3u = "#EXTM3U"

for channel in channels:
    channels_json[clean_string(channel)] = {
        "url": channels[channel]['url'],
        "key1": channels[channel]['license_key'],
        "key2": "",
        "key3": "",
        "key4": "",
        "key5": "",
        "useragent": "ExoPlayerLib/2.5.3",
        "authorization": "",
        "referer": "",
        "proxy": "",
        "resolution": ""
    }

    tvheadend_m3u += f'\n#EXTINF:-1 tvg-id="{channel}" tvg-name="{channel}" group-title="{channels[channel]["group_title"]}" tvg-logo="{channels[channel]["tvg_logo"]}",{channel}'
    tvheadend_m3u += f'\nhttp://{server_nm3u8dl}/stream/{clean_string(channel)}'

with open("../channels/channels.json", "w") as nm3u8dl_channels_file:
    nm3u8dl_channels_file.write(json.dumps(channels_json, indent=4))

with open("../channels/tvheadend.m3u", "w") as tvheadend_channels_file:
    tvheadend_channels_file.write(tvheadend_m3u)