# -*- coding: utf-8 -*-
from __future__ import unicode_literals  # ← precisa vir logo no início no Python 2

import sys
from six import text_type, PY3

if not PY3:
    try:
        reload(sys)
        sys.setdefaultencoding('utf-8')
    except:
        pass

from six.moves.urllib.parse import urlparse, parse_qs, urlencode, parse_qsl, unquote_plus, quote
import requests
import os
import json ## NOVO: Importado para processar as respostas JSON das novas APIs

try:
    from kodi_six import xbmc, xbmcplugin, xbmcgui, xbmcaddon, xbmcvfs
except ImportError:
    import xbmc
    import xbmcplugin
    import xbmcgui
    import xbmcaddon
    import xbmcvfs

from resources.lib import tmdb, m3u, proxy
from resources.lib.dns import customdns
PORT = proxy.PORT
URL_HLSRETRY = "http://127.0.0.1:{}/hlsretry?url=".format(PORT)
URL_TS_DOWNLOADER = "http://127.0.0.1:{}/tsdownloader?url=".format(PORT)
ADDON_HANDLE = int(sys.argv[1])
BASE_URL = sys.argv[0]
ADDON = xbmcaddon.Addon()
TRANSLATE = xbmcvfs.translatePath if PY3 else xbmc.translatePath
homeDir = ADDON.getAddonInfo('path')
addonIcon = TRANSLATE(os.path.join(homeDir, 'icon.png'))
addonFanart = TRANSLATE(os.path.join(homeDir, 'fanart.jpg'))
profile = TRANSLATE(ADDON.getAddonInfo('profile'))
if not os.path.exists(profile):
    os.makedirs(profile)

## NOVO: Criar um diretório para as legendas
subtitle_dir = os.path.join(profile, 'subtitles')
if not os.path.exists(subtitle_dir):
    os.makedirs(subtitle_dir)


ONEPLAY_DESC = '''
Para trabalhar em equipe precisamos ter empatia, transparência, solidariedade e muita lealdade, esses ingredientes são necessários para o sucesso em grupo.

[B][COLOR aquamarine]Repositório Oficial ONEPLAY[/COLOR][/B]
[COLOR blue]https://oneplayhd.github.io[/COLOR]

[B][COLOR aquamarine]Grupo Oficial FACEBOOK[/COLOR][/B]
[COLOR blue]https://tinyurl.com/oneplay2019[/COLOR]

[B][COLOR aquamarine]Grupo Oficial TELEGRAM[/COLOR][/B]
[COLOR blue]http://t.me/oneplay2019[/COLOR]
    '''
_DNS_READY = False

def ensure_customdns():
    global _DNS_READY
    if _DNS_READY:
        return
    try:
        customdns()
    except:
        pass
    _DNS_READY = True

ensure_customdns()

def _setting_bool(key, default=False):
    try:
        return ADDON.getSetting(key).lower() == 'true'
    except:
        return default

def _set_setting_bool(key, value):
    try:
        ADDON.setSetting(key, 'true' if value else 'false')
    except:
        pass

def _apply_default_view_once(flag_key, view, delay_ms=40, repeat=2):
    if _setting_bool(flag_key, False):
        return
    try:
        setview(view)
    except Exception:
        return
    extra_retries = max(0, int(repeat) - 1)
    for _ in range(extra_retries):
        try:
            xbmc.sleep(delay_ms)
        except Exception:
            pass
        try:
            setview(view)
        except Exception:
            break
    _set_setting_bool(flag_key, True)

def _complete_plugin_action(succeeded=True):
    for builtin in ('Dialog.Close(busydialog)', 'Dialog.Close(busydialognocancel)'):
        try:
            xbmc.executebuiltin(builtin)
        except:
            pass
    try:
        xbmcplugin.endOfDirectory(ADDON_HANDLE, succeeded=succeeded, updateListing=False, cacheToDisc=False)
    except TypeError:
        try:
            xbmcplugin.endOfDirectory(ADDON_HANDLE, succeeded=succeeded)
        except:
            pass
    except:
        pass

def _add_settings_item(plot='Abrir as configurações do addon OnePlay.'):
    label = 'Configurações'
    icon = TRANSLATE(os.path.join(homeDir, 'resources', 'images', 'configuracoes.png'))
    li = xbmcgui.ListItem(label)
    li.setArt({'icon': icon, 'thumb': icon, 'poster': icon, 'fanart': addonFanart})
    li.setInfo('video', {'mediatype': 'video'})
    li.setInfo(type="Video", infoLabels={"Title": label, "Plot": plot})
    li.setProperty('IsPlayable', 'false')
    xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=build_url({'action': 'open_settings'}), listitem=li, isFolder=False)

def open_settings():
    opened = False
    try:
        ADDON.openSettings()
        opened = True
    except Exception:
        try:
            xbmc.executebuiltin('Addon.OpenSettings({})'.format(ADDON.getAddonInfo('id')))
            opened = True
        except Exception:
            try:
                xbmcgui.Dialog().ok('OnePlay', 'Não foi possível abrir as configurações do addon.')
            except:
                pass
    _complete_plugin_action(succeeded=opened)

def _resolve_tv_mode():
    try:
        mode = ADDON.getSetting('modocanais')
    except:
        mode = ''
    if mode == '1':
        return 0
    if mode == '2':
        return 1
    try:
        return xbmcgui.Dialog().select('Escolha uma opção', ['MODO M3U8', 'MODO TSDOWNLOADER'])
    except:
        return 0

def desc_vip():
    text = ''
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:124.0) Gecko/20100101 Firefox/124.0'
    try:
        r = requests.get('https://oneplayhd.com/download/vip/info_oneplay.txt', headers={'User-Agent': user_agent})
        text += r.content.decode('utf-8')
    except:
        pass
    return text 

try:
    class Donate_(xbmcgui.WindowDialog):
        def __init__(self):
            try:
                self.image = xbmcgui.ControlImage(440, 128, 400, 400, TRANSLATE(os.path.join(homeDir, 'resources', 'images','qrcode.png')))
                self.text = xbmcgui.ControlLabel(x=150,y=570,width=1100,height=25,label='[B][COLOR yellow]SE ESSE ADD-ON LHE AGRADA, FAÇA UMA DOAÇÃO VIA PIX ACIMA E MANTENHA ESSE SERVIÇO ATIVO[/COLOR][/B]',textColor='yellow')
                self.text2 = xbmcgui.ControlLabel(x=495,y=600,width=1000,height=25,label='[B][COLOR yellow]PRESSIONE VOLTAR PARA SAIR[/COLOR][/B]',textColor='yellow')
                self.addControl(self.image)
                self.addControl(self.text)
                self.addControl(self.text2)
            except:
                pass
except:
    pass

def setview(name):
    mode = {'Wall': '500',
            'List': '50',
            'Poster': '51',
            'Shift': '53',
            'InfoWall': '54',
            'WideList': '55',
            'Fanart': '502'
            }.get(name, '50')
    view = 'Container.SetViewMode(%s)'%mode
    xbmc.executebuiltin(view)

def _end_directory_with_view(content=None, view=None, succeeded=True, cache=True, delay_ms=40, repeat=1, default_once_key=None):
    if content:
        try:
            xbmcplugin.setContent(ADDON_HANDLE, content)
        except Exception:
            pass
    try:
        xbmcplugin.endOfDirectory(ADDON_HANDLE, succeeded=succeeded, updateListing=False, cacheToDisc=cache)
    except TypeError:
        try:
            xbmcplugin.endOfDirectory(ADDON_HANDLE, succeeded=succeeded)
        except Exception:
            pass
    except Exception:
        pass
    if view:
        if default_once_key:
            _apply_default_view_once(default_once_key, view, delay_ms=delay_ms, repeat=repeat)
        else:
            try:
                setview(view)
            except Exception:
                return
            extra_retries = max(0, int(repeat) - 1)
            for _ in range(extra_retries):
                try:
                    xbmc.sleep(delay_ms)
                except Exception:
                    pass
                try:
                    setview(view)
                except Exception:
                    break

def build_url(query):
    if PY3:
        return BASE_URL + '?' + urlencode(query, encoding='utf-8')
    else:
        try:
            query = {k: (v.encode('utf-8') if isinstance(v, unicode) else v) for k, v in query.items()}
        except NameError:
            pass
        return BASE_URL + '?' + urlencode(query)

def home():
    items = [('[COLOR aquamarine]:::[/COLOR]BEM-VINDOS AO ONEPLAY[COLOR aquamarine]:::[/COLOR]', ONEPLAY_DESC, addonIcon, {'action': ''}),
             ('Pesquisar', 'Buscar filmes e séries pelo nome do conteúdo.', TRANSLATE(os.path.join(homeDir, 'resources','images','pesquisar.png')), {'action': 'search'}),
             ('TV', 'Entrar nas listas e categorias de canais ao vivo.', TRANSLATE(os.path.join(homeDir, 'resources','images','tv.png')), {'action': 'tv'}),
             ('Filmes', 'Explorar filmes em alta, top avaliados e lançamentos.', TRANSLATE(os.path.join(homeDir, 'resources','images','filmes.png')), {'action': 'menu_movies'}),
             ('Séries', 'Explorar séries em alta e top avaliadas.', TRANSLATE(os.path.join(homeDir, 'resources','images','series.png')), {'action': 'menu_series'}),
             ('Configurações', 'Abrir as configurações do addon OnePlay.', TRANSLATE(os.path.join(homeDir, 'resources','images','configuracoes.png')), {'action': 'open_settings'})]

    if _setting_bool('exibirvip', True):
        items.insert(1, ('VIP', desc_vip(), TRANSLATE(os.path.join(homeDir, 'resources', 'images','vip.png')), {'action': ''}))

    for label, description, icon, query in items:
        if label == 'VIP':
            url = 'plugin://plugin.video.oneplayvip/'
        else:
            url = build_url(query)
        li = xbmcgui.ListItem(label)
        li.setArt({'icon': icon, 'thumb': icon, 'poster': icon, 'fanart': addonFanart})
        li.setInfo('video', {'mediatype': 'video'})
        li.setInfo(type="Video", infoLabels={"Title": label, "Plot": description})
        if label == 'Configurações':
            li.setProperty('IsPlayable', 'false')
        xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=url, listitem=li, isFolder=(label != 'Configurações'))

    _end_directory_with_view(content='movies', view='List', delay_ms=40, repeat=2, default_once_key='default_view_home_list_applied')

# --- As funções de TV (m3u, proxy, etc) não foram alteradas ---
def menu_tv():
    options = m3u.get_lists()
    for index, option in enumerate(options):
        name = 'LISTA {}'.format(index + 1)
        icon = TRANSLATE(os.path.join(homeDir, 'resources','images','tv.png'))
        url = build_url({'action': 'openm3u', 'url': option})
        li = xbmcgui.ListItem(name)
        li.setInfo('video', {'mediatype': 'video'})
        li.setInfo(type="Video", infoLabels={"Title": name, "Plot": 'Abrir a {} de canais ao vivo.'.format(name.lower())})
        li.setArt({'icon': icon, 'thumb': icon, 'poster': icon, 'fanart': addonFanart})
        xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=url, listitem=li, isFolder=True)

    _add_settings_item()
    _end_directory_with_view(content='movies', view='List', delay_ms=40, repeat=2, default_once_key='default_view_tv_list_applied')

def openm3u(params):
    url = params.get('url')
    if not url:
        xbmcgui.Dialog().ok('Kodi', 'URL da lista M3U inválida.')
        return
    try:
        channels, groups = m3u.parse_m3u(url)
        if not groups:
            xbmcgui.Dialog().ok('Kodi', 'Nenhum grupo encontrado na lista.')
            return
        for group in groups:
            url_ = build_url({'action': 'opengroup', 'url': url, 'group': group})
            icon = TRANSLATE(os.path.join(homeDir, 'resources', 'images', 'tv.png'))
            li = xbmcgui.ListItem(group)
            li.setInfo('video', {'title': group, 'mediatype': 'video'})
            li.setInfo(type="Video", infoLabels={"Title": group, "Plot": 'Abrir a categoria {} de canais.'.format(group)})
            li.setArt({'icon': icon, 'thumb': icon, 'poster': icon, 'fanart': addonFanart})
            xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=url_, listitem=li, isFolder=True)
        _end_directory_with_view(content='movies', view='List', delay_ms=40, repeat=2, default_once_key='default_view_tv_list_applied')
    except Exception as e:
        xbmcgui.Dialog().ok('Kodi', 'Erro ao processar a lista M3U.')

def opengroup(params):   
    url = params.get('url')
    group = params.get('group')
    if group:
        try:
            group = group.decode('utf-8')
        except:
            pass
    if not url:
        xbmcgui.Dialog().ok('Kodi', 'URL da lista M3U inválida.')
        return
    try:
        channels, groups = m3u.parse_m3u(url)
        if not channels:
            xbmcgui.Dialog().ok('Kodi', 'Nenhum canal encontrado na lista.')
            return
        channel_filter = [channel for channel in channels if channel['group'] == group]
        for channel in channel_filter:
            url_ = build_url({'action': 'play_proxy', 'name': channel['name'], 'url': channel['url'], 'icon': channel['logo']})
            li = xbmcgui.ListItem(channel['name'])
            li.setInfo('video', {'title': channel['name'], 'mediatype': 'video'})
            li.setInfo(type="Video", infoLabels={"Title": channel['name'], "Plot": 'Abrir o canal para reprodução.'})
            li.setArt({'icon': channel['logo'], 'thumb': channel['logo'], 'poster': channel['logo'], 'fanart': addonFanart})
            li.setProperty('IsPlayable', 'false')
            xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=url_, listitem=li, isFolder=False)
        _end_directory_with_view(content='movies', view='List', delay_ms=40, repeat=2, default_once_key='default_view_tv_list_applied')
    except Exception as e:
        xbmcgui.Dialog().ok('Kodi', 'Erro ao processar a lista M3U.')

def play_proxy(params):
    url = params.get('url')
    if not url:
        xbmcgui.Dialog().ok('Kodi', 'URL inválida.')
        return
    op = _resolve_tv_mode()
    if op == 0:
        name = params.get('name', 'Canal') + ' (M3U8)'
        url = unquote_plus(url)
        url = url.split('|')[0] if '|' in url else url
        url = m3u.convert_to_m3u8(url)
        url = URL_HLSRETRY + quote(url)
    elif op == 1:
        name = params.get('name', 'Canal') + ' (TS)'
        url = unquote_plus(url)
        url = url.replace('live/', '').replace('.m3u8', '')
        url = URL_TS_DOWNLOADER + quote(url)
    else:
        return
    proxy.kodiproxy()
    li=xbmcgui.ListItem(name)
    li.setInfo('video', {'title': name, 'mediatype': 'video'})
    li.setArt({'icon': params.get('icon', ''), 'thumb': params.get('icon', ''), 'poster': params.get('icon', ''), 'fanart': addonFanart})
    xbmc.Player().play(item=url, listitem=li)

# --- Funções de Filmes e Séries (navegação) não foram alteradas ---
def menu_movies():  
    items = [
        ('Filmes - Em Alta', 'Ver os filmes que estão bombando no momento.', {'action': 'list', 'type': 'movie', 'category': 'trending'}),
        ('Filmes - Top Avaliados', 'Ver os filmes com melhor avaliação nas fontes.', {'action': 'list', 'type': 'movie', 'category': 'top'}),
        ('Filmes - Lançamentos', 'Ver os filmes lançados mais recentemente.', {'action': 'list', 'type': 'movie', 'category': 'latest'}),
    ]
    for label, description, query in items:
        url = build_url(query)
        icon = TRANSLATE(os.path.join(homeDir, 'resources','images','filmes.png'))
        li = xbmcgui.ListItem(label)
        li.setInfo('video', {'mediatype': 'video'})
        li.setInfo(type="Video", infoLabels={"Title": label, "Plot": description})
        li.setArt({'icon': icon, 'thumb': icon, 'poster': icon, 'fanart': addonFanart})
        xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=url, listitem=li, isFolder=True)
    xbmcplugin.endOfDirectory(ADDON_HANDLE)
    xbmcplugin.setContent(ADDON_HANDLE, 'movies')
    setview('List')      

def menu_series():  
    items = [
        ('Séries - Em Alta', 'Ver as séries que estão em destaque agora.', {'action': 'list', 'type': 'series', 'category': 'trending'}),
        ('Séries - Top Avaliados', 'Ver as séries com melhor avaliação nas fontes.', {'action': 'list', 'type': 'series', 'category': 'top'}),
    ]    
    for label, description, query in items:
        url = build_url(query)
        icon = TRANSLATE(os.path.join(homeDir, 'resources','images','series.png'))
        li = xbmcgui.ListItem(label)
        li.setInfo('video', {'mediatype': 'video'})
        li.setInfo(type="Video", infoLabels={"Title": label, "Plot": description})
        li.setArt({'icon': icon, 'thumb': icon, 'poster': icon, 'fanart': addonFanart})
        xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=url, listitem=li, isFolder=True)
    xbmcplugin.endOfDirectory(ADDON_HANDLE) 
    xbmcplugin.setContent(ADDON_HANDLE, 'movies') 
    setview('List')            

def list_items(params):  
    # ... (sem alterações aqui)
    next_button = False
    page = int(params.get('page', '1'))
    items = tmdb.get_items(params.get('type'), params.get('category'), page)
    if items:
        next_button = True

    for item in items:
        title = '{} ({})'.format(item['title'], item['year']) if item['year'] else item['title']
        fanart = item['background'] if item.get('background') else ''
        url = build_url({'action': 'details', 'type': params.get('type'), 'id': item['id'], 'name': item['title'], 'year': item['year'], 'fanart': fanart})
        li = xbmcgui.ListItem(title)
        if item.get('poster') or item.get('background'):
            li.setArt({
                'thumb': item['poster'] if item.get('poster') else None,
                'icon': item['poster'] if item.get('poster') else None,
                'poster': item['poster'] if item.get('poster') else None,
                'fanart': item['background'] if item.get('background') else None
            })
        li.setInfo('video', {'title': title, 'plot': item.get('description', ''), 'year': int(item['year']) if item['year'] else 0})
        li.setInfo('video', {'mediatype': 'video'})
        xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=url, listitem=li, isFolder=True)

    next_page_url = build_url({
        'action': 'list',
        'type': params.get('type'),
        'category': params.get('category'),
        'page': str(page + 1)
    })
    if next_button:
        next_li = xbmcgui.ListItem('[Próxima Página]')
        icon = TRANSLATE(os.path.join(homeDir, 'resources','images','proximo.png'))
        next_li.setArt({'icon': icon, 'thumb': icon, 'poster': icon, 'fanart': addonFanart})
        next_li.setInfo('video', {'mediatype': 'video'})
        xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=next_page_url, listitem=next_li, isFolder=True)

    xbmcplugin.endOfDirectory(ADDON_HANDLE)
    xbmcplugin.setContent(ADDON_HANDLE, 'movies')
    setview('List')      

def list_seasons(params):
    # ... (sem alterações aqui)
    tmdb_id = params['id']
    seasons = tmdb.get_seasons(params['type'], tmdb_id)

    for season in seasons:
        name = season['name']
        url = build_url({
            'action': 'list_episodes',
            'type': params['type'],
            'id': tmdb_id,
            'season_number': str(season['season_number']),
            'poster': params['poster'],
            'name': params['name'],
            'year': params['year']
        })
        li = xbmcgui.ListItem(name)
        if season.get('poster'):
            li.setArt({'thumb': season['poster'], 'icon': season['poster'], 'poster': season['poster']})
        li.setInfo('video', {'title': name, 'plot': season.get('description', ''), 'year': int(season['year']) if season['year'] else 0})
        li.setInfo('video', {'mediatype': 'video'})
        xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=url, listitem=li, isFolder=True)

    xbmcplugin.endOfDirectory(ADDON_HANDLE)
    xbmcplugin.setContent(ADDON_HANDLE, 'movies')
    setview('List')      

def list_episodes(params):
    # ... (sem alterações aqui, exceto a action no build_url)
    tmdb_id = params['id']
    season_number = params['season_number']
    episodes = tmdb.get_episodes(params['type'], tmdb_id, season_number)

    for episode in episodes:
        name = '{} - S{}E{}'.format(params['name'], season_number.zfill(2), str(episode['episode_number']).zfill(2))
        url = build_url({
            'action': 'list_streams', ## MODIFICADO: de 'audio' para 'list_streams'
            'type': params['type'],
            'id': tmdb_id,
            'season_number': season_number,
            'episode_number': str(episode['episode_number']),
            'name': params['name'],
            'poster': params['poster'],
            'year': params['year'],
            'fanart': params.get('fanart', '')
        })
        li = xbmcgui.ListItem(name)
        if episode.get('poster'):
            li.setArt({'thumb': episode['poster'], 'icon': episode['poster'], 'poster': episode['poster']})
        li.setInfo('video', {'title': name, 'plot': episode.get('description', ''), 'year': int(episode['year']) if episode['year'] else 0})
        li.setInfo('video', {'mediatype': 'video'})
        xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=url, listitem=li, isFolder=True)

    xbmcplugin.endOfDirectory(ADDON_HANDLE)
    xbmcplugin.setContent(ADDON_HANDLE, 'movies')
    setview('List')    

## MODIFICADO: A função 'audio_options' foi renomeada e completamente reescrita
def list_streams(params):    
    type_ = params['type']
    id_ = params['id']
    imdb_id = tmdb.get_imdb_id_tmdb(id_, type_)

    if not imdb_id:
        xbmcgui.Dialog().ok("Erro", "Não foi possível encontrar o ID do IMDB para este item.")
        return

    if type_ == 'series':
        url_nuvio = 'https://nuviostreams.hayd.uk/stream/series/{}:{}:{}.json'.format(imdb_id, params['season_number'], params['episode_number'])
    else: # movie
        url_nuvio = 'https://nuviostreams.hayd.uk/stream/movie/{}.json'.format(imdb_id)

    #if type_ == 'series':
    #    url_skyflix = 'https://skyflix.onrender.com/stream/series/{}:{}:{}.json'.format(imdb_id, params['season_number'], params['episode_number'])
    if not type_ == 'series': # movie
        url_skyflix = 'https://skyflix.onrender.com/stream/movie/{}.json'.format(imdb_id)        
    
    # nuvio
    try:
        r = requests.get(url_nuvio, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36'})
        r.raise_for_status() # Lança um erro se a requisição falhar
        data = r.json()
    except requests.exceptions.RequestException as e:
        xbmc.log("Erro ao buscar streams: {}".format(e), level=xbmc.LOGERROR)
        xbmcgui.Dialog().ok("Erro", "Não foi possível obter a lista de streams. A fonte pode estar offline.")
        return
    # skyflix
    # try:
    #     r2 = requests.get(url_skyflix, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36'})
    #     r2.raise_for_status() # Lança um erro se a requisição falhar
    #     data2 = r2.json()
    # except requests.exceptions.RequestException as e:
    #     xbmc.log("Erro ao buscar streams: {}".format(e), level=xbmc.LOGERROR)
    #     #xbmcgui.Dialog().ok("Erro", "Não foi possível obter a lista de streams. A fonte pode estar offline.")
    #     data2 = {}
        
    # if data2.get('streams'):
    #     streams = data.get('streams', []) + data2.get('streams', [])
    # else:
    streams = data.get('streams', [])
    if not streams:
        xbmcgui.Dialog().ok("Sem Fontes", "Nenhum stream foi encontrado para este conteúdo.")
        return

    # streams_ordenado = sorted(
    # streams,
    # key=lambda x: 0 if "- Auto" in x["name"] else 1
    # )
    streams.sort(
        key=lambda x: 
            0 if "- Auto" in x["name"] else 
            1 if "- Dublado" in x.get('description', '') else 
            2
    )    

    for stream in streams:
        # filtrar streams validos
        #if 'showbox' in stream.get('name', '').lower() or '- 4k' in stream.get('name', '').lower():
        if 'showbox' in stream.get('name', '').lower():
            continue
        # O campo 'title' da API nuviostreams é muito descritivo
        stream_title = stream.get('title', stream.get('description', '')).replace('\n', ' ').replace('\t', '').replace('SKYFLIX API', 'OnePlay API').strip()
        stream_url = stream.get('url')

        if not stream_url:
            continue

        if 'pixeldrain.dev' in stream_url or 'hindi' in stream_url.lower():
            continue 

        if 'beta' in stream_url and '.top' in stream_url:
            continue

        if 'hindi' in stream_title.lower():
            continue     

        # detect type
        if '- 4k' in stream.get('name', '').lower():
            name_type = '[B][COLOR orange](4K)[/COLOR][/B]'
        elif '1080p' in stream.get('name', '').lower():
            name_type = '[B][COLOR gold](1080p)[/COLOR][/B]'
        elif '720p' in stream.get('name', '').lower():
            name_type = '[B][COLOR deepskyblue](720p)[/COLOR][/B]'
        elif 'Dublado' in stream.get('description', ''):
            name_type = '[B][COLOR yellow](Dublado)[/COLOR][/B]'
        else:
            name_type = '[B][COLOR lime](Auto)[/COLOR][/B]'

        if type_ == 'series':
            if name_type:
                item_name = '{} - S{}E{} {} ({})'.format(params['name'],params['season_number'].zfill(2), params['episode_number'].zfill(2), name_type,stream_title)
            else:
                item_name = '{} - S{}E{} ({})'.format(params['name'], params['season_number'].zfill(2), params['episode_number'].zfill(2), stream_title)
        else:
            if name_type:
                item_name = '{} ({}) {} - {}'.format(params['name'], params['year'], name_type, stream_title)
            else:
                item_name = '{} ({}) - {}'.format(params['name'], params['year'], stream_title)

        # Prepara os parâmetros para a próxima ação (play_item_with_subtitles)
        play_params = {
            'action': 'play_item_with_subtitles',
            'video_url': stream_url,
            'imdb_id': imdb_id,
            'type': type_,
            'name': item_name,
            'poster': params['poster'],
            'fanart': params.get('fanart', '')
        }
        if type_ == 'series':
            play_params['season'] = params['season_number']
            play_params['episode'] = params['episode_number']

        url_to_play = build_url(play_params)
        
        li = xbmcgui.ListItem(item_name)
        li.setArt({'thumb': params['poster'], 'icon': params['poster'], 'fanart': params.get('fanart', '')})
        li.setInfo('video', {'title': item_name, 'plot': stream_title})
        li.setProperty('IsPlayable', 'true') # Importante: Kodi precisa saber que é um item reproduzível
        li.setInfo('video', {'mediatype': 'video'})
        xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=url_to_play, listitem=li, isFolder=False)
        
    xbmcplugin.endOfDirectory(ADDON_HANDLE)
    xbmcplugin.setContent(ADDON_HANDLE, 'videos')
    setview('WideList')

## NOVO: Função para buscar e baixar as legendas
def get_and_download_subtitles(imdb_id, type_, season=None, episode=None):
    if type_ == 'series':
        sub_api_url = 'https://opensubtitles.stremio.homes/pt-br/ai-translated=false%7Cfrom=all%7CCauto-adjustment=true/subtitles/series/{}:{}:{}.json'.format(imdb_id, season, episode)
    else: # movie
        sub_api_url = 'https://opensubtitles.stremio.homes/pt-br/ai-translated=false%7Cfrom=all%7CCauto-adjustment=true/subtitles/movie/{}.json'.format(imdb_id)
        
    local_sub_paths = []
    
    # Limpa o diretório de legendas antigas para não acumular lixo
    for f in os.listdir(subtitle_dir):
        os.remove(os.path.join(subtitle_dir, f))
        
    try:
        r = requests.get(sub_api_url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36'}, timeout=10)
        r.raise_for_status()
        sub_data = r.json()
        subtitles = sub_data.get('subtitles', [])
        
        if not subtitles:
            xbmc.log("Nenhuma legenda encontrada na API para {}".format(imdb_id), level=xbmc.LOGINFO)
            return []

        for i, sub in enumerate(subtitles):
            sub_url = sub.get('url')
            if not sub_url:
                continue
            
            try:
                # Baixa a legenda
                sub_content = requests.get(sub_url, timeout=10).content
                # Salva o arquivo localmente com um nome único
                subtitle_path = os.path.join(subtitle_dir, 'sub_{}.vtt'.format(i))
                with open(subtitle_path, 'wb') as f:
                    f.write(sub_content)
                local_sub_paths.append(subtitle_path)
            except Exception as e:
                xbmc.log("Falha ao baixar/salvar legenda {}: {}".format(sub_url, e), level=xbmc.LOGWARNING)
        
        return local_sub_paths
    except Exception as e:
        xbmc.log("Erro ao buscar legendas da API: {}".format(e), level=xbmc.LOGERROR)
        return []

## NOVO: Função que resolve o item final, adiciona legendas e inicia a reprodução
def play_item_with_subtitles(params):
    video_url = params.get('video_url')
    name = params.get('name', 'Reproduzindo')
    imdb_id = params.get('imdb_id')
    type_ = params.get('type')

    dialog = xbmcgui.DialogProgress()
    dialog.create('OnePlay', 'Buscando legendas...')
    dialog.update(50)

    subtitle_paths = get_and_download_subtitles(
        imdb_id,
        type_,
        params.get('season'),
        params.get('episode')
    )
    
    dialog.close()

    li = xbmcgui.ListItem(name)
    li.setArt({'thumb': params.get('poster'), 'icon': params.get('poster'), 'fanart': params.get('fanart')})
    li.setInfo('video', {'title': name})
    li.setPath(video_url) # Define o caminho do vídeo
    
    if subtitle_paths:
        li.setSubtitles(subtitle_paths)
        xbmc.Player().setSubtitles(subtitle_paths[0]) # Tenta ativar a primeira legenda por padrão

    #xbmc.Player().play(item=video_url, listitem=li) # Forma antiga
    xbmcplugin.setResolvedUrl(handle=ADDON_HANDLE, succeeded=True, listitem=li) # Forma correta para itens "IsPlayable=true"

def show_details(params):
    meta = tmdb.get_meta(params['type'], params['id'])
    name = '{} ({})'.format(meta['name'], meta['year']) if meta['year'] else meta['name']
    if params['type'] == 'series':
        url = build_url({'action': 'list_seasons', 'type': params['type'], 'id': params['id'], 'name': meta['name'], 'poster': meta['poster'], 'year': meta['year'], 'fanart': params.get('fanart', meta['background'])})
        li = xbmcgui.ListItem(name)
        li.setInfo('video', {'title': name, 'plot': meta['description'], 'year': int(meta['year']) if meta['year'] else 0})
        li.setArt({'thumb': meta['poster'], 'poster': meta['poster'], 'fanart': meta['background']})
        li.setInfo('video', {'mediatype': 'video'})
        xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=url, listitem=li, isFolder=True)
        xbmcplugin.endOfDirectory(ADDON_HANDLE)
        xbmcplugin.setContent(ADDON_HANDLE, 'movies')
        setview('List')
    else: # movie
        # Para filmes, vamos direto para a lista de streams
        play_params = {
            'action': 'list_streams', ## MODIFICADO: De 'audio' para 'list_streams'
            'type': params['type'],
            'id': params['id'],
            'name': meta['name'],
            'poster': meta['poster'],
            'year': meta['year'],
            'fanart': params.get('fanart', meta['background'])
        }
        list_streams(play_params)

def search(params):
    # ... (sem alterações aqui)
    if not params.get('query'):
        keyboard = xbmc.Keyboard('', 'Digite o nome')
        keyboard.doModal()
        if not keyboard.isConfirmed():
            return
        query = keyboard.getText()
        if not query:
            dialog = xbmcgui.Dialog()
            dialog.ok("Erro", "Por favor, insira um termo de busca válido.")
            return
        if isinstance(query, text_type):
            query = query.encode('utf-8') if sys.version_info[0] == 2 else query
        params = {'action': 'search', 'query': query, 'page': '1'}
        search(params)
        return

    query = params.get('query')
    if not query:
        dialog = xbmcgui.Dialog()
        dialog.ok("Erro", "Termo de busca inválido.")
        return     
    page = int(params.get('page', '1'))
    next_button = False
    for type_ in ['movie', 'series']:
        items = tmdb.search(type_, query, page)
        if items:
            next_button = True
        for item in items:
            fanart = item['background'] if item.get('background') else ''
            title = '{} ({})'.format(item['title'], item['year']) if item['year'] else item['title']
            url = build_url({'action': 'details', 'type': type_, 'id': item['id'], 'name': item['title'], 'year': item['year'], 'fanart': fanart})
            li = xbmcgui.ListItem(title)
            if item.get('poster') or item.get('background'):
                li.setArt({
                    'thumb': item['poster'] if item.get('poster') else None,
                    'poster': item['poster'] if item.get('poster') else None,
                    'fanart': item['background'] if item.get('background') else None
                })
            li.setInfo('video', {'title': title, 'plot': item.get('description', ''), 'year': int(item['year']) if item['year'] else 0})
            li.setInfo('video', {'mediatype': 'video'})
            xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=url, listitem=li, isFolder=True)

    next_page_url = build_url({
        'action': 'search',
        'query': query,
        'page': str(page + 1)
    })
    if next_button:
        next_li = xbmcgui.ListItem('[Próxima Página]')
        icon = TRANSLATE(os.path.join(homeDir, 'resources','images','proximo.png'))
        next_li.setArt({'icon': icon, 'thumb': icon, 'poster': icon, 'fanart': addonFanart})
        next_li.setInfo('video', {'mediatype': 'video'})
        xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE, url=next_page_url, listitem=next_li, isFolder=True)

    xbmcplugin.endOfDirectory(ADDON_HANDLE)
    xbmcplugin.setContent(ADDON_HANDLE, 'movies')
    setview('List')     

def router(paramstring):
    params = dict(parse_qsl(paramstring, keep_blank_values=True))
    action = params.get('action')

    ## MODIFICADO: Atualização do roteador para as novas ações
    if action is None:
        home()
    elif action == 'menu_movies':
        menu_movies()
    elif action == 'tv':
        menu_tv()
    elif action == 'openm3u':
        openm3u(params)
    elif action == 'opengroup':
        opengroup(params)
    elif action == 'play_proxy':
        play_proxy(params)
    elif action == 'menu_series':
        menu_series()
    elif action == 'list':
        list_items(params)
    elif action == 'details':
        show_details(params)
    elif action == 'search':
        search(params)
    elif action == 'open_settings':
        open_settings()
    elif action == 'list_seasons':
        list_seasons(params)
    elif action == 'list_episodes':
        list_episodes(params)
    elif action == 'list_streams': # Rota antiga 'audio' agora é 'list_streams'
        list_streams(params)
    elif action == 'play_item_with_subtitles': # Rota nova para reprodução com legendas
        play_item_with_subtitles(params)
    elif action == 'donate':
        dialog_donate = Donate_()
        dialog_donate.doModal()
    else:
        home()

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