# -*- coding: utf-8 -*-
import os
import zipfile
import xbmc, xbmcvfs, xbmcgui
from io import BytesIO
import gzip

def log(module, msg):
    xbmc.log((u"### [titulky_light:%s] - %s" % (str(module), str(msg))), level=xbmc.LOGDEBUG)

def get_file_size(filename):
    """Získá velikost souboru. Pro zjednodušení nepoužívá RAR parsing."""
    try:
        return xbmcvfs.Stat(filename).st_size()
    except:
        return -1

def extract_subtitles(archive_path):
    """Rozbalí ZIP a vrátí seznam cest k titulkům. Při chybě fallback na Kodi Extract."""
    dest_dir = os.path.dirname(archive_path)
    exts = {".srt", ".sub", ".txt", ".smi", ".ssa", ".ass"}
    found_subtitles = []

    try:
        with zipfile.ZipFile(archive_path, "r") as zf:
            used_names = set()
            for i, member in enumerate(zf.namelist()):
                base = os.path.basename(member)
                if not base or base.startswith("."):
                    continue
                ext = os.path.splitext(base)[1].lower()
                if ext not in exts:
                    continue
                out_name = base
                if out_name in used_names:
                    stem, e = os.path.splitext(base)
                    out_name = "%s_%d%s" % (stem, i, e)
                used_names.add(out_name)
                out_path = os.path.join(dest_dir, out_name)
                with zf.open(member) as src, open(out_path, "wb") as dst:
                    dst.write(src.read())
                found_subtitles.append(out_path)
        if found_subtitles:
            return found_subtitles
    except Exception as e:
        log("utils", "zipfile extract failed: %s — fallback Extract" % e)

    xbmc.executebuiltin('Extract("%s")' % archive_path)
    xbmc.sleep(1000)
    try:
        extracted_files = os.listdir(dest_dir)
    except Exception:
        return found_subtitles
    for filename in extracted_files:
        if os.path.splitext(filename)[1].lower() in exts:
            found_subtitles.append(os.path.join(dest_dir, filename))
    return found_subtitles

def get_content_from_response(response):
    """Přečte obsah z HTTP odpovědi, řeší gzip a kódování."""
    content = response.read()
    response.close()

    if response.getheader('Content-Encoding') == 'gzip':
        buf = BytesIO(content)
        f = gzip.GzipFile(fileobj=buf)
        content = f.read()

    # Detekce a dekódování textu
    content_type = response.getheader('Content-Type') or ""
    if content_type.startswith("text/"):
        try:
            content = content.decode("utf-8")
        except UnicodeDecodeError:
            content = content.decode("cp1250", errors="ignore") # fallback pro titulky.com

    return content
