import xbmc
import xbmcaddon
import xbmcvfs
import xbmcgui
import os
import time
import json
import urllib
import gzip
try:
    from io import StringIO # Py2
except ImportError:
    from io import BytesIO as StringIO # Py3
try:
    # Python 3
    import urllib.request as urllib2
    from urllib.parse import urlparse, quote_plus, unquote, unquote_plus
    pyv3 = True
except ImportError:
    # Python 2
    import urllib2
    from urllib import quote_plus, unquote, unquote_plus
    pyv3 = False

# --- CONFIG ---
AddonID = 'plugin.video.iptvaddons'
Addon = xbmcaddon.Addon(AddonID)
if pyv3:
    addon_data_dir = xbmcvfs.translatePath(Addon.getAddonInfo('profile'))
else:
    addon_data_dir = xbmc.translatePath(Addon.getAddonInfo('profile'))
sitesource = "https://www.ipset.in/" # Update if dynamic fetching is needed
# Note: For simplicity we assume code is known or fetched. 
# Ideally we should share code with default.py, but importing default.py runs it.
# We will use a minimal GetUrl approach.

def GetUrl(url):
    req_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                   'Accept-Encoding': 'gzip'}
    try:
        if pyv3:
            req = urllib2.Request(url, headers=req_headers)
            response = urllib2.urlopen(req)
        else:
            req = urllib2.Request(url, headers=req_headers)
            response = urllib2.urlopen(req)
            
        content = response.read()
        
        # Check for GZIP encoding
        is_gzipped = False
        if response.info().get('Content-Encoding') == 'gzip':
            is_gzipped = True
        
        # Fallback check on magic bytes
        if not is_gzipped and len(content) > 2:
            b1 = content[0]
            b2 = content[1]
            if pyv3:
                if b1 == 0x1f and b2 == 0x8b: is_gzipped = True
            else:
                if ord(b1) == 0x1f and ord(b2) == 0x8b: is_gzipped = True

        if is_gzipped:
            try:
                buf = StringIO(content) if not pyv3 else BytesIO(content) # Fix for Py3 BytesIO
                f = gzip.GzipFile(fileobj=buf)
                content = f.read()
            except:
                pass 
                # If StringIO fails in Py3, try BytesIO
                if pyv3:
                   from io import BytesIO
                   buf = BytesIO(content)
                   f = gzip.GzipFile(fileobj=buf)
                   content = f.read()

        return content
        
    except Exception as e:
        xbmc.log("IPTVAddons Service: Error downloading " + url + " - " + str(e), xbmc.LOGERROR)
        return None

def IsCacheValid(file_path, seconds=604800):
    try:
        if os.path.exists(file_path):
            if (time.time() - os.path.getmtime(file_path)) < seconds:
                return True
    except: pass
    return False

if __name__ == '__main__':
    # Wait for network
    xbmc.sleep(5000)
    
    # Check Series Cache (Weekly)
    cache_file = os.path.join(addon_data_dir, "series_json_cache.json")
    
    if not IsCacheValid(cache_file, 604800):
        xbmc.log("IPTVAddons Service: Aggiornamento Cache Serie in corso...", xbmc.LOGINFO)
        # We need the user code/credentials... 
        # Since we duplicated logic, we might miss the dynamic 'code' from settings/p.htm
        # Strategy: Read settings. But logic in default.py constructs 'code' dynamically.
        # Fallback: Just try to read 'code' from settings if available or construct minimal.
        
        # Simplified: We can't easily replicate the login flow here without code duplication.
        # Alternative: Just skip if we can't get the full URL easily?
        # Let's try to get code from settings.
        
        # Actually, let's keep it simple. If we trigger the update here, we save user wait time.
        # But we need the authentication code.
        # Assuming the standard path:
        # We will skip complicated auth logic here to avoid breakage.
        # User explicitly asked to load it at startup.
        pass
        # RESTRUCTURE: We cannot easily run this independent of default.py logic (auth).
        # We will implement a 'headless' mode in default.py instead? No, unsafe.
        
        # Let's rely on default.py caching which we just set to 1 week.
        # The 'startup' part is tricky without duplicated auth code.
        
        # However, we can invoke default.py with a special mode?
        # xbmc.executebuiltin('RunScript(plugin.video.iptvaddons, ?mode=background_update)')
        # This is safer!
        
        # Use RunPlugin to correctly invoke the plugin environment
        xbmc.executebuiltin('RunPlugin(plugin://plugin.video.iptvaddons/?mode=200)') # Mode 200 = Background Update
