# -*- coding: utf-8 -*-
"""Merge this Kodi's own data into the account right after a sign-in (WEB docs/plan/account-sync S28, T37).

The sign-in backup (DATA/account/local_backup/) holds the device's data as it was before the sign-in. `summary()`
counts what can be merged; `ops()` turns it into ordinary account ops with the data's own times, so the server merges
them by the sync's rules (newer position wins, a watched is never lost, lists are a union, a later removal in the
account stays). Op ids are deterministic: the same data merged again is answered `duplicate`. Channel uuids are
remapped per account, so one Kodi's channels can go into two accounts. Nothing here changes the backup."""
import hashlib
import json
import os
import sqlite3
import uuid

from wcs.account import docs, hooks, state

POS_AFTER = 100              # merged channels sort after the account's own


def backup_dir():
    return docs._path('account', 'local_backup')


def _files(root):
    return os.path.join(root, 'files')


def _rows(root, sql):
    path = os.path.join(root, 'library_user.db')
    if not os.path.isfile(path):
        return []
    conn = sqlite3.connect(path, timeout=5.0)
    conn.row_factory = sqlite3.Row
    try:
        return [dict(r) for r in conn.execute(sql)]
    except sqlite3.Error:
        return []
    finally:
        conn.close()


def _channels(root):
    return docs._channel_local(_files(root))


def summary(root=None):
    """{movies, series, in_progress, watched, mytv, mycinema}: what this Kodi would add; all zero = nothing to offer."""
    root = root or backup_dir()
    lists = _rows(root, 'SELECT media_type, COUNT(*) AS n FROM titles WHERE in_list=1 GROUP BY media_type')
    count = {r['media_type']: r['n'] for r in lists}
    states = _rows(root, 'SELECT SUM(resume_pos > 0) AS progress, SUM(playcount > 0) AS watched FROM ('
                         'SELECT resume_pos, playcount FROM movie_state UNION ALL SELECT resume_pos, playcount FROM episode_state)')
    channels = _channels(root)
    return {'movies': count.get('movie', 0), 'series': count.get('tv', 0),
            'in_progress': int((states[0]['progress'] if states else 0) or 0),
            'watched': int((states[0]['watched'] if states else 0) or 0),
            'mytv': sum(1 for c in channels.values() if c['type'] == 'tv'),
            'mycinema': sum(1 for c in channels.values() if c['type'] == 'cinema')}


def has_data(counts):
    return any(counts.values())


def _op(kind, key, at, payload):
    payload = payload or {}
    digest = hashlib.sha1(json.dumps([kind, key, payload, int(at)], sort_keys=True, ensure_ascii=False).encode('utf-8'))
    return {'op_id': 'm-' + digest.hexdigest()[:30], 'type': kind, 'key': key, 'at': max(0, int(at)), 'payload': payload}


def _watch_ops(root, offset):
    ops = []
    rows = [dict(r, media='movie', key=hooks.watch_key('movie', r['tmdb_id'])) for r in _rows(root, 'SELECT * FROM movie_state')]
    rows += [dict(r, media='tv', key=hooks.watch_key('tv', r['show_id'], r['season'], r['episode']))
             for r in _rows(root, 'SELECT * FROM episode_state')]
    for row in rows:
        at = int(row.get('last_played_at') or 0) * 1000 + offset if row.get('last_played_at') else 0
        source = {'ident': row.get('last_ident'), 'provider': row.get('last_provider'), 'file_name': row.get('last_file_name')}
        resume = float(row.get('resume_pos') or 0)
        if int(row.get('playcount') or 0) > 0:
            ops.append(_op('watched', row['key'], at - 1 if resume > 0 and at else at, source))
        if resume > 0:
            ops.append(_op('progress', row['key'], at, dict(source, pos=resume, total=float(row.get('resume_total') or 0))))
    return ops


def _list_ops(root, offset):
    ops = []
    for row in _rows(root, 'SELECT media_type, tmdb_id, list_added_at FROM titles WHERE in_list=1 ORDER BY list_pos'):
        added = int(row.get('list_added_at') or 0)
        ops.append(_op('list_set', '{}:{}'.format(row['media_type'], int(row['tmdb_id'])), added * 1000 + offset if added else 0,
                       {'in_list': True, 'pos': None, 'added_at': added or None}))
    return ops


def _mtime_ms(path):
    newest = 0.0
    if os.path.isdir(path):
        for name in os.listdir(path):
            newest = max(newest, os.path.getmtime(os.path.join(path, name)))
    elif os.path.isfile(path):
        newest = os.path.getmtime(path)
    return int(newest * 1000)


def _remap(email, local_uuid):
    return str(uuid.uuid5(uuid.NAMESPACE_URL, 'milionar-account:{}:{}'.format((email or '').lower(), local_uuid)))


def _channel_ops(root, email, offset):
    files = _files(root)
    channels = {}
    for key, value in _channels(root).items():
        channels[_remap(email, key)] = dict(value, pos=int(value.get('pos') or 0) + POS_AFTER)
    progress = {}
    for key, value in docs._progress_local(files).items():
        channel, rest = key.split(':', 1)
        if _remap(email, channel) in channels:
            progress['{}:{}'.format(_remap(email, channel), rest)] = value
    at = max(_mtime_ms(os.path.join(files, name)) for name in docs.CHANNEL_FILES.values()) + offset
    ops = docs.diff_ops('channel', {}, channels, at)
    history_at = max(_mtime_ms(os.path.join(files, name)) for name in docs.HISTORY_DIRS.values()) + offset
    ops += docs.diff_ops('channel_progress', {}, progress, history_at or at)
    return [_op(o['type'], o['key'], o['at'], o['payload']) for o in ops]


def ops(root=None, email=None, offset=0):
    """Every op of the merge, in an order the server can apply (channels before their items and progress)."""
    root = root or backup_dir()
    return _list_ops(root, offset) + _watch_ops(root, offset) + _channel_ops(root, email, offset)


def enqueue(root=None):
    """Queue the merge into the outbox of the signed-in account; returns the number of new ops."""
    import xbmcaddon
    from wcs.library2 import store
    addon = xbmcaddon.Addon(state.ADDON_ID)
    with store.tx() as conn:
        merged = ops(root, addon.getSetting(state.EMAIL), hooks.offset_ms(conn))
        before = conn.execute('SELECT COUNT(*) FROM sync_outbox').fetchone()[0]
        for op in merged:
            conn.execute('INSERT OR IGNORE INTO sync_outbox(op_id, type, key, at, payload) VALUES(?,?,?,?,?)',
                         (op['op_id'], op['type'], op['key'], op['at'], json.dumps(op['payload'], ensure_ascii=False)))
        added = conn.execute('SELECT COUNT(*) FROM sync_outbox').fetchone()[0] - before
    hooks.committed()
    return added


def pending():
    """Merge ops still waiting in the outbox."""
    from wcs.library2 import store
    conn = store.connect()
    try:
        return conn.execute("SELECT COUNT(*) FROM sync_outbox WHERE op_id LIKE 'm-%'").fetchone()[0]
    finally:
        conn.close()
