# -*- coding: utf-8 -*-
"""Pulled account changes → the local copy (docs/plan/milionar-account/020 §4).

SQLite entities of one page (watch, library, title, feedback, play_log) are written in ONE store transaction together
with the new cursor; documents (channels, histories, favourites), settings and the onboarding go through wcs.account.docs
and wcs.account.settings_sync afterwards (idempotent). A key with a queued local op is skipped (T6): the push of that op
is answered by the server and the next pull brings the resolved row. Rows only change when values differ, so only the
cards of really changed titles redraw (store.dirty + conn.widget_titles, as for a local change)."""
import json

from wcs.account import state

SQL_ENTITIES = ('watch', 'library', 'title', 'feedback', 'play_log')
WATCH_OPS = ('progress', 'watched', 'unwatched', 'clear_resume')

acked = {}            # key -> account rev the server returned for our last op on it (set by the push thread)


def pending_keys(conn):
    """{(entity, key)} that still have a local op in the outbox."""
    keys = set()
    for row in conn.execute('SELECT type, key FROM sync_outbox'):
        op, key = row['type'], row['key']
        if op in WATCH_OPS:
            keys.add(('watch', key))
        elif op == 'mark_many':
            keys.add(('watch*', key))                         # every episode / the film of this title
        elif op in ('list_set', 'list_move'):
            keys.add(('library', key))
        elif op == 'hide_continue':
            keys.add(('title', key))
        elif op.startswith('feedback'):
            keys.add(('feedback', key))
        elif op == 'reset_watch':
            keys.add(('watch*', '*'))
        elif op.startswith('search_'):
            keys.add(('search', key))
        elif op.startswith('recent_'):
            keys.add(('recent', key))
        elif op.startswith('ai_recent_'):
            keys.add(('ai_recent', key))
        elif op == 'favorite_set':
            keys.add(('favorite', key))
        elif op.startswith('channel_progress'):
            keys.add(('channel_progress', key))
        elif op.startswith('channel_'):
            keys.add(('channel', key.split(':')[0]))
        elif op.startswith('setting_'):
            keys.add(('setting', key))
        elif op == 'onboarding_set':
            keys.add(('onboarding', 'user'))
    return keys


def _pending(entity, key, pending):
    if (entity, key) in pending:
        return True
    if entity == 'watch':
        title = ':'.join(key.split(':')[:2])
        if ('watch*', title) in pending or ('watch*', '*') in pending:
            return True
    return False


def _skipped(entity, key, rev, pending):
    if _pending(entity, key, pending):
        return True
    seen = acked.get((entity, key))
    return seen is not None and rev < seen


def skipped_keys(conn):
    """Keys whose server row was skipped while a local op on them was queued: fetched again once the op is answered."""
    row = conn.execute("SELECT value FROM sync_state WHERE key='skipped'").fetchone()
    try:
        return set(tuple(k) for k in json.loads(row[0])) if row else set()
    except ValueError:
        return set()


def save_skipped(conn, keys):
    conn.execute("INSERT OR REPLACE INTO sync_state(key, value) VALUES('skipped', ?)", (json.dumps(sorted(keys)),))


def due_refresh(conn):
    """Skipped keys that have no queued op any more."""
    pending = pending_keys(conn)
    return sorted(k for k in skipped_keys(conn) if not _pending(k[0], k[1], pending))


def _watch(conn, store, key, row, deleted):
    parts = key.split(':')
    media = parts[0]
    tmdb_id = int(parts[1])
    season = episode = None
    if media == 'tv':
        season, episode = int(parts[2]), int(parts[3])
        if season < 0 or episode < 0:
            return False
    table, where, args, cols, vals = store._state_keys(media, tmdb_id, season, episode)
    if deleted:
        changed = conn.execute('UPDATE {} SET playcount=0, resume_pos=0, resume_total=0 WHERE {} AND '
                               '(playcount!=0 OR resume_pos!=0)'.format(table, where), args).rowcount
    else:
        store._ensure_state(conn, media, tmdb_id, season, episode)
        values = (int(row.get('playcount') or 0), row.get('last_played_at'), float(row.get('resume_pos') or 0),
                  float(row.get('resume_total') or 0), row.get('last_ident'), row.get('last_provider'), row.get('last_file_name'))
        changed = conn.execute(
            'UPDATE {} SET playcount=?, last_played_at=?, resume_pos=?, resume_total=?, last_ident=COALESCE(?, last_ident), '
            'last_provider=COALESCE(?, last_provider), last_file_name=COALESCE(?, last_file_name) WHERE {} AND '
            '(playcount IS NOT ? OR last_played_at IS NOT ? OR resume_pos IS NOT ? OR resume_total IS NOT ?)'.format(table, where),
            values + args + values[:4]).rowcount
        if changed and row.get('last_played_at'):
            store._ensure_title(conn, media, tmdb_id)
            conn.execute('UPDATE titles SET last_activity_at=MAX(COALESCE(last_activity_at, 0), ?) WHERE media_type=? AND tmdb_id=?',
                         (int(row['last_played_at']), media, tmdb_id))
    if changed:
        store._changed(conn, media, tmdb_id, season, episode)
        store._media_dirty(conn, media)
    return bool(changed)


def _library(conn, store, key, row, deleted):
    media, tmdb_id = key.split(':')[0], int(key.split(':')[1])
    store._ensure_title(conn, media, tmdb_id)
    if deleted:
        changed = conn.execute('UPDATE titles SET in_list=0, list_pos=NULL WHERE media_type=? AND tmdb_id=? AND in_list!=0',
                               (media, tmdb_id)).rowcount
    else:
        pos = row.get('list_pos')
        if pos is None:
            current = conn.execute('SELECT in_list, list_pos FROM titles WHERE media_type=? AND tmdb_id=?', (media, tmdb_id)).fetchone()
            pos = current['list_pos'] if current and current['in_list'] else conn.execute(
                'SELECT COALESCE(MAX(list_pos), -1) + 1 FROM titles WHERE media_type=? AND in_list=1', (media,)).fetchone()[0]
        changed = conn.execute('UPDATE titles SET in_list=1, list_pos=?, list_added_at=COALESCE(list_added_at, ?) '
                               'WHERE media_type=? AND tmdb_id=? AND (in_list!=1 OR list_pos IS NOT ?)',
                               (pos, row.get('list_added_at') or store._now(), media, tmdb_id, pos)).rowcount
    if changed:
        store._media_dirty(conn, media, True)
    return bool(changed)


def _title(conn, store, key, row, deleted):
    media, tmdb_id = key.split(':')[0], int(key.split(':')[1])
    store._ensure_title(conn, media, tmdb_id)
    hidden = None if deleted else row.get('hidden_from_continue_at')
    changed = conn.execute('UPDATE titles SET hidden_from_continue_at=? WHERE media_type=? AND tmdb_id=? '
                           'AND hidden_from_continue_at IS NOT ?', (hidden, media, tmdb_id, hidden)).rowcount
    if changed:
        store._media_dirty(conn, media)
    return bool(changed)


def _feedback(conn, store, key, row, deleted):
    media, tmdb_id = key.split(':')[0], int(key.split(':')[1])
    if deleted or row.get('value') not in store.FEEDBACK_VALUES:
        return bool(conn.execute('DELETE FROM feedback WHERE media_type=? AND tmdb_id=?', (media, tmdb_id)).rowcount)
    at = int((row.get('at') or 0) / 1000) or store._now()
    return bool(conn.execute('INSERT OR REPLACE INTO feedback(media_type, tmdb_id, value, at) SELECT ?,?,?,? WHERE NOT EXISTS '
                             '(SELECT 1 FROM feedback WHERE media_type=? AND tmdb_id=? AND value=?)',
                             (media, tmdb_id, row['value'], at, media, tmdb_id, row['value'])).rowcount)


def _play_log(conn, store, key, row, deleted):
    if deleted:
        changed = conn.execute('DELETE FROM play_log WHERE uuid=?', (key,)).rowcount
        if changed:
            store.dirty(conn, {'recent_played'})
        return bool(changed)
    if conn.execute('SELECT 1 FROM play_log WHERE uuid=?', (key,)).fetchone():
        return False
    conn.execute('INSERT INTO play_log(media_type,tmdb_id,season,episode,started_at,ended_at,position,total,outcome,uuid) '
                 'VALUES(?,?,?,?,?,?,?,?,?,?)', (row.get('media_type'), row.get('tmdb_id'), row.get('season'), row.get('episode'),
                                                row.get('started_at'), row.get('ended_at'), row.get('position'), row.get('total'),
                                                row.get('outcome'), key))
    store.dirty(conn, {'recent_played'})
    return True


APPLY = {'watch': _watch, 'library': _library, 'title': _title, 'feedback': _feedback, 'play_log': _play_log}


def apply_page(changes, cursor, replace=False):
    """Apply one page of changes, then store `cursor` (None: keep it). Returns the number of changed rows.
    `replace`: a bootstrap (sign-in or resync) — every SQL entity's rows are first emptied (the account replaces them)."""
    import time
    from wcs.library2 import store
    changed = 0
    docs = []
    started = time.time()
    marks = {}
    with state.applying():
        with store.tx() as conn:
            marks['lock'] = time.time() - started
            if replace:
                acked.clear()                      # a whole account: no op of ours is newer than it
                save_skipped(conn, set())
                conn.execute('DELETE FROM movie_state')
                conn.execute('DELETE FROM episode_state')
                conn.execute('DELETE FROM play_log')
                conn.execute('DELETE FROM feedback')
                conn.execute('UPDATE titles SET in_list=0, list_pos=NULL, hidden_from_continue_at=NULL, last_activity_at=NULL')
                from wcs.skin.refresh import ALL_ROWS
                store.dirty(conn, ALL_ROWS)
            pending = set() if replace else pending_keys(conn)
            skipped = set() if replace else skipped_keys(conn)
            before = set(skipped)
            for change in changes:
                entity, key = change.get('entity'), str(change.get('key'))
                if _pending(entity, key, pending):
                    skipped.add((entity, key))     # our op is newer here; after its answer the row is fetched again
                    continue
                if _skipped(entity, key, int(change.get('rev') or 0), pending):
                    continue
                skipped.discard((entity, key))
                if entity not in APPLY:
                    docs.append(change)
                    continue
                if APPLY[entity](conn, store, key, change.get('row') or {}, bool(change.get('deleted'))):
                    changed += 1
            if skipped != before:
                save_skipped(conn, skipped)
            if replace or len(conn.widget_titles) > 40:
                conn.widget_titles.clear()         # a whole account: the rows rebuild from their revisions, no card patches
            marks['rows'] = time.time() - started
    sql_s = time.time() - started
    if docs or replace:
        from wcs.account import docs as documents
        changed += documents.apply(docs, replace=replace)
    if cursor is not None:
        # only after the documents: a stop in between pulls the page again (both applies are idempotent)
        with store.tx() as conn:
            conn.execute("INSERT OR REPLACE INTO sync_state(key, value) VALUES('cursor', ?)", (str(int(cursor)),))
    if time.time() - started > 1.0:
        from wcs.account import client
        client._log('page of {} changes: library.db {:.1f} s (lock {:.1f}, rows {:.1f}), documents {:.1f} s'.format(
            len(changes), sql_s, marks.get('lock', 0), marks.get('rows', 0), time.time() - started - sql_s))
    return changed


def cursor():
    from wcs.library2 import store
    conn = store.connect()
    try:
        row = conn.execute("SELECT value FROM sync_state WHERE key='cursor'").fetchone()
        return int(row[0]) if row else 0
    finally:
        conn.close()


def bootstrap_changes(snapshot):
    """A bootstrap response as one list of changes (rows with their keys), for apply_page(replace=True)."""
    out = []
    for entity, rows in (snapshot.get('entities') or {}).items():
        for row in rows:
            out.append({'entity': entity, 'key': row.get('key') if entity != 'channel' else row.get('uuid'), 'rev': 0,
                        'deleted': False, 'row': row})
    return out


def dumps(value):
    return json.dumps(value, ensure_ascii=False, sort_keys=True)
