# -*- coding: utf-8 -*-
import xbmc, xbmcaddon, xbmcvfs
import json
import os
import sqlite3

from sqlite3 import Error
from xml.etree import ElementTree
from resources.libs.common.config import CONFIG
from resources.libs.common import logging

# Variables
amgr = 'AM Lite ERROR'
translatePath = xbmcvfs.translatePath

# Auth cache
AUTH_CACHE = {}

# Fen Light Database Paths
fenlt_settings_db = translatePath('special://profile/addon_data/plugin.video.fenlight/databases/settings.db')

# Gears Database Paths
gears_settings_db = translatePath('special://profile/addon_data/plugin.video.gears/databases/settings.db')

# Realizer json Path
chkset_realx_json = translatePath('special://profile/addon_data/plugin.video.realizerx/rdauth.json')

ORDER = ['fenlt',
         'gears',
         'fen',
         'umb',
         'pov',
         'dradis',
         'genocide',
         'coal',    # Premiumize Only
         'seren',
         'shadow',
         'ghost',
         'chains',
         'homelander',
         'nightwing',
         'absolution',
         'thecrew',
         'scrubs',
         'otaku',
         'rurl',
         'tmdbhelper',
         'trakt',
         'premx',   # Premiumize Only
         'realx',   # Real-Debrid Only
         'acctmgr']

ADDONS = {
    #FEN LIGHT
    'fenlt': {
        'name'        : 'Fen Light',
        'plugin'      : 'plugin.video.fenlight',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.fenlight'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.fenlight/resources/media/addon_icons/', 'fenlight_icon_01.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.fenlight/resources/media/', 'fenlight_fanart2.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.fenlight/databases', 'settings.db'),
        #TK
        'default_tk'  : 'trakt.token',
        'data_tk'     : [],
        #RD
        'default_rd'  : 'rd.token',
        'data_rd'     : [],
        #PM
        'default_pm'  : 'pm.token',
        'data_pm'     : [],
        #AD
        'default_ad'  : 'ad.token',
        'data_ad'     : [],
        #ED
        'default_ed'  : 'ed.token',
        'data_ed'     : [],
        #TB
        'default_tb'  : 'tb.token',
        'data_tb'     : [],
        #EN
        'default_en'  : 'easynews_password',
        'data_en'     : [],
    },

    #GEARS
    'gears': {
        'name'        : 'Gears',
        'plugin'      : 'plugin.video.gears',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.gears'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.gears/resources/media/addon_icons/', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.gears/', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.gears', 'settings.db'),
        #TK
        'default_tk'  : 'trakt.token',
        'data_tk'     : [],
        #RD
        'default_rd'  : 'rd.token',
        'data_rd'     : [],
        #PM
        'default_pm'  : 'pm.token',
        'data_pm'     : [],
        #AD
        'default_ad'  : 'ad.token',
        'data_ad'     : [],
        #ED
        'default_ed'  : 'ed.token',
        'data_ed'     : [],
        #TB
        'default_tb'  : 'tb.token',
        'data_tb'     : [],
        #OC
        #'default_oc'  : 'oc.token',
        #'data_oc'     : [],
        #EN
        'default_en'  : 'easynews_password',
        'data_en'     : [],
    },

    #UMBRELLA
    'umb': {
        'name'        : 'Umbrella',
        'plugin'      : 'plugin.video.umbrella',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.umbrella'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.umbrella', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.umbrella', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.umbrella', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt.user.token',
        'data_tk'     : ['trakt.user.token', 'trakt.user.name', 'trakt.token.expires', 'trakt.refreshtoken', 'trakt.isauthed', 'indicators', 'trakt.scrobble', 'resume.source'],
        #RD
        'default_rd'  : 'realdebridtoken',
        'data_rd'     : ['realdebridusername', 'realdebridtoken', 'realdebrid.clientid', 'realdebridsecret', 'realdebridrefresh', 'realdebrid.enable'],
        #PM
        'default_pm'  : 'premiumizetoken',
        'data_pm'     : ['premiumizeusername', 'premiumizetoken', 'premiumize.enable'],
        #AD
        'default_ad'  : 'alldebridtoken',
        'data_ad'     : ['alldebridusername', 'alldebridtoken', 'alldebrid.enable'],
        #ED
        'default_ed'  : 'easydebridtoken',
        'data_ed'     : ['easydebridtoken', 'easydebrid.enable'],
        #TB
        'default_tb'  : 'torboxtoken',
        'data_tb'     : ['torboxtoken', 'torbox.username', 'torbox.enable'],
        #OC
        #'default_oc'  : 'offcloudtoken',
        #'data_oc'     : ['offcloudtoken', 'offcloud.enable', 'offcloud.username'],
        #EN
        'default_en'  : 'easynews.password',
        'data_en'     : ['easynews.password', 'easynews.user', 'easynews.enable'],
    },

    #FEN
    'fen': {
        'name'        : 'Fen',
        'plugin'      : 'plugin.video.fen',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.fen'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.fen/resources/media/', 'fen_icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.fen/resources/media/', 'fen_fanart.png'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.fen', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt.token',
        'data_tk'     : ['trakt.refresh', 'trakt.expires', 'trakt.token', 'trakt.user', 'trakt.indicators_active', 'watched_indicators'],
        #RD
        'default_rd'  : 'rd.token',
        'data_rd'     : ['rd.client_id', 'rd.refresh', 'rd.secret', 'rd.token', 'rd.account_id', 'rd.enabled'],
        #PM
        'default_pm'  : 'pm.token',
        'data_pm'     : ['pm.token', 'pm.account_id', 'pm.enabled'],
        #AD
        'default_ad'  : 'ad.token',
        'data_ad'     : ['ad.token', 'ad.enabled', 'ad.account_id'],
        #EN
        'default_en'  : 'easynews_password',
        'data_en'     : ['easynews_password', 'easynews_user', 'provider.easynews'],
    },

    #POV
    'pov': {
        'name'        : 'POV',
        'plugin'      : 'plugin.video.pov',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.pov'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.pov', 'pov.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.pov', 'pov_fanart.png'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.pov', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt.token',
        'data_tk'     : ['trakt.refresh', 'trakt.expires', 'trakt.token', 'trakt_user', 'trakt.client_id', 'trakt.client_secret', 'trakt_indicators_active', 'watched_indicators'],
        #RD
        'default_rd'  : 'rd.token',
        'data_rd'     : ['rd.username', 'rd.token', 'rd.client_id', 'rd.refresh', 'rd.secret', 'rd.enabled'],
        #PM
        'default_pm'  : 'pm.token',
        'data_pm'     : ['pm.account_id', 'pm.token', 'pm.enabled'],
        #AD
        'default_ad'  : 'ad.token',
        'data_ad'     : ['ad.account_id', 'ad.enabled', 'ad.token'],
        #ED
        'default_ed'  : 'eb.token',
        'data_ed'     : ['ed.token', 'ed.account_id', 'ed.enabled'],
        #TB
        'default_tb'  : 'tb.token',
        'data_tb'     : ['tb.token', 'tb.account_id', 'tb.expires', 'tb.enabled'],
        #OC
        'default_oc'  : 'oc.token',
        'data_oc'     : ['oc.token', 'oc.account_id', 'oc.enabled'],
        #EN
        'default_en'  : 'easynews_password',
        'data_en'     : ['easynews_password', 'easynews_user', 'provider.easynews'],
    },

    #DRADIS
    'dradis': {
        'name'        : 'Dradis',
        'plugin'      : 'plugin.video.dradis',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.dradis'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.dradis', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.dradis', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.dradis', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt.token',
        'data_tk'     : ['trakt.token', 'trakt.username', 'trakt.expires', 'trakt.refresh', 'trakt.isauthed', 'trakt_user', 'trakt.client_id'],
        #RD
        'default_rd'  : 'realdebrid.token',
        'data_rd'     : ['realdebrid.username', 'realdebrid.token', 'realdebrid.client_id', 'realdebrid.secret', 'realdebrid.refresh', 'realdebrid.enable'],
        #PM
        'default_pm'  : 'premiumize.token',
        'data_pm'     : ['premiumize.username', 'premiumize.token', 'premiumize.enable'],
        #AD
        'default_ad'  : 'alldebrid.token',
        'data_ad'     : ['alldebrid.username', 'alldebrid.token', 'alldebrid.enable'],
        #TB
        'default_tb'  : 'torbox.token',
        'data_tb'     : ['torbox.token', 'torbox.username', 'torbox.enable', 'torbox.expires'],
        #OC
        'default_oc'  : 'offcloud.token',
        'data_oc'     : ['offcloud.token', 'offcloud.username', 'offcloud.enable'],
        #EN
        'default_en'  : 'easynews_password',
        'data_en'     : ['easynews_password', 'easynews_user', 'provider.easynews'],
    },

    #GENOCIDE
    'genocide': {
        'name'        : 'Genocide',
        'plugin'      : 'plugin.video.genocide',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.genocide'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.genocide', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.genocide', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.genocide', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt.token',
        'data_tk'     : ['trakt.token', 'trakt.username', 'trakt.expires', 'trakt.refresh', 'trakt.isauthed', 'trakt_user', 'trakt.client_id'],
        #RD
        'default_rd'  : 'realdebrid.token',
        'data_rd'     : ['realdebrid.username', 'realdebrid.token', 'realdebrid.client_id', 'realdebrid.secret', 'realdebrid.refresh', 'realdebrid.enable'],
        #PM
        'default_pm'  : 'premiumize.token',
        'data_pm'     : ['premiumize.username', 'premiumize.token', 'premiumize.enable'],
        #AD
        'default_ad'  : 'alldebrid.token',
        'data_ad'     : ['alldebrid.username', 'alldebrid.token', 'alldebrid.enable'],
        #TB
        'default_tb'  : 'torbox.token',
        'data_tb'     : ['torbox.token', 'torbox.username', 'torbox.enable', 'torbox.expires'],
        #OC
        #'default_oc'  : 'offcloud.token',
        #'data_oc'     : ['offcloud.token', 'offcloud.username', 'offcloud.enable'],
        #EN
        'default_en'  : 'easynews_password',
        'data_en'     : ['easynews_password', 'easynews_user', 'provider.easynews'],
    },

    #THE COALITION
    'coal': {
        'name'        : 'The Coalition',
        'plugin'      : 'plugin.video.coalition',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.coalition'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.coalition', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.coalition', 'fanart.png'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.coalition', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt.token',
        'data_tk'     : ['trakt.refresh', 'trakt.expires', 'trakt.token', 'trakt_user', 'trakt_user', 'trakt.client_id', 'trakt_indicators_active', 'watched_indicators'],
        #PM
        'default_pm'  : 'pm.token',
        'data_pm'     : ['pm.account_id', 'pm.token', 'pm.enabled'],
    },

    #SEREN
    'seren': {
        'name'        : 'Seren',
        'plugin'      : 'plugin.video.seren',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.seren'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.seren/resources/images', 'ico-seren-3.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.seren/resources/images', 'fanart-seren-3.png'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.seren', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt.token',
        'data_tk'     : ['trakt.auth', 'trakt.refresh', 'trakt.username', 'trakt.expires'],
        #RD
        'default_rd'  : 'rd.auth',
        'data_rd'     : ['rd.auth', 'rd.client_id', 'rd.refresh', 'rd.secret', 'rd.username', 'realdebrid.enabled', 'realdebrid.premiumstatus'],
        #PM
        'default_pm'  : 'premiumize.token',
        'data_pm'     : ['premiumize.enabled', 'premiumize.username', 'premiumize.token', 'premiumize.premiumstatus'],
        #AD
        'default_ad'  : 'alldebrid.apikey',
        'data_ad'     : ['alldebrid.enabled', 'alldebrid.username', 'alldebrid.apikey', 'alldebrid.premiumstatus'],
    },

    #SHADOW
    'shadow': {
        'name'        : 'Shadow',
        'plugin'      : 'plugin.video.shadow',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.shadow'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.shadow', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.shadow', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.shadow', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt_access_token',
        'data_tk'     : ['trakt_expires_at', 'trakt_refresh_token', 'trakt_access_token'],
        #RD
        'default_rd'  : 'rd.auth',
        'data_rd'     : ['rd.auth', 'rd.client_id', 'rd.refresh', 'rd.secret', 'debrid_use', 'debrid_use_rd'],
        #PM
        'default_pm'  : 'premiumize.token',
        'data_pm'     : ['premiumize.token', 'debrid_use', 'debrid_use_pm'],
        #AD
        'default_ad'  : 'alldebrid.token',
        'data_ad'     : ['alldebrid.username', 'alldebrid.token', 'debrid_use_ad', 'debrid_use'],
        #TB
        'default_tb'  : 'tb.token',
        'data_tb'     : ['tb.token', 'tb.account_id'],
    },

    #GHOST
    'ghost': {
        'name'        : 'Ghost',
        'plugin'      : 'plugin.video.ghost',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.ghost'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.ghost', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.ghost', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.ghost', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt_access_token',
        'data_tk'     : ['trakt_expires_at', 'trakt_refresh_token', 'trakt_access_token'],
        #RD
        'default_rd'  : 'rd.auth',
        'data_rd'     : ['rd.auth', 'rd.client_id', 'rd.refresh', 'rd.secret', 'debrid_use', 'debrid_use_rd'],
        #PM
        'default_pm'  : 'premiumize.token',
        'data_pm'     : ['premiumize.token', 'debrid_use', 'debrid_use_pm'],
        #AD
        'default_ad'  : 'alldebrid.token',
        'data_ad'     : ['alldebrid.username', 'alldebrid.token', 'debrid_use_ad', 'debrid_use'],
        #TB
        'default_tb'  : 'tb.token',
        'data_tb'     : ['tb.token', 'tb.account_id'],
    },

    #THE CHAINS
    'chains': {
        'name'        : 'The Chains',
        'plugin'      : 'plugin.video.chains',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.chains'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.chains', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.chains', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.chains', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt_access_token',
        'data_tk'     : ['trakt_expires_at', 'trakt_refresh_token', 'trakt_access_token'],
        #RD
        'default_rd'  : 'rd.auth',
        'data_rd'     : ['rd.auth', 'rd.client_id', 'rd.refresh', 'rd.secret', 'debrid_use', 'debrid_use_rd'],
        #PM
        'default_pm'  : 'premiumize.token',
        'data_pm'     : ['premiumize.token', 'debrid_use', 'debrid_use_pm'],
        #AD
        'default_ad'  : 'alldebrid.token',
        'data_ad'     : ['alldebrid.username', 'alldebrid.token', 'debrid_use_ad', 'debrid_use'],
        #TB
        'default_tb'  : 'tb.token',
        'data_tb'     : ['tb.token', 'tb.account_id'],
    },
    
    #HOMELANDER
    'homelander': {
        'name'        : 'Homelander',
        'plugin'      : 'plugin.video.homelander',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.homelander'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.homelander', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.homelander', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.homelander', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt.token',
        'data_tk'     : ['trakt.authed', 'trakt.user', 'trakt.token', 'trakt.refresh', 'trakt.client_id', 'trakt.client_secret'],
    },

    #NIGHTWING
    'nightwing': {
        'name'        : 'Nightwing',
        'plugin'      : 'plugin.video.nightwing',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.nightwing'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.nightwing', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.nightwing', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.nightwing', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt.token',
        'data_tk'     : ['trakt.authed', 'trakt.user', 'trakt.token', 'trakt.refresh', 'trakt.client_id', 'trakt.client_secret'],
    },

    #JOKERS ABSOLUTION
    'absolution': {
        'name'        : 'Jokers Absolution',
        'plugin'      : 'plugin.video.absolution',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.absolution'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.absolution', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.absolution', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.absolution', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt.token',
        'data_tk'     : ['trakt.authed', 'trakt.user', 'trakt.token', 'trakt.refresh', 'trakt.client_id', 'trakt.client_secret'],
    },

    #THE CREW
    'thecrew': {
        'name'        : 'The Crew',
        'plugin'      : 'plugin.video.thecrew',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.thecrew'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.thecrew', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.thecrew', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.thecrew', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt.token',
        'data_tk'     : ['trakt.refresh', 'trakt.token', 'trakt.user'],
    },

    #SCRUBS V2
    'scrubs': {
        'name'        : 'Scrubs V2',
        'plugin'      : 'plugin.video.scrubsv2',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.scrubsv2'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.scrubsv2/resources/images', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.scrubsv2/resources/images', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.scrubsv2', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt.token',
        'data_tk'     : ['trakt.refresh', 'trakt.token', 'trakt.user', 'trakt.authed'],
    },

    #OTAKU
    'otaku': {
        'name'        : 'Otaku',
        'plugin'      : 'plugin.video.otaku',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.otaku'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.otaku', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.otaku', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.otaku', 'settings.xml'),
        #RD
        'default_rd'  : 'realdebrid.token',
        'data_rd'     : ['realdebrid.username', 'realdebrid.token', 'realdebrid.client_id', 'realdebrid.secret', 'realdebrid.refresh', 'realdebrid.enabled'],
        #PM
        'default_pm'  : 'premiumize.token',
        'data_pm'     : ['premiumize.username', 'premiumize.token', 'premiumize.enabled'],
        #AD
        'default_ad'  : 'alldebrid.token',
        'data_ad'     : ['alldebrid.username', 'alldebrid.token', 'alldebrid.enabled'],
        #ED
        'default_ed'  : 'eb.token',
        'data_ed'     : [],
        #TB
        'default_tb'  : 'torbox.token',
        'data_tb'     : ['torbox.token', 'torbox.username', 'torbox.enabled', 'torbox.auth.status'],
    },

    #RESOLVEURL
    'rurl': {
        'name'        : 'ResolveURL',
        'plugin'      : 'script.module.resolveurl',
        'path'        : os.path.join(CONFIG.ADDONS, 'script.module.resolveurl'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'script.module.resolveurl', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'script.module.resolveurl', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'script.module.resolveurl', 'settings.xml'),
        #RD
        'default_rd'  : 'RealDebridResolver_token',
        'data_rd'     : ['RealDebridResolver_client_id', 'RealDebridResolver_client_secret', 'RealDebridResolver_refresh', 'RealDebridResolver_token', 'RealDebridResolver_cached_only'],
        #PM
        'default_pm'  : 'PremiumizeMeResolver_token',
        'data_pm'     : ['PremiumizeMeResolver_token', 'PremiumizeMeResolver_cached_only', 'premiumize.status'],
        #AD
        'default_ad'  : 'AllDebridResolver_token',
        'data_ad'     : ['AllDebridResolver_token', 'AllDebridResolver_cached_only'],
    },

    #TMDb HELPER
    'tmdbhelper': {
        'name'        : 'TMDb Helper',
        'plugin'      : 'plugin.video.themoviedb.helper',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.themoviedb.helper'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.themoviedb.helper', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.themoviedb.helper', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.themoviedb.helper', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt_token',
        'data_tk'     : ['trakt_token'],
    },

    #TRAKT ADDON
    'trakt': {
        'name'        : 'Trakt Add-on',
        'plugin'      : 'script.trakt',
        'path'        : os.path.join(CONFIG.ADDONS, 'script.trakt'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'script.trakt', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'script.trakt', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'script.trakt', 'settings.xml'),
        #TK
        'default_tk'  : 'authorization',
        'data_tk'     : ['authorization', 'user'],
    },

    #PREMIUMIZERX
    'premx': {
        'name'        : 'Premiumizer',
        'plugin'      : 'plugin.video.premiumizerx',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.premiumizerx'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.premiumizerx', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.premiumizerx', 'fanart.jpg'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.premiumizerx', 'settings.xml'),
        #PM
        'default_pm'  : 'premiumize.token',
        'data_pm'     : ['premiumize.status', 'premiumize.token', 'premiumize.refresh'],
    },

    #REALIZERX
    'realx': {
        'name'        : 'Realizer',
        'plugin'      : 'plugin.video.realizerx',
        'path'        : os.path.join(CONFIG.ADDONS, 'plugin.video.realizerx'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'plugin.video.realizerx', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'plugin.video.realizerx', 'fanart.png'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'plugin.video.realizerx', 'rdauth.json'),
        #RD
        'default_rd'  : 'rdauth',
        'data_rd'     : [],
    },

    #ACCOUNT MANAGER
    'acctmgr': {
        'name'        : 'Account Manager Lite',
        'plugin'      : 'script.module.acctmgr',
        'path'        : os.path.join(CONFIG.ADDONS, 'script.module.acctmgr'),
        'icon'        : os.path.join(CONFIG.ADDONS, 'script.module.acctmgr', 'icon.png'),
        'fanart'      : os.path.join(CONFIG.ADDONS, 'script.module.acctmgr', 'fanart.png'),
        'settings'    : os.path.join(CONFIG.ADDON_DATA, 'script.module.acctmgr', 'settings.xml'),
        #TK
        'default_tk'  : 'trakt.token',
        'data_tk'     : [],
        #RD
        'default_rd'  : 'realdebrid.token',
        'data_rd'     : ['realdebrid.client_id', 'realdebrid.refresh', 'realdebrid.secret', 'realdebrid.token', 'realdebrid.username'],
        #PM
        'default_pm'  : 'premiumize.token',
        'data_pm'     : ['premiumize.token', 'premiumize.username'],
        #AD
        'default_ad'  : 'alldebrid.token',
        'data_ad'     : ['alldebrid.token', 'alldebrid.username'],
        #ED
        'default_ed'  : 'easydebrid.token',
        'data_ed'     : ['easydebrid.token', 'easydebrid.acct_id', 'easydebrid.enabled'],
        #TB
        'default_tb'  : 'torbox.token',
        'data_tb'     : ['torbox.token', 'torbox.acct_id', 'torbox.enabled'],
        #OC
        'default_oc'  : 'offcloud.token',
        'data_oc'     : ['offcloud.token', 'offcloud.pass', 'offcloud.user', 'offcloud.userid', 'offcloud.enabled'],
        #EN
        'default_en'  : 'easynews.password',
        'data_en'     : ['easynews.password', 'easynews.username'],
    },
}

# Helpers
def get_addon_by_id(id):
    try:
        return xbmcaddon.Addon(id=id)
    except:
        return None

def is_authorized_value(val):
    return bool(val) and str(val).strip().lower() not in ('', 'none', 'null', 'empty_setting')

def open_settings(who): # Open addon settings
    addon = get_addon_by_id(ADDONS[who]['plugin'])
    if addon:
        addon.openSettings()

def chk_sql_auth(db, key):  # Database helper
    if not key:
        return False

    try:
        conn = sqlite3.connect(db, timeout=3)
        cur = conn.cursor()
        cur.execute(
            "SELECT setting_value FROM settings WHERE setting_id = ?",(key,))
        row = cur.fetchone()
        cur.close()
        conn.close()
        return is_authorized_value(row[0] if row else '')
    except Exception:
        return False

# Check Authorization
def addon_user(who, service):

    cache_key = f"{who}:{service}"
    if cache_key in AUTH_CACHE:
        return AUTH_CACHE[cache_key]

    info = ADDONS.get(who)
    if not info:
        AUTH_CACHE[cache_key] = False
        return False

    xbmc.sleep(100)
    user = False

    try:
        # Fen Light & Gears (settings.db)
        if who == 'fenlt':
            key = info.get(f'default_{service}')
            user = chk_sql_auth(fenlt_settings_db, key)

        elif who == 'gears':
            key = info.get(f'default_{service}')
            user = chk_sql_auth(gears_settings_db, key)

        # Realizer (rdauth.josn)
        elif who == 'realx':
            if service == 'rd' and os.path.exists(chkset_realx_json):
                with open(chkset_realx_json) as f:
                    user = is_authorized_value(json.load(f).get('token'))

        # Standard add-ons (settings.xml)
        else:
            key = info.get(f'default_{service}')
            if key:
                addon = get_addon_by_id(info['plugin'])
                if addon:
                    user = is_authorized_value(addon.getSetting(key))

    except Exception as e:
        xbmc.log(f"{amgr}: Auth check failed for {who}: {e}", xbmc.LOGINFO)

    AUTH_CACHE[cache_key] = user
    return user
    
# Revoke Handler
def addon_it(do, who='all', services=('tk', 'rd', 'pm', 'ad', 'ed', 'tb', 'oc', 'en')):
    
    # do = 'wipeaddon'
    # who = addon key or 'all'
    
    if who == 'all':
        targets = ORDER
    else:
        targets = (who,)

    for addon in targets:
        if addon not in ADDONS:
            continue

        for service in services:
            # Only revoke if currently authorized
            if addon_user(addon, service):
                wipe_addons(do, addon, service)
                
# Revoke Add-ons
def wipe_addons(do, who, service):
    info = ADDONS[who]
    settings = info['settings']
    data = info.get(f'data_{service}', [])
    
    if who in ('fenlt','gears','acctmgr'):  # Never wipe these
        return

    if settings.endswith('.json'):  # Wipe Realizer
        if os.path.exists(settings):
            with open(settings, 'w') as f:
                f.write('{}')
        return

    if os.path.exists(settings):
        tree = ElementTree.parse(settings)
        root = tree.getroot()
        for setting in root.findall('setting'):
            if setting.attrib.get('id') in data:
                root.remove(setting)
        tree.write(settings)
