"""Keep Milionář updates manual without changing Kodi's global update preference.

Kodi 21 exposes no Python/JSON-RPC setter for per-addon update rules. Use its
existing USER_DISABLED_AUTO_UPDATE rule, then reload the native rule cache via
UpdateLocalAddons (AddonMgr::FindAddons). See docs/plan/skin-milionar/250-update.md.
"""
from contextlib import closing
import os
import re
import sqlite3

import xbmc
import xbmcvfs

ADDONS = ('plugin.video.milionar', 'skin.milionar')
USER_DISABLED_AUTO_UPDATE = 1


def enforce():
    try:
        folder = xbmcvfs.translatePath('special://database/')
        candidates = [(int(match.group(1)), name) for name in os.listdir(folder)
                      if (match := re.fullmatch(r'Addons(\d+)\.db', name))]
        if not candidates:
            raise OSError('Kodi addon database is unavailable')
        path = os.path.join(folder, max(candidates)[1])
        # mode=rw never creates an empty replacement database.
        from urllib.parse import quote
        with closing(sqlite3.connect('file:' + quote(path, safe='/') + '?mode=rw', uri=True, timeout=5)) as database:
            changed = False
            for addon_id in ADDONS:
                if database.execute('SELECT 1 FROM update_rules WHERE addonID=? AND updateRule=?',
                                    (addon_id, USER_DISABLED_AUTO_UPDATE)).fetchone():
                    continue
                cursor = database.execute(
                    'INSERT OR IGNORE INTO update_rules(addonID, updateRule) VALUES (?, ?)',
                    (addon_id, USER_DISABLED_AUTO_UPDATE))
                changed = changed or cursor.rowcount > 0
            database.commit()
        if changed:
            xbmc.executebuiltin('UpdateLocalAddons', True)
        return True
    except (OSError, sqlite3.Error) as exc:
        xbmc.log('[Milionář Update] manual update policy failed: ' + type(exc).__name__, xbmc.LOGERROR)
        return False


def run():
    monitor = xbmc.Monitor()
    while not monitor.waitForAbort(60):
        enforce()
