# -*- coding: utf-8 -*-
"""Reset of everything watched / in progress (user request 2026-10-01): addon store, Recently played, MyTV and
MyCinema channel progress and Kodi's own watched / resume data. Lists, channels and search history stay."""
import json
import os

import xbmc
import xbmcgui
import xbmcvfs

from wcs.library2 import mirror, store

ADDON_ID = 'plugin.video.milionar'
S_TITLE, S_CONFIRM, S_DONE = 32270, 32271, 32272


def _rpc(method, params):
    return json.loads(xbmc.executeJSONRPC(json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': params})))


def _profile():
    return xbmcvfs.translatePath('special://profile/addon_data/{}/'.format(ADDON_ID))


def _zero_kodi_records(keys):
    """Kodi's records of the addon's canonical URLs (what the mirror wrote)."""
    done = 0
    for kind, tmdb_id, season, episode in keys:
        url = mirror.canonical_for('movie' if kind == 'movie' else 'episode', tmdb_id, season, episode)
        reply = _rpc('Files.SetFileDetails', {'file': url, 'media': 'video', 'playcount': 0, 'lastplayed': '',
                                              'resume': {'position': 0, 'total': 0}})
        done += reply.get('result') == 'OK'
    return done


def _reset_kodi_library():
    """Watched flags and resume points of the Kodi video library (movies and episodes)."""
    flt = {'or': [{'field': 'playcount', 'operator': 'greaterthan', 'value': '0'},
                  {'field': 'inprogress', 'operator': 'true', 'value': ''}]}
    cleared = 0
    for method, key, setter, id_key in (
            ('VideoLibrary.GetMovies', 'movies', 'VideoLibrary.SetMovieDetails', 'movieid'),
            ('VideoLibrary.GetEpisodes', 'episodes', 'VideoLibrary.SetEpisodeDetails', 'episodeid')):
        rows = (_rpc(method, {'filter': flt, 'properties': ['playcount']}).get('result') or {}).get(key, [])
        for row in rows:
            _rpc(setter, {id_key: row[id_key], 'playcount': 0, 'lastplayed': '', 'resume': {'position': 0, 'total': 0}})
            cleared += 1
    return cleared


def _remove_files(folder, names=None):
    removed = 0
    if not os.path.isdir(folder):
        return 0
    for name in (names or os.listdir(folder)):
        path = os.path.join(folder, name)
        if os.path.isfile(path):
            os.remove(path)
            removed += 1
    return removed


def reset_all():
    """Do the reset; returns a dict of counts."""
    profile = _profile()
    counts = {}
    counts['kodi_mirror'] = _zero_kodi_records(store.all_state_keys())
    counts['kodi_library'] = _reset_kodi_library()
    counts.update(store.reset_watch_state())
    counts['taste'] = store.reset_taste()
    counts['recent'] = _remove_files(profile, ['global_watch_history.json', 'recently_played.json'])
    counts['channels'] = _remove_files(os.path.join(profile, 'mytv_history')) + \
        _remove_files(os.path.join(profile, 'mycinema_history'))
    try:
        from wcs.skin.refresh import changed
        changed({'widget_mytv_channels', 'widget_mytv_next', 'widget_mycinema_channels', 'widget_game_topics'})
    except Exception:
        pass
    return counts


def confirm_and_reset(addon):
    if not xbmcgui.Dialog().yesno(addon.getLocalizedString(S_TITLE), addon.getLocalizedString(S_CONFIRM)):
        return None
    counts = reset_all()
    xbmc.log('[Milionář Library] watch history reset: {}'.format(counts), xbmc.LOGINFO)
    xbmcgui.Dialog().notification('Milionář', addon.getLocalizedString(S_DONE), xbmcgui.NOTIFICATION_INFO, 4000)
    try:                                                # Pro tebe at once: the pick card is back in the row
        from wcs.foryou import service
        service.build_now('reset')
    except Exception as exc:
        xbmc.log('[Milionář Library] Pro tebe rebuild after reset failed: {}'.format(exc), xbmc.LOGWARNING)
    return counts
