# -*- coding: utf-8 -*-
import base64
import json
import urllib.parse

from resources.lib import proxy


_BLOCKED_HEADERS = {'host', 'connection', 'content-length', 'accept-encoding'}


def _emit(log_fn, message, level=None):
    if not log_fn:
        return
    try:
        log_fn(message, level) if level is not None else log_fn(message)
    except TypeError:
        try:
            log_fn(message)
        except Exception:
            pass
    except Exception:
        pass


def _parse_kodi_url(url):
    raw = url or ''
    clean, sep, header_blob = raw.partition('|')
    headers = {}
    if sep and header_blob:
        try:
            parsed = urllib.parse.parse_qsl(header_blob, keep_blank_values=True)
        except Exception:
            parsed = []
        for key, value in parsed:
            lk = (key or '').strip().lower()
            if not lk or lk in _BLOCKED_HEADERS:
                continue
            headers[key] = value
    return clean or raw, headers


def _encode_headers(headers):
    if not headers:
        return ''
    try:
        payload = json.dumps(headers, ensure_ascii=False, separators=(',', ':')).encode('utf-8')
        return base64.urlsafe_b64encode(payload).decode('ascii').rstrip('=')
    except Exception:
        return ''


def is_live_proxy_enabled(addon):
    try:
        return (addon.getSetting('proxy_live_enabled') or 'false').lower() == 'true'
    except Exception:
        return False


def set_live_proxy_enabled(addon, enabled, log_fn=None):
    try:
        addon.setSetting('proxy_live_enabled', 'true' if enabled else 'false')
        return True
    except Exception as exc:
        _emit(log_fn, f'Falha ao salvar estado do proxy live: {exc}')
        return False


def ensure_live_proxy_started(log_fn=None):
    try:
        return bool(proxy.start_proxy())
    except Exception as exc:
        _emit(log_fn, f'Falha ao iniciar proxy live: {exc}')
        return False


def stop_live_proxy_if_running(log_fn=None):
    try:
        return bool(getattr(proxy, 'stop_proxy', lambda: True)())
    except Exception as exc:
        _emit(log_fn, f'Falha ao desligar proxy live: {exc}')
        return False


def wrap_live_url_with_proxy(url, addon, strip_headers_fn, log_fn=None):
    raw_url = url or ''
    clean_url, headers = _parse_kodi_url(raw_url)
    clean_url = clean_url or strip_headers_fn(raw_url)
    if not clean_url:
        return clean_url or raw_url
    if clean_url.startswith('http://127.0.0.1:') and (('/hlsretry?url=' in clean_url) or ('/tsdownloader?url=' in clean_url)):
        return clean_url
    if not is_live_proxy_enabled(addon):
        return raw_url or clean_url
    if not ensure_live_proxy_started(log_fn=log_fn):
        return raw_url or clean_url
    try:
        port = int(getattr(proxy, 'PORT', 8088) or 8088)
    except Exception:
        port = 8088
    params = {'url': clean_url}
    encoded_headers = _encode_headers(headers)
    if encoded_headers:
        params['headers'] = encoded_headers
    try:
        clean_lower = (clean_url or '').lower().split('?', 1)[0].split('#', 1)[0]
        endpoint = 'tsdownloader' if clean_lower.endswith('.ts') else 'hlsretry'
        return 'http://127.0.0.1:%d/%s?%s' % (port, endpoint, urllib.parse.urlencode(params))
    except Exception as exc:
        _emit(log_fn, f'Falha ao montar URL do proxy live: {exc}')
        return raw_url or clean_url
