# -*- coding: utf-8 -*-
"""The addon's JSON documents, its account settings and its onboarding as account entities (020 §3).

Each entity has a local map {key: value} read from the device (files / settings) and a `base` map: the last state agreed
with the server, kept in DATA/account/base/<entity>.json. A round compares local with base and queues ops for the
differences (push); a pulled change updates the file and the base together (no echo). A crash between a file write and
the diff is harmless: the next round finds the difference again and the server dedupes it by content.

Entities: search, recent, ai_recent, favorite, channel, channel_progress, setting, onboarding."""
import json
import os
import time
import uuid

from wcs.account import state

FAVORITES = {'actor': 'favorite_actors.json', 'director': 'favorite_directors.json', 'writer': 'favorite_writers.json'}
CHANNEL_FILES = {'tv': 'mytv_channels.json', 'cinema': 'mycinema_channels.json'}
HISTORY_DIRS = {'tv': 'mytv_history', 'cinema': 'mycinema_history'}
ROWS = {'channel': {'widget_mytv_channels', 'widget_mytv_next', 'widget_mycinema_channels', 'widget_mycinema_recommended'},
        'channel_progress': {'widget_mytv_next'}, 'recent': {'widget_game_topics'}, 'ai_recent': {'widget_ai_recent'}}
ENTITIES = ('search', 'recent', 'ai_recent', 'favorite', 'channel', 'channel_progress', 'setting', 'onboarding')


def profile():
    """The addon's profile folder, the same way wcs/user_data.py finds it."""
    import xbmcaddon
    import xbmcvfs
    return xbmcvfs.translatePath(xbmcaddon.Addon(state.ADDON_ID).getAddonInfo('profile'))


def _path(*parts):
    return os.path.join(profile(), *parts)


def _read(path, default):
    try:
        with open(path, 'r', encoding='utf-8') as handle:
            return json.load(handle)
    except (OSError, ValueError):
        return default


def _write(path, data):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    temporary = path + '.tmp'
    with open(temporary, 'w', encoding='utf-8') as handle:
        json.dump(data, handle, ensure_ascii=False, indent=2)
    os.replace(temporary, path)


def _addon():
    import xbmcaddon
    return xbmcaddon.Addon(state.ADDON_ID)


def item_key(item):
    media = item.get('media_type') or ('tv' if item.get('series_name') else 'movie')
    if item.get('tmdb_id') or item.get('id'):
        return '{}:{}'.format(media, item.get('tmdb_id') or item.get('id'))
    return 'title:{}'.format(item.get('title') or item.get('name') or '')


# --------------------------------------------------------------------------- local maps

def _search_local():
    data = _read(_path('search_history.json'), {})
    out = {}
    for scope, queries in (data.items() if isinstance(data, dict) else []):
        for index, query in enumerate(queries if isinstance(queries, list) else []):
            out['{}:{}'.format(scope, query)] = {'scope': scope, 'query': query, 'order': index}
    return out


def _list_local(name):
    items = _read(_path(name), [])
    return {item_key(item): {'item': item, 'order': index} for index, item in enumerate(items if isinstance(items, list) else [])
            if isinstance(item, dict)}


def _favorite_local():
    out = {}
    for role, name in FAVORITES.items():
        for index, item in enumerate(_read(_path(name), []) or []):
            if isinstance(item, dict) and item.get('id'):
                out['{}:{}'.format(role, int(item['id']))] = {'item': item, 'order': index}
    return out


def _channel_local(root=None):
    """`root`: another folder with the same files (the sign-in backup, wcs/account/merge.py)."""
    out = {}
    for kind, name in CHANNEL_FILES.items():
        for pos, channel in enumerate(_read(os.path.join(root, name) if root else _path(name), []) or []):
            if not isinstance(channel, dict) or not channel.get('id'):
                continue
            items = channel.get('media_list') or channel.get('series_list') or []
            out[str(channel['id'])] = {'type': kind, 'name': channel.get('name', ''), 'pos': pos,
                                       'items': [{'key': item_key(dict(item, media_type='tv' if kind == 'tv' else 'movie')),
                                                  'item': item} for item in items if isinstance(item, dict)]}
    return out


def _progress_local(root=None):
    out = {}
    for kind, folder in HISTORY_DIRS.items():
        directory = os.path.join(root, folder) if root else _path(folder)
        if not os.path.isdir(directory):
            continue
        for name in os.listdir(directory):
            if not name.endswith('.json'):
                continue
            data = _read(os.path.join(directory, name), {})
            for title_id, entry in (data.items() if isinstance(data, dict) else []):
                out['{}:{}:{}'.format(name[:-5], 'tv' if kind == 'tv' else 'movie', title_id)] = {'kind': kind, 'entry': entry}
    return out


def _settings_local(ids):
    addon = _addon()
    return {sid: addon.getSetting(sid) for sid in ids}


def _onboarding_local():
    addon = _addon()
    step = addon.getSetting('onboarding_step')
    genres = [g for g in addon.getSetting('onboarding_genres').split(',') if g]
    return {'user': {'step': step, 'genres': genres}} if step else {}


def local(entity, schema=None):
    if entity == 'search':
        return _search_local()
    if entity == 'recent':
        return _list_local('global_watch_history.json')
    if entity == 'ai_recent':
        return _list_local('ai_recommendations.json')
    if entity == 'favorite':
        return _favorite_local()
    if entity == 'channel':
        return _channel_local()
    if entity == 'channel_progress':
        return _progress_local()
    if entity == 'setting':
        return _settings_local((schema or {}).get('account', []))
    if entity == 'onboarding':
        return _onboarding_local()
    return {}


# --------------------------------------------------------------------------- base maps

def base(entity):
    return _read(_path('account', 'base', entity + '.json'), {})


def save_base(entity, data):
    _write(_path('account', 'base', entity + '.json'), data)


def same(left, right):
    return json.dumps(left, sort_keys=True, ensure_ascii=False) == json.dumps(right, sort_keys=True, ensure_ascii=False)


# --------------------------------------------------------------------------- push: local vs base → ops

def diff_ops(entity, old, new, now_ms):
    """Ops that turn the server's `old` into the device's `new` (both maps of one entity)."""
    ops = []

    def op(kind, key, payload=None, at=None):
        ops.append({'op_id': uuid.uuid4().hex, 'type': kind, 'key': key, 'at': at or now_ms, 'payload': payload or {}})

    if entity == 'search':
        for key, value in new.items():
            if key not in old:
                op('search_add', key, at=now_ms - value.get('order', 0))
        for key in set(old) - set(new):
            op('search_remove', key)
    elif entity in ('recent', 'ai_recent'):
        prefix = 'recent' if entity == 'recent' else 'ai_recent'
        for key, value in new.items():
            if key not in old or not same(old[key].get('item'), value.get('item')):
                op(prefix + '_add', key, {'item': value.get('item')}, at=now_ms - value.get('order', 0))
        for key in set(old) - set(new):
            op(prefix + '_remove', key)
    elif entity == 'favorite':
        for key, value in new.items():
            if key not in old or not same(old[key].get('item'), value.get('item')):
                op('favorite_set', key, {'on': True, 'item': value.get('item')}, at=now_ms - value.get('order', 0))
        for key in set(old) - set(new):
            op('favorite_set', key, {'on': False})
    elif entity == 'channel':
        for key, value in new.items():
            before = old.get(key)
            if before is None:
                op('channel_create', key, {'type': value['type'], 'name': value['name'], 'pos': value['pos']})
                before = {'items': []}
            else:
                if before.get('name') != value['name']:
                    op('channel_rename', key, {'name': value['name']})
                if before.get('pos') != value['pos']:
                    op('channel_move', key, {'pos': value['pos']})
            old_items = {entry['key']: (index, entry['item']) for index, entry in enumerate(before.get('items', []))}
            new_items = {entry['key']: (index, entry['item']) for index, entry in enumerate(value['items'])}
            for item_key_, (index, item) in new_items.items():
                if item_key_ not in old_items or old_items[item_key_][0] != index or not same(old_items[item_key_][1], item):
                    media, ident = item_key_.split(':', 1)
                    op('channel_item_set', '{}:{}:{}'.format(key, media, ident), {
                        'on': True, 'pos': index, 'item': item, 'title': item.get('name') or item.get('title') or '',
                        'poster_path': item.get('poster_path'), 'year': str(item.get('year') or '')})
            for item_key_ in set(old_items) - set(new_items):
                media, ident = item_key_.split(':', 1)
                op('channel_item_set', '{}:{}:{}'.format(key, media, ident), {'on': False})
        for key in set(old) - set(new):
            op('channel_delete', key)
    elif entity == 'channel_progress':
        for key, value in new.items():
            if key not in old or not same(old[key].get('entry'), value.get('entry')):
                entry = value.get('entry') or {}
                op('channel_progress_set', key, {'entry': entry, 'season': entry.get('season'), 'episode': entry.get('episode'),
                                                 'watched': bool(entry.get('watched'))})
    elif entity == 'setting':
        for key, value in new.items():
            if key in old and old[key] != value:
                op('setting_set', key, {'value': value})
    elif entity == 'onboarding':
        value, before = new.get('user'), old.get('user')
        if value and not same(value, before):
            op('onboarding_set', 'user', {'step': value['step'], 'genres': value['genres'], 'done': value['step'] == 'done'})
    return ops


def round_ops(schema, now_ms, dialog_open=False, settings=True):
    """One push round: (ops, bases). The caller commits the ops to the outbox FIRST and only then calls
    save_bases(bases), so a crash in between only repeats ops (the server dedupes them by content and time)."""
    ops, bases = [], {}
    for entity in ENTITIES:
        if entity == 'setting' and (dialog_open or not settings):
            continue                                   # T20: Kodi writes the dialog's values on OK; else only when changed
        current = local(entity, schema)
        old = base(entity)
        if entity == 'setting':
            old = {key: value for key, value in old.items() if key in current}
            if not old and current:
                bases[entity] = current               # first round after a sign-in: nothing to send
                continue
        new_ops = diff_ops(entity, old, current, now_ms)
        if new_ops:
            ops.extend(new_ops)
            bases[entity] = current
    return ops, bases


def save_bases(bases):
    for entity, data in bases.items():
        save_base(entity, data)


# --------------------------------------------------------------------------- pull: server rows → files + base

def _changed_rows(names):
    try:
        from wcs.skin.refresh import changed
        changed(set(names))
    except Exception:
        pass


def _by_at(rows):
    return sorted(rows, key=lambda row: -(row.get('at') or 0))


def _apply_search(changes, replace):
    data = {} if replace else _read(_path('search_history.json'), {})
    data = data if isinstance(data, dict) else {}
    for change in (changes if not replace else []):
        row = change.get('row') or {}
        scope, query = (change['key'].split(':', 1) + [''])[:2]
        lst = [q for q in data.get(scope, []) if q != query]
        if not change.get('deleted'):
            lst.insert(0, query)
        data[scope] = lst
    if replace:
        for row in _by_at([c.get('row') or {} for c in changes]):
            data.setdefault(row.get('scope', 'universal'), []).append(row.get('query'))
    for scope in ('universal', 'tmdb', 'tv'):
        data.setdefault(scope, [])
    _write(_path('search_history.json'), data)
    save_base('search', _search_local())


def _apply_list(entity, name, changes, replace):
    items = [] if replace else [i for i in (_read(_path(name), []) or []) if isinstance(i, dict)]
    if replace:
        items = [row.get('item') or {} for row in _by_at([c.get('row') or {} for c in changes])]
    else:
        for change in changes:
            items = [i for i in items if item_key(i) != change['key']]
            if not change.get('deleted'):
                items.insert(0, (change.get('row') or {}).get('item') or {})
    _write(_path(name), items[:50 if entity == 'recent' else 30])
    save_base(entity, _list_local(name))
    _changed_rows(ROWS[entity])


def _apply_favorite(changes, replace):
    files = {role: ([] if replace else [i for i in (_read(_path(name), []) or []) if isinstance(i, dict)]) for role, name in FAVORITES.items()}
    for change in (_by_at(changes) if replace else changes):
        role, ident = change['key'].split(':', 1)
        if role not in files:
            continue
        files[role] = [i for i in files[role] if str(i.get('id')) != ident]
        if not change.get('deleted'):
            item = (change.get('row') or {}).get('item') or {'id': int(ident)}
            files[role].insert(len(files[role]) if replace else 0, item)
    for role, name in FAVORITES.items():
        _write(_path(name), files[role])
    save_base('favorite', _favorite_local())


def _apply_channels(changes, replace):
    files = {kind: ([] if replace else [c for c in (_read(_path(name), []) or []) if isinstance(c, dict)]) for kind, name in CHANNEL_FILES.items()}
    for change in changes:
        uuid_ = change['key']
        existing = None
        for kind in files:
            for channel in files[kind]:
                if str(channel.get('id')) == uuid_:
                    existing = channel
            files[kind] = [c for c in files[kind] if str(c.get('id')) != uuid_]
        if change.get('deleted'):
            continue
        row = change.get('row') or {}
        kind = 'cinema' if row.get('type') == 'cinema' else 'tv'
        items = []
        for entry in sorted(row.get('items') or [], key=lambda e: (e.get('pos') is None, e.get('pos') or 0)):
            item = entry.get('item') or {'id': entry.get('tmdb_id'), 'name': entry.get('title'), 'title': entry.get('title'),
                                         'poster_path': entry.get('poster_path'), 'year': entry.get('year')}
            items.append(item)
        channel = dict(existing or {}, id=uuid_, name=row.get('name') or '', channel_type=kind, media_list=items, series_list=items)
        channel.setdefault('icon', '')
        position = int(row.get('pos') or 0)
        files[kind].insert(min(max(position, 0), len(files[kind])), channel)
    for kind, name in CHANNEL_FILES.items():
        _write(_path(name), files[kind])
    save_base('channel', _channel_local())
    _changed_rows(ROWS['channel'])


def _apply_progress(changes, replace):
    touched = {}
    if replace:
        for folder in HISTORY_DIRS.values():
            directory = _path(folder)
            for name in (os.listdir(directory) if os.path.isdir(directory) else []):
                if name.endswith('.json'):
                    os.remove(os.path.join(directory, name))
    for change in changes:
        channel, media, title_id = change['key'].split(':', 2)
        folder = HISTORY_DIRS['tv' if media == 'tv' else 'cinema']
        path = _path(folder, channel + '.json')
        data = touched.get(path) or _read(path, {})
        data = data if isinstance(data, dict) else {}
        if change.get('deleted'):
            data.pop(title_id, None)
        else:
            data[title_id] = (change.get('row') or {}).get('entry') or {}
        touched[path] = data
    for path, data in touched.items():
        _write(path, data)
    save_base('channel_progress', _progress_local())
    _changed_rows(ROWS['channel_progress'])


def _settings_dialog_open():
    try:
        import xbmc
        return xbmc.getCondVisibility('Window.IsActive(addonsettings)')
    except Exception:
        return False


def apply_pending_settings():
    """Settings that came while the settings dialog was open (T20), applied once it is closed."""
    pending = _read(_path('account', 'pending_settings.json'), {})
    if not pending or _settings_dialog_open():
        return 0
    addon = _addon()
    current = base('setting')
    for key, value in pending.items():
        if addon.getSetting(key) != value:
            addon.setSetting(key, value)
        current[key] = value
    save_base('setting', current)
    os.remove(_path('account', 'pending_settings.json'))
    return len(pending)


def _apply_settings(changes, replace):
    from wcs.account import schema as account_schema
    allowed = set(account_schema.account_ids())
    values = {key: None for key in allowed} if replace else {}     # a sign-in: every account setting, default when unset
    for change in changes:
        key = change['key']
        if key not in allowed:
            continue
        values[key] = None if change.get('deleted') else str((change.get('row') or {}).get('value', ''))
    if _settings_dialog_open():
        pending = _read(_path('account', 'pending_settings.json'), {})
        pending.update({k: v for k, v in values.items() if v is not None})
        _write(_path('account', 'pending_settings.json'), pending)
        return
    addon = _addon()
    current = base('setting')
    for key, value in values.items():
        if value is None:
            value = account_schema.default(key)
        if addon.getSetting(key) != value:
            addon.setSetting(key, value)
        current[key] = value
    save_base('setting', current)


def _apply_onboarding(changes, replace):
    for change in changes:
        row = change.get('row') or {}
        if change.get('deleted'):
            continue
        addon = _addon()
        step = 'done' if row.get('done') else str(row.get('step') or '')
        if step and addon.getSetting('onboarding_step') != step:
            addon.setSetting('onboarding_step', step)
        genres = ','.join(str(g) for g in (row.get('genres') or []))
        if addon.getSetting('onboarding_genres') != genres:
            addon.setSetting('onboarding_genres', genres)
    save_base('onboarding', _onboarding_local())


def apply(changes, replace=False):
    """Pulled document / setting / onboarding changes (already filtered to these entities)."""
    groups = {}
    for change in changes:
        groups.setdefault(change.get('entity'), []).append(change)
    handlers = {'search': _apply_search, 'favorite': _apply_favorite, 'channel': _apply_channels,
                'channel_progress': _apply_progress, 'setting': _apply_settings, 'onboarding': _apply_onboarding,
                'recent': lambda c, r: _apply_list('recent', 'global_watch_history.json', c, r),
                'ai_recent': lambda c, r: _apply_list('ai_recent', 'ai_recommendations.json', c, r)}
    count = 0
    with state.applying():
        for entity in ENTITIES:
            if entity in groups or (replace and entity != 'onboarding'):
                started = time.time()
                handlers[entity](groups.get(entity, []), replace)
                count += len(groups.get(entity, []))
                if time.time() - started > 0.5:
                    from wcs.account import client
                    client._log('{} applied in {:.1f} s'.format(entity, time.time() - started))
    return count
