from urllib.parse import urlencode, parse_qsl
import sys, xbmcgui, xbmcplugin, requests, os, re, json
import xbmcaddon, xbmc, urllib.request
import shutil, zipfile
import datetime

addon = xbmcaddon.Addon()
info_update = "https://www.dropbox.com/scl/fi/ii5dcdnn2x3i9kk4stgg6/ver.txt?rlkey=s2f5u1b1x6ozom342fpmjh6hj&e=1&st=nmurh0r8&dl=1"
download_url = "https://www.dropbox.com/scl/fi/clzeq4gef77sfknuwn2uw/plugin.video.90phuttv.zip?rlkey=conqnudz4btkrq6svkas0zkc5&st=hiido3ka&dl=1"
current_version = addon.getAddonInfo('version')
response = requests.get(info_update, timeout=15, verify=False)
if response.status_code == 200:
    info_version = response.content.decode('utf-8')
    latest_version = re.search(r'ver: "(.*?)"', info_version)
    latest_version_detail = re.search(r'info: "(.*?)"', info_version)
    if latest_version.group(1) != current_version:
        temp_dir = os.path.join(addon.getAddonInfo('path'), 'temp')
        os.makedirs(temp_dir, exist_ok=True)
        response = requests.get(download_url, verify=False)
        if response.status_code == 200:
            zip_file = os.path.join(temp_dir, 'update.zip')
            with open(zip_file, 'wb') as f:
                f.write(response.content)
            with zipfile.ZipFile(zip_file, 'r') as zip_ref:
                zip_ref.extractall(temp_dir)
            extracted_dir = os.path.join(temp_dir, addon.getAddonInfo('id'))
            addon_dir = addon.getAddonInfo('path')

            for root, dirs, files in os.walk(extracted_dir):
                for file_name in files:
                    src_file = os.path.join(root, file_name)
                    relative_path = os.path.relpath(src_file, extracted_dir)
                    dest_file = os.path.join(addon_dir, relative_path)
                    dest_dir = os.path.dirname(dest_file)
                    if not os.path.exists(dest_dir):
                        os.makedirs(dest_dir)
                    shutil.move(src_file, dest_file)
            
            shutil.rmtree(temp_dir)
            dialog = xbmcgui.Dialog()
            dialog.ok('Đã cập nhật phiên bản mới!', latest_version_detail.group(1)+'\nVui lòng khởi động lại Kodi để cập nhật có hiệu lực!')
else:
    dialog = xbmcgui.Dialog()
    dialog.ok('Lỗi cập nhật!', 'Kết nối dữ liệu cập nhật không thành công.')

base_url = sys.argv[0]
HANDLE = int(sys.argv[1])
ADDON_PATH = addon.getAddonInfo('path')
def get_url(**kwargs):
    return base_url + '?' + urlencode(kwargs)
menu = [
{
    "name": "CakhiaTV",
    "id": "cakhia",
    "logo": os.path.join(ADDON_PATH, 'icon.cakhia.png'),
    "fanart": os.path.join(ADDON_PATH, 'fanart.cakhia.jpg'),
    "desc": "Tr\u1ef1c ti\u1ebfp b\u00f3ng \u0111\u00e1 CakhiaTV",
},
{
    "name": "SaokeTV",
    "id": "saoke",
    "logo": os.path.join(ADDON_PATH, 'icon.saoke.png'),
    "fanart": os.path.join(ADDON_PATH, 'fanart.saoke.png'),
    "desc": "Tr\u1ef1c ti\u1ebfp b\u00f3ng \u0111\u00e1 SaokeTV",
},
{
    "name": "LuongsonTV",
    "id": "luongson",
    "logo": os.path.join(ADDON_PATH, 'icon.luongson.png'),
    "fanart": os.path.join(ADDON_PATH, 'fanart.luongson.jpg'),
    "desc": "Tr\u1ef1c ti\u1ebfp b\u00f3ng \u0111\u00e1 LuongsonTV",
},
{
    "name": "Sports Online",
    "id": "spo",
    "logo": os.path.join(ADDON_PATH, 'icon.spotsonline.png'), 
    "fanart": os.path.join(ADDON_PATH, 'fanart.spotsonline.jpg'),
    "desc": "Tr\u1ef1c ti\u1ebfp b\u00f3ng \u0111\u00e1 Sports Online",
}
#{
#    "name": "Highlights",
#    "id": "highlights",
#    "logo": os.path.join(ADDON_PATH, 'icon.highlights.jpg'),
#    "fanart": os.path.join(ADDON_PATH, 'fanart.highlights.jpg'),
#    "desc": "Highlights c\u00e1c tr\u1eadn \u0111\u1ea5u t\u00e2m \u0111i\u1ec3m",
#},
#{
#	"name": "Xem l\u1ea1i",
#	"id": "replay",
#	"logo": os.path.join(ADDON_PATH, 'icon.replay.jpg'),
#	"fanart": "",
#	"desc": "Xem l\u1ea1i c\u00e1c tr\u1eadn \u0111\u1ea5u \u0111\u00e3 di\u1ec5n ra",
#	"isfolder": "True"
#}
]

def list_menu(menu):
    for k in menu:
        name = k["name"]
        match = k["id"]
        logo = k["logo"]
        fanart = k["fanart"]
        desc = k["desc"]
        list_item = xbmcgui.ListItem(name)
        list_item.setArt({'thumb': logo, 'poster': logo, 'banner': logo, 'icon': logo, 'fanart': fanart})
        list_item.setInfo(type='video', infoLabels={'title': name,'sorttitle': name,'plot': desc})
        list_item.setProperty("IsPlayable", 'false')
        url = get_url(action='list_type', link=match)
        xbmcplugin.addDirectoryItem(HANDLE, url, list_item, isFolder=True)
    xbmcplugin.endOfDirectory(HANDLE)

def list_cakhia():
    headers = {
              "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
              'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
              'Accept-Language': 'vi-VN,vi;q=0.8,en-US;q=0.5,en;q=0.3',
              'Connection': 'keep-alive'
              }
    api = 'https://api.rkdata.xyz/v1/cakhia/match.html'
    data_match = requests.get(url=api, headers=headers).json()
    for item in data_match['data']['lives']:
        blv = '|BLV: ' + item['blv']['name']
        if not item['blv']['name']:
            blv = ''
        name = item['timeShort']+": "+item['home']['name']+" vs "+item['away']['name']+blv
        match = item['url']
        logo = os.path.join(ADDON_PATH, 'icon.cakhia.png')
        fanart = ""
        desc = item['tournament']['name']
        list_item = xbmcgui.ListItem(name)
        list_item.setArt({'thumb': logo, 'poster': logo, 'banner': logo, 'icon': logo, 'fanart': fanart})
        list_item.setInfo(type='video', infoLabels={'title': name,'sorttitle': name,'plot': desc})
        list_item.setProperty("IsPlayable", 'false')
        url = get_url(action='cakhia', link=match)
        xbmcplugin.addDirectoryItem(HANDLE, url, list_item, isFolder=True)
    xbmcplugin.endOfDirectory(HANDLE)

def list_link_cakhia(link):
    headers = {
              "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
              'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
              'Accept-Language': 'vi-VN,vi;q=0.8,en-US;q=0.5,en;q=0.3',
              'Connection': 'keep-alive'
              }
    api_link = 'https://api.rkdata.xyz/v1/cakhia/match.html'
    data = requests.get(url=api_link, headers=headers).json()
    url = 'http://' + data['data']['baseLink'][0]+link.replace('.html', '')
    data = requests.get(url=url, headers=headers).text
    match1 = re.search(r'\\"links\\":\[(.*?)\]\},', data, re.S)
    if match1:
        data_link = re.search(r'\[\{(.*?)\}\]', match1.group(0))
    if data_link:
        name_link = re.findall(r'name":"(.*?)"', data_link.group(0).replace('\\', ''))
        hls_link = re.findall(r'url":"(.*?)"', data_link.group(0).replace('\\', ''))
        for i in range(len(hls_link)):
            if ".m3u8" in hls_link[i] or ".flv" in hls_link[i]:
                logo = os.path.join(ADDON_PATH, 'icon.cakhia.png')
                name = name_link[i]
                match = hls_link[i]+'|Referer=https://watch.rkplayer.xyz/'
                fanart = ""
                desc = "Link: "+name_link[i]
                list_item = xbmcgui.ListItem(name)
                list_item.setArt({'thumb': logo, 'poster': logo, 'banner': logo, 'icon': logo, 'fanart': fanart})
                list_item.setInfo(type='video', infoLabels={'title': name,'sorttitle': name,'plot': desc})
                list_item.setProperty("IsPlayable", 'true')
                xbmcplugin.addDirectoryItem(HANDLE, match, list_item, isFolder=False)
    xbmcplugin.endOfDirectory(HANDLE)

def list_saoke():
    headers = {
              "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
              'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
              'Accept-Language': 'vi-VN,vi;q=0.8,en-US;q=0.5,en;q=0.3',
              'Connection': 'keep-alive'
              }
    web = xbmcaddon.Addon().getSetting('saoke_url')
    temp = requests.get(web).text
    url = re.search(r'web:\["(.*?)"', temp).group(1)
    data_match = requests.get(url=url, headers=headers).text
    html = data_match.split('lives=')[1]
    html = html.split('footer')[0]
    html = html.split('},{_id:')
    for item in html:
        match1 = re.search(r'"(.*?)",nameNoUtf8', item)
        match4 = re.search(r'nameNoUtf8:"(.*?)"', item)
        match2 = re.search(r'hôm nay: (.*?)"', item)
        match3 = re.search(r'",time:(.*?),teamAId', item)
        data_league = item.split('league:{_id')[1]
        match5 = re.search(r',name:"(.*?)"', data_league)
        match6 = re.findall(r'picture:"(.*?)"', item)
        match7 = re.search(r'blv:"(.*?)"', item)
        logo = match6[2]
        if logo == '':
            logo = os.path.join(ADDON_PATH, 'icon.saoke.png')
        time = match3.group(1).split('e')[0]
        if len(time) == 7:
            time += '0'
        time += '00'
        if len(time) == 8:
            time += '00'
        time = datetime.datetime.fromtimestamp(int(time)).strftime('%Hh%M-%d/%m')
        blv = '|BLV: ' + match7.group(1)
        if not match7.group(1):
            blv = ''
        name = time+": "+match2.group(1)+blv
        match = f"{match4.group(1)}-{match1.group(1)}"
        fanart = ""
        desc = match5.group(1)
        list_item = xbmcgui.ListItem(name)
        list_item.setArt({'thumb': logo, 'poster': logo, 'banner': logo, 'icon': logo, 'fanart': fanart})
        list_item.setInfo(type='video', infoLabels={'title': name,'sorttitle': name,'plot': desc})
        list_item.setProperty("IsPlayable", 'false')
        url = get_url(action='saoke', link=match)
        xbmcplugin.addDirectoryItem(HANDLE, url, list_item, isFolder=True)
    xbmcplugin.endOfDirectory(HANDLE)

def list_link_saoke(link):
    headers = {
              "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
              'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
              'Accept-Language': 'vi-VN,vi;q=0.8,en-US;q=0.5,en;q=0.3',
              'Cookie': "_ga=GA1.1.1004931860.1740033531; _ga_CFWC6W7DM6=GS1.1.1740033531.1.1.1740033893.0.0.0; _ga_94F2S8MBTB=GS1.1.1740033532.1.1.1740033893.60.0.0; _ga_5TCQ2TL8D6=GS1.1.1740033532.1.1.1740033893.0.0.0; _ga_F8XK0CVH7G=GS1.1.1740033532.1.1.1740033893.0.0.0; _ga_9PZ2YKK2F0=GS1.1.1740033532.1.1.1740033893.0.0.0; _ga_KNR5JKBZGP=GS1.1.1740033532.1.1.1740033893.0.0.0; _ga_GB6YGTY5MT=GS1.1.1740033532.1.1.1740033893.0.0.0"
              }
    web = xbmcaddon.Addon().getSetting('saoke_url')
    temp = requests.get(web).text
    url = re.search(r'web:\["(.*?)"', temp).group(1)
    api = url+'/'+link+'.html'
    data_match = requests.get(url=api, headers=headers).text
    stream_match = re.search(r"cache:'(.*?)',", data_match).group(1)
    if stream_match:
        data_list = json.loads(stream_match)
        for item in data_list:
            if item['name']:
                logo = os.path.join(ADDON_PATH, 'icon.saoke.png')
                name = item['name']
                match = item['url']+'|Referer=https://sk.mediastation.live/'
                fanart = ""
                desc = "Link: "+item['name']
                list_item = xbmcgui.ListItem(name)
                list_item.setArt({'thumb': logo, 'poster': logo, 'banner': logo, 'icon': logo, 'fanart': fanart})
                list_item.setInfo(type='video', infoLabels={'title': name,'sorttitle': name,'plot': desc})
                list_item.setProperty("IsPlayable", 'true')
                xbmcplugin.addDirectoryItem(HANDLE, match, list_item, isFolder=False)
        xbmcplugin.endOfDirectory(HANDLE)

def list_luongson():
    headers = {
              "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
              'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
              'Accept-Language': 'vi-VN,vi;q=0.8,en-US;q=0.5,en;q=0.3'
              }
    api = 'https://api-ls.cdnokvip.com/api/get-livestream-group'
    data_match = requests.get(url=api, headers=headers).json()
    for item in data_match['value']['datas']:
        time = datetime.datetime.fromtimestamp(item['matchTime']).strftime('%Hh%M-%d/%m')
        time_h = datetime.datetime.fromtimestamp(item['matchTime']).strftime('%Hh%M')
        blv = '|BLV: ' + item['commentator']
        if not item['commentator']:
            blv = ''
        name = time+": "+item['homeName']+" vs "+item['awayName']+blv
        if item['status'] == 3:
            name = "PHÁT LẠI: "+time_h+' '+item['homeName']+" vs "+item['awayName']
        match = item['matchId']
        logo = os.path.join(ADDON_PATH, 'icon.luongson.png')
        fanart = ""
        desc = item['leagueName']
        list_item = xbmcgui.ListItem(name)
        list_item.setArt({'thumb': logo, 'poster': logo, 'banner': logo, 'icon': logo, 'fanart': fanart})
        list_item.setInfo(type='video', infoLabels={'title': name,'sorttitle': name,'plot': desc})
        list_item.setProperty("IsPlayable", 'false')
        url = get_url(action='luongson', link=match)
        xbmcplugin.addDirectoryItem(HANDLE, url, list_item, isFolder=True)
    xbmcplugin.endOfDirectory(HANDLE)

def list_link_luongson(link):
    reff = 'https://ls39.live/'
    origin = 'https://ls39.live'
    ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
    headers = {
              "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
              'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
              'Accept-Language': 'vi-VN,vi;q=0.8,en-US;q=0.5,en;q=0.3',
              'Referer': reff
              }
    url = 'https://api-ls.cdnokvip.com/api/match-detail?matchId=' + link
    data = requests.post(url=url, headers=headers, verify=False).json()
    if data:
        logo = os.path.join(ADDON_PATH, 'icon.luongson.png')
        name = data['value']['datas']['homeName']+' vs '+data['value']['datas']['awayName']+' | '+data['value']['datas']['commentator']
        match = data['value']['datas']['linkLive']
        fanart = ""
        desc = data['value']['datas']['leagueName']
        list_item = xbmcgui.ListItem(name)
        list_item.setArt({'thumb': logo, 'poster': logo, 'banner': logo, 'icon': logo, 'fanart': fanart})
        list_item.setInfo(type='video', infoLabels={'title': name,'sorttitle': name,'plot': desc})
        list_item.setProperty("IsPlayable", 'true')
        list_item.setProperty("inputstream", "inputstream.adaptive")
        list_item.setProperty("inputstream.adaptive.manifest_type", "hls")
        list_item.setPath(match)
        xbmcplugin.addDirectoryItem(handle=HANDLE, url=match, listitem=list_item, isFolder=False)
    xbmcplugin.endOfDirectory(HANDLE)

def add_hours(time_str, add_h):
    try:
        h, m = time_str.split(":")
        h = int(h)
        m = int(m)
        h = (h + int(add_h)) % 24
        return "%02d:%02d" % (h, m)
    except Exception:
        return time_str

def js_unpack_packer(source: str) -> str:
    pattern = re.compile(
        r"eval\(function\(p,a,c,k,e,(?:r|d)\)\{.*?\}\((?P<p>.+?),(?P<a>\d+),(?P<c>\d+),'(?P<k>.+?)'\.split\('\|'\)",
        re.DOTALL
    )

    m = pattern.search(source)
    if not m:
        return source  # Không phải packer → trả nguyên
    payload = m.group("p")
    base = int(m.group("a"))
    count = int(m.group("c"))
    symtab = m.group("k").split("|")

    def baseN(num, b):
        chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        s = ""
        while num:
            s = chars[num % b] + s
            num //= b
        return s or "0"

    for i in range(count):
        if i < len(symtab) and symtab[i]:
            key = baseN(i, base)
            payload = re.sub(rf"\b{key}\b", symtab[i], payload)

    payload = payload.strip()
    if payload.startswith("'") and payload.endswith("'"):
        payload = payload[1:-1]

    return payload

def list_spo():
    headers = {
              "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
              'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
              'Accept-Language': 'vi-VN,vi;q=0.8,en-US;q=0.5,en;q=0.3'
              }
    web = xbmcaddon.Addon().getSetting('spo_url')
    api = web+'favicon.ico'
    text = requests.get(api, verify=False).text
    text = text.encode('latin1').decode('utf-8')
    pattern = r'(\d{1,2}[:.]\d{2})\s+(.*?)\s+\|\s+(https?://[^\s]+)'
    data_match = re.findall(pattern, text)
    for item in data_match:
        time_new = add_hours(item[0], 7)
        channels = re.search(r'/([^/]+)\.php', item[2]).group(1)
        name = time_new + " " + item[1]+' ('+channels+')'
        match = item[2]
        logo = ''
        fanart = ""
        desc = item[1]+"\n"+'('+channels+')'
        list_item = xbmcgui.ListItem(name)
        list_item.setArt({'thumb': logo, 'poster': logo, 'banner': logo, 'icon': logo, 'fanart': fanart})
        list_item.setInfo(type='video', infoLabels={'title': name,'sorttitle': name,'plot': desc})
        list_item.setProperty("IsPlayable", 'true')
        url = get_url(action='spo', link=match)
        xbmcplugin.addDirectoryItem(HANDLE, url, list_item, isFolder=False)
    xbmcplugin.endOfDirectory(HANDLE)

def list_link_spo(link):
    headers = {
              "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
              'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
              'Accept-Language': 'vi-VN,vi;q=0.8,en-US;q=0.5,en;q=0.3',
              'Referer': link
              }
    data0 = requests.get(link, headers=headers, verify=False).text
    link0 = re.findall(r'<iframe[^>]*\s+src="([^"]+)"', data0, re.IGNORECASE)
    data1 = requests.get('https:'+link0[0], headers=headers, verify=False).text
    link1 = re.findall(r'<script\b[^>]*>\s*(eval\(function.*?\))\s*<\/script>', data1, re.IGNORECASE | re.DOTALL)
    jsDec = js_unpack_packer(link1[1])
    matches2 = re.findall(r'src="(.*?)"', jsDec)
    list_item = xbmcgui.ListItem('PlayStream', path=matches2[0]+'|Referer='+'https:'+link0[0])
    xbmcplugin.setResolvedUrl(HANDLE, True, list_item)


def play_replay(link):
    headers = {
              "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
              'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
              'Accept-Language': 'vi-VN,vi;q=0.8,en-US;q=0.5,en;q=0.3',
              'referer': 'https://t5c2.bdhub.link/'
              }
    api = 'https://t5c2.bdhub.link'+urllib.parse.unquote(link)
    data_match = requests.get(url=api, headers=headers).text
    play = re.search(r'link=(.*?)&amp;', data_match)
    match = urllib.parse.unquote(play.group(1))
    list_item = xbmcgui.ListItem('PlayStream', path=match)
    xbmcplugin.setResolvedUrl(HANDLE, True, list_item)


def router(string):
    params = dict(parse_qsl(string))
    if not params:
        list_menu(menu)
    elif params['action'] == 'list_type':
        if params['link'] == 'spo':
            list_spo()
        elif params['link'] == 'thapcam':
            list_thapcam()
        elif params['link'] == 'cakhia':
            list_cakhia()
        elif params['link'] == 'luongson':
            list_luongson()
        elif params['link'] == 'saoke':
            list_saoke()
        elif params['link'] == 'highlights':
            list_highlights()
        elif params['link'] == 'replay':
        	list_replay()

    elif params['action'] == 'spo':
        list_link_spo(params['link'])
    elif params['action'] == 'thapcam':
        list_link_thapcam(params['link'])
    elif params['action'] == 'cakhia':
        list_link_cakhia(params['link'])
    elif params['action'] == 'luongson':
        list_link_luongson(params['link'])
    elif params['action'] == 'saoke':
        list_link_saoke(params['link'])
    elif params['action'] == 'replay':
        list_link_replay(params['link'])
    elif params['action'] == 'play_replay':
    	play_replay(params['link'])
    elif params['action'] == 'highlights':
        play_highlights(params['link'])


    else:
        raise ValueError(f'Invalid paramstring: {string}!')

if __name__ == '__main__':
    router(sys.argv[2][1:])