# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import base64
from resources.lib.dns import customdns
from resources.lib.common import make_session, log, DEFAULT_TIMEOUT

customdns()

MASTER_URL = 'https://oneplayhd.com/listas_oneplay/master.txt'
SESSION = make_session()


def _get_text(url, timeout=DEFAULT_TIMEOUT):
    last_exc = None
    candidates = [url]
    if 'proxy.liyao.space' not in url:
        candidates.append('https://proxy.liyao.space/------{}'.format(url))
    for candidate in candidates:
        try:
            res = SESSION.get(candidate, timeout=timeout)
            if res.status_code == 200 and res.text:
                res.encoding = 'utf-8'
                return res.text
            log('M3U HTTP {} para {}'.format(res.status_code, candidate), level=2)
        except Exception as exc:
            last_exc = exc
            log('M3U falhou em {}: {}'.format(candidate, exc), level=2)
    raise Exception('Erro ao baixar recurso M3U: {}'.format(last_exc or url))


def parse_m3u(m3u_url):
    text = _get_text(m3u_url)
    channels = []
    groups = set()
    current = None

    for raw_line in text.splitlines():
        line = raw_line.strip()
        if not line:
            continue

        if line.startswith('#EXTINF'):
            try:
                group = line.split('group-title="', 1)[1].split('"', 1)[0].strip()
            except Exception:
                group = 'Outros'

            try:
                logo = line.split('tvg-logo="', 1)[1].split('"', 1)[0].strip()
            except Exception:
                logo = ''

            name = line.split(',')[-1].strip() or 'Canal'
            current = {
                'group': group or 'Outros',
                'name': name,
                'logo': logo,
                'id': base64.urlsafe_b64encode(name.encode('utf-8')).decode('ascii')
            }
            groups.add(current['group'])
        elif current and (line.startswith('http://') or line.startswith('https://')):
            current['url'] = line
            channels.append(current.copy())
            current = None

    return channels, sorted(groups)


def get_lists():
    text = _get_text(MASTER_URL)
    return [line.strip() for line in text.splitlines() if line.strip().startswith(('http://', 'https://'))]


def basename(path):
    idx = path.rfind('/') + 1
    return path[idx:]


def convert_to_m3u8(url):
    if not url:
        return url

    if '|' in url:
        url = url.split('|', 1)[0]
    elif '%7C' in url:
        url = url.split('%7C', 1)[0]

    lowered = url.lower()
    if ('.m3u8' not in lowered and '/hl' not in lowered and url.count('/') > 4 and
            '.mp4' not in lowered and '.avi' not in lowered):
        try:
            from six.moves.urllib.parse import urlparse
            parsed = urlparse(url)
            host_part = '{}://{}'.format(parsed.scheme, parsed.netloc)
            remainder = url.split(host_part, 1)[1]
            url = host_part + '/live' + remainder
            filename = basename(url)
            if filename.lower().endswith('.ts'):
                url = url[:-3] + '.m3u8'
            else:
                url = url + '.m3u8'
        except Exception as exc:
            log('convert_to_m3u8 falhou para {}: {}'.format(url, exc), level=2)
    return url
