#!/usr/bin/env python3
"""One headless Kodi device running the real wcs.account + wcs.library2 code (docs/plan/milionar-account/060 §2).

Library mode for the simulator and tests:
    import client; dev = client.Device(server='http://127.0.0.1:5239/', helper='http://127.0.0.1:5240')
    dev.pair('A'); dev.progress('movie', 603, 600, 6000); dev.sync(); dev.dump()

Each Device lives in its own process (the Kodi stubs and module globals are per process). Run with python3 -B.
Simulator (A09) environment:
  SIM_PROFILE=<dir>   a fixed profile: the settings live in <dir>/settings.json, so a killed process restarts with
                      its data, settings and switch journal (Kodi keeps settings on disk too)
  SIM_CLOCK=<offset_ms>,<drift_ppm>   this device's wall clock is wrong by offset and runs fast/slow by drift
"""
import json
import os
import sys
import time
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
ADDON = os.path.abspath(os.path.join(HERE, '..', '..'))
KODI_ADDONS = os.path.dirname(ADDON)
for module in ('script.module.requests', 'script.module.urllib3', 'script.module.chardet', 'script.module.idna',
               'script.module.certifi'):
    path = os.path.join(KODI_ADDONS, module, 'lib')
    if os.path.isdir(path) and path not in sys.path:
        sys.path.insert(0, path)
sys.path.insert(0, os.path.join(ADDON, 'scripts', 'library_harness'))
sys.path.insert(0, ADDON)


def _skew_clock(spec):
    offset_ms, drift_ppm = (float(x) for x in spec.split(','))
    real = time.time
    start = real()

    def skewed():
        now = real()
        return now + offset_ms / 1000.0 + (now - start) * drift_ppm / 1e6
    time.time = skewed


if os.environ.get('SIM_CLOCK'):
    _skew_clock(os.environ['SIM_CLOCK'])

import stubs  # noqa: E402

PROFILE = stubs.install()
if os.environ.get('SIM_PROFILE'):
    PROFILE = stubs.PROFILE = os.environ['SIM_PROFILE']
    os.makedirs(PROFILE, exist_ok=True)
import xbmcaddon  # noqa: E402


class PersistentSettings(dict):
    """The stub's settings, written through to a file like Kodi's settings.xml."""

    def __init__(self, path):
        super(PersistentSettings, self).__init__()
        self.path = path
        if os.path.exists(path):
            with open(path, encoding='utf-8') as handle:
                dict.update(self, json.load(handle))

    def _save(self):
        tmp = self.path + '.tmp'
        with open(tmp, 'w', encoding='utf-8') as handle:
            json.dump(dict(self), handle)
        os.replace(tmp, self.path)

    def __setitem__(self, key, value):
        dict.__setitem__(self, key, value)
        self._save()

    def update(self, *args, **kwargs):
        dict.update(self, *args, **kwargs)
        self._save()


if os.environ.get('SIM_PROFILE'):
    xbmcaddon.Addon.settings = PersistentSettings(os.path.join(PROFILE, 'settings.json'))


def _post(url, body):
    request = urllib.request.Request(url, data=json.dumps(body).encode(), headers={'content-type': 'application/json'})
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.loads(response.read().decode() or 'null')


SIM_SETTINGS = ('mytv_upcoming_count', 'autoplay_first_item_delay')


class Device(object):
    def __init__(self, server, helper):
        self.helper = helper.rstrip('/')
        if xbmcaddon.Addon.settings.get('account_server') != server:
            xbmcaddon.Addon.settings['account_server'] = server
        if xbmcaddon.Addon.settings.get('webshare_enabled') != 'true':
            xbmcaddon.Addon.settings['webshare_enabled'] = 'true'
        from wcs.library2 import store
        store.set_path(os.path.join(PROFILE, 'library.db'))
        store.connect().close()
        self.profile = PROFILE
        from wcs.account import switch
        switch.resume_if_needed()                     # the service does this first at Kodi start

    # ------------------------------------------------------------------ account
    def pair(self, user='A'):
        from wcs.account import client, switch
        for attempt in range(20):
            try:
                _s, started = client.request('POST', 'device/pair/start', {'name': 'harness', 'platform': 'kodi', 'app_version': 'harness'}, token='')
                break
            except client.AccountError as exc:
                if exc.code != 'slow_down' or attempt == 19:
                    raise
                time.sleep(0.5)
        _post(self.helper + '/approve', {'code': started['user_code'], 'user': user})
        _s, body = client.request('POST', 'device/pair/poll', {'device_code': started['device_code']}, token='')
        return switch.signin(body['token'], body['device_id'], body['user'])

    def signout(self, push=True):
        from wcs.account import switch
        return switch.signout(push=push)

    def sync(self, rounds=3):
        """Push everything queued, then pull until idle (no long wait). Returns {outbox, ops (queued by the documents
        round), error}; network faults end the round early as they end the service's round."""
        from wcs.account import client, state, switch, sync
        result = {'ops': [], 'error': None, 'logout': False}
        if not state.signed_in():
            result['outbox'] = sync.outbox_size()
            return result
        result['push_ms'], result['pull_ms'] = [], []
        try:
            for _ in range(rounds):
                before = self._last_id()
                sync.queue_docs()
                result['ops'] += self._ops_since(before)
                while True:
                    started = time.time()
                    sent = sync.push_once()
                    if not sent:
                        break
                    result['push_ms'].append(round((time.time() - started) * 1000, 1))
                while True:
                    started = time.time()
                    outcome = sync.pull_once(0, lambda: False)
                    result['pull_ms'].append(round((time.time() - started) * 1000, 1))
                    if outcome == 'logout':
                        result['logout'] = True
                        switch.signout(push=False)
                        result['outbox'] = sync.outbox_size()
                        return result
                    if outcome != 'changes':
                        break
        except client.AccountError as exc:
            result['error'] = exc.code
        result['outbox'] = sync.outbox_size()
        return result

    def due_now(self):
        """Time passes: every queued op is due again (the back-off is over)."""
        from wcs.library2 import store
        with store.tx() as conn:
            conn.execute('UPDATE sync_outbox SET next_attempt=0')
        return True

    def status(self):
        from wcs.account import state, switch, sync
        state.invalidate()
        return {'signed_in': state.signed_in(), 'outbox': sync.outbox_size(), 'journal': switch._journal() or None,
                'name': xbmcaddon.Addon.settings.get('account_name', '')}

    # ------------------------------------------------------------------ local actions (as the addon does them)
    def _last_id(self):
        """The op ids queued now (a coalesced progress reuses the deleted row's id, so ids alone are not enough)."""
        from wcs.library2 import store
        conn = store.connect()
        try:
            return [r[0] for r in conn.execute('SELECT op_id FROM sync_outbox')]
        finally:
            conn.close()

    def _ops_since(self, before):
        from wcs.library2 import store
        known = set(before)
        conn = store.connect()
        try:
            return [{'type': r['type'], 'key': r['key'], 'at': r['at'], 'payload': json.loads(r['payload'] or '{}')}
                    for r in conn.execute('SELECT * FROM sync_outbox ORDER BY id') if r['op_id'] not in known]
        finally:
            conn.close()

    def act(self, name, *args):
        """Run one local action and return the ops it queued (empty when signed out)."""
        before = self._last_id()
        getattr(self, name)(*args)
        return self._ops_since(before)

    def progress(self, media, tmdb_id, pos, total, season=None, episode=None):
        from wcs.library2 import store
        store.save_resume('movie' if media == 'movie' else 'tv', tmdb_id, pos, total, season, episode,
                          source={'ident': 'ws-{}'.format(tmdb_id), 'provider': 'webshare', 'file_name': 'f.mkv'})

    def watched(self, media, tmdb_id, season=None, episode=None):
        from wcs.library2 import store
        store.mark_watched('movie' if media == 'movie' else 'tv', tmdb_id, season, episode)

    def unwatched(self, media, tmdb_id, season=None, episode=None):
        from wcs.library2 import store
        store.mark_unwatched('movie' if media == 'movie' else 'tv', tmdb_id, season, episode)

    def clear_resume(self, media, tmdb_id, season=None, episode=None):
        from wcs.library2 import store
        store.clear_resume('movie' if media == 'movie' else 'tv', tmdb_id, season, episode)

    def list_add(self, media, tmdb_id, on=True):
        from wcs.library2 import store
        store.set_in_list(media, tmdb_id, on)

    def hide(self, media, tmdb_id, hidden=True):
        from wcs.library2 import store
        store.set_hidden_from_continue(media, tmdb_id, hidden)

    def feedback(self, media, tmdb_id, value=None):
        from wcs.library2 import store
        store.set_feedback(media, tmdb_id, value)

    def reset(self):
        from wcs.library2 import store
        store.reset_watch_state()

    def _channels(self, kind):
        from wcs import user_data
        load = user_data.load_mytv_channels if kind == 'tv' else user_data.load_mycinema_channels
        save = user_data.store_mytv_channels if kind == 'tv' else user_data.store_mycinema_channels
        return load(None), save

    def channel(self, uuid_, name, items, kind='tv'):
        channels, save = self._channels(kind)
        channels = [c for c in channels if c.get('id') != uuid_]
        channels.append({'id': uuid_, 'name': name, 'icon': '', 'channel_type': kind, 'media_list': items, 'series_list': items})
        save(None, channels)

    def channel_rename(self, uuid_, name, kind='tv'):
        channels, save = self._channels(kind)
        for c in channels:
            if c.get('id') == uuid_:
                c['name'] = name
        save(None, channels)

    def channel_delete(self, uuid_, kind='tv'):
        channels, save = self._channels(kind)
        save(None, [c for c in channels if c.get('id') != uuid_])

    def channel_item(self, uuid_, item, on=True, kind='tv'):
        channels, save = self._channels(kind)
        for c in channels:
            if c.get('id') != uuid_:
                continue
            for field in ('media_list', 'series_list'):
                items = [i for i in c.get(field) or [] if str(i.get('id')) != str(item['id'])]
                if on:
                    items.append(item)
                c[field] = items
        save(None, channels)

    def setting(self, key, value):
        xbmcaddon.Addon.settings[key] = value

    def channel_progress(self, uuid_, media, title_id, entry, kind='tv'):
        """A MyTV / MyCinema history entry, as the channel dialogs write it (wcs/account/docs.py HISTORY_DIRS)."""
        from wcs.account import docs
        path = docs._path(docs.HISTORY_DIRS[kind], uuid_ + '.json')
        data = docs._read(path, {})
        data[str(title_id)] = entry
        docs._write(path, data)

    def merge_summary(self):
        from wcs.account import merge
        return merge.summary()

    def merge(self):
        """S28: the user chose „Sloučit s účtem“ after the sign-in."""
        from wcs.account import merge
        return merge.enqueue()

    # ------------------------------------------------------------------ state
    def dump(self):
        """The device's user data, normalised for comparison (the simulator compares devices with each other)."""
        from wcs.library2 import store
        conn = store.connect()
        try:
            movies = {str(r['tmdb_id']): [r['playcount'], round(r['resume_pos'], 1)] for r in conn.execute('SELECT * FROM movie_state')
                      if r['playcount'] or r['resume_pos']}
            episodes = {'{}:{}:{}'.format(r['show_id'], r['season'], r['episode']): [r['playcount'], round(r['resume_pos'], 1)]
                        for r in conn.execute('SELECT * FROM episode_state') if r['playcount'] or r['resume_pos']}
            lists = sorted('{}:{}'.format(r['media_type'], r['tmdb_id']) for r in conn.execute('SELECT * FROM titles WHERE in_list=1'))
            hidden = sorted('{}:{}'.format(r['media_type'], r['tmdb_id'])
                            for r in conn.execute('SELECT * FROM titles WHERE hidden_from_continue_at IS NOT NULL'))
            feedback = {'{}:{}'.format(r['media_type'], r['tmdb_id']): r['value'] for r in conn.execute('SELECT * FROM feedback')}
        finally:
            conn.close()
        channels = {}
        for kind in ('tv', 'cinema'):
            for c in self._channels(kind)[0]:
                items = c.get('media_list') if kind == 'cinema' else (c.get('series_list') or c.get('media_list'))
                channels[c.get('id')] = [kind, c.get('name'), sorted(str(i.get('id')) for i in items or [])]
        return {'movies': movies, 'episodes': episodes, 'lists': lists, 'hidden': hidden, 'feedback': feedback,
                'channels': channels, 'settings': {k: xbmcaddon.Addon.settings.get(k, '') for k in SIM_SETTINGS}}


if __name__ == '__main__':
    server, helper = sys.argv[1], sys.argv[2]
    device = Device(server, helper)
    print('paired', device.pair('A'))
    print(json.dumps(device.dump(), default=str, ensure_ascii=False)[:800])
