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

import os
from resources.lib.common import ensure_dir, make_session, log, DEFAULT_TIMEOUT

try:
    from kodi_six import xbmcaddon, xbmcvfs
except ImportError:
    import xbmcaddon
    import xbmcvfs

SESSION = make_session()


def get_stremio_subtitle(imdb_id, season=None, episode=None, lang="pt-br"):
    try:
        addon = xbmcaddon.Addon()
        addon_id = addon.getAddonInfo('id')
        profile_path = xbmcvfs.translatePath("special://profile/addon_data/{}/subtitles".format(addon_id))
        ensure_dir(profile_path)

        base = "https://opensubtitles.stremio.homes/{}/ai-translated=true|from=all|Cauto-adjustment=true".format(lang)
        if season and episode:
            url = "{}/subtitles/series/{}:{}:{}.json".format(base, imdb_id, season, episode)
        else:
            url = "{}/subtitles/movie/{}.json".format(base, imdb_id)

        r = SESSION.get(url, timeout=DEFAULT_TIMEOUT)
        if r.status_code != 200:
            log('[STREMIO] API error {}'.format(r.status_code), level=4)
            return None

        data = r.json()
        subtitles = data.get("subtitles") or []
        if not subtitles:
            log('[STREMIO] No subtitles found for {}'.format(imdb_id))
            return None

        sub_url = subtitles[0].get("url")
        if not sub_url:
            return None

        sub_filename = "{}_{}.srt".format(imdb_id, lang)
        sub_path = os.path.join(profile_path, sub_filename)

        resp = SESSION.get(sub_url, timeout=DEFAULT_TIMEOUT)
        if resp.status_code == 200:
            with open(sub_path, "wb") as fh:
                fh.write(resp.content)
            log('[STREMIO] Subtitle saved: {}'.format(sub_path))
            return sub_path

        log('[STREMIO] Subtitle download failed: {}'.format(resp.status_code), level=4)
    except Exception as exc:
        log('[STREMIO] Subtitle error: {}'.format(exc), level=4)
    return None
