import xbmc
import xbmcgui
import xbmcaddon
import requests
import os
import json

def get_stremio_subtitle(imdb_id, season=None, episode=None, lang="pt-br"):
    try:
        addon = xbmcaddon.Addon()
        addon_id = addon.getAddonInfo('id')
        profile_path = xbmc.translatePath(f"special://profile/addon_data/{addon_id}/subtitles")
        os.makedirs(profile_path, exist_ok=True)

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

        r = requests.get(url, timeout=10)
        if r.status_code != 200:
            xbmc.log(f"[STREMIO] API error {r.status_code}", xbmc.LOGERROR)
            return None

        data = r.json()
        if not data.get("subtitles"):
            xbmc.log(f"[STREMIO] No subtitles found for {imdb_id}", xbmc.LOGINFO)
            return None

        sub_url = data["subtitles"][0]["url"]
        sub_filename = f"{imdb_id}_{lang}.srt"
        sub_path = os.path.join(profile_path, sub_filename)

        resp = requests.get(sub_url, timeout=10)
        if resp.status_code == 200:
            with open(sub_path, "wb") as f:
                f.write(resp.content)
            xbmc.log(f"[STREMIO] Subtitle saved: {sub_path}", xbmc.LOGINFO)
            return sub_path
        else:
            xbmc.log(f"[STREMIO] Subtitle download failed: {resp.status_code}", xbmc.LOGERROR)

    except Exception as e:
        xbmc.log(f"[STREMIO] Subtitle error: {e}", xbmc.LOGERROR)
    return None
