import urllib.request
import re

ASSET_MAP_CACHE = None

def get_asset_map():
    global ASSET_MAP_CACHE
    if ASSET_MAP_CACHE is not None:
        return ASSET_MAP_CACHE
    
    asset_map = {}
    try:
        url = "https://addictedbytheproject.nl/epg_general/assets/"
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        html = urllib.request.urlopen(req, timeout=10).read().decode('utf-8')
        links = re.findall(r'href="([^"]+)"', html)
        for link in links:
            if link.startswith('?') or link.startswith('/'):
                continue
            name_without_ext = link.rsplit('.', 1)[0].lower()
            asset_map[name_without_ext] = link
        ASSET_MAP_CACHE = asset_map
        print(f"Loaded {len(asset_map)} asset mappings.")
    except Exception as e:
        print(f"Failed: {e}")
        ASSET_MAP_CACHE = {}
    return ASSET_MAP_CACHE

def test_channels(channels):
    asset_map = get_asset_map()
    for chan in channels:
        fmt = chan.lower().replace(" ", "_").replace("+", "plus")
        if "sky_sport_25" in fmt:
            fmt = "sky_sport"
        elif fmt == "sky_tv8" or fmt == "sky_tv8_hd":
            fmt = "tv8"
        
        if fmt in asset_map:
            img = asset_map[fmt]
        elif fmt.replace("_", "") in asset_map:
            img = asset_map[fmt.replace("_", "")]
        else:
            img = "NOT FOUND"
        print(f"{chan:25} -> {img}")

channels = ["Sky Classica", "Sky Adventure", "Canale 5", "Rai 1", "Italia 1", "Sky Uno Plus", "Cielo"]
test_channels(channels)
