# -*- coding: utf-8 -*-
"""Convergence and invariants of one simulator run (WEB docs/plan/account-sync/03-architecture.md §6).

`ops` is every op the actors produced: {'src', 'type', 'key', 'at', 'payload'} with the `at` the device stamped
(after its server-time correction) or the `at` the server stored for a web write. Clock correction is only as good as
the network (a delayed answer skews the learned offset by the delay), so two ops on one key closer than TOL_MS are
"concurrent": either may win. Everything else must be exact."""
TOL_MS = 1500
POSITION_OPS = ('progress', 'watched', 'unwatched', 'clear_resume', 'mark')
RESET_OPS = ('unwatched',)


def diff(left, right, path=''):
    """Human-readable differences of two dumps."""
    out = []
    if isinstance(left, dict) and isinstance(right, dict):
        for key in sorted(set(left) | set(right), key=str):
            if key not in left:
                out.append('{}/{}: missing left, right={}'.format(path, key, right[key]))
            elif key not in right:
                out.append('{}/{}: left={}, missing right'.format(path, key, left[key]))
            else:
                out += diff(left[key], right[key], '{}/{}'.format(path, key))
    elif left != right:
        out.append('{}: {} != {}'.format(path, left, right))
    return out


def server_watch(web):
    rows = web.db('SELECT media_type, tmdb_id, season, episode, playcount, watched, position, at, last_ident FROM watch_state '
                  'WHERE user_id={}'.format(web.uid()))
    out = {}
    for r in rows:
        key = 'movie:{}'.format(r['tmdb_id']) if r['media_type'] == 'movie' else 'tv:{}:{}:{}'.format(
            r['tmdb_id'], r['season'], r['episode'])
        out[key] = (max(r['playcount'], r['watched']), round(r['position'], 1))
        RAW[key] = (r['at'] % 1000000, r['last_ident'])
    return out


RAW = {}


def dump_watch(dump):
    out = {'movie:{}'.format(k): tuple(v) for k, v in dump['movies'].items()}
    out.update({'tv:{}'.format(k): tuple(v) for k, v in dump['episodes'].items()})
    return out


def watch_ops(ops):
    """{watch key: [ops]}, a device reset (key 'user') applies to every key."""
    by_key, resets = {}, []
    for op in ops:
        if op['type'] == 'reset_watch':
            resets.append(op)
        elif op['type'] in POSITION_OPS:
            by_key.setdefault(op['key'], []).append(op)
    return by_key, resets


def check_watch(ops, final):
    errors = []
    by_key, resets = watch_ops(ops)
    for key, items in by_key.items():
        playcount, position = final.get(key, (0, 0.0))
        events = items + [dict(r, type='reset') for r in resets]
        latest = max(e['at'] for e in events)
        candidates = set()
        for e in events:
            if e['at'] >= latest - TOL_MS:
                candidates.add(round(float(e['payload'].get('pos') or 0), 1) if e['type'] == 'progress' else 0.0)
        if position not in candidates:
            errors.append('stale wins {}: position {} not in {} (ops {}, row {})'.format(key, position, sorted(candidates), _short(events), RAW.get(key)))
        reset_at = max([e['at'] for e in events if e['type'] in RESET_OPS + ('reset',)] or [-1])
        plays = [e for e in items if e['type'] == 'watched']
        must = sum(1 for e in plays if e['at'] > reset_at + TOL_MS)
        marks = any(e['type'] == 'mark' for e in items)
        upper = len(plays) + (1 if marks else 0)
        if playcount < must:
            errors.append('watched lost {}: playcount {} < {} plays after the last reset'.format(key, playcount, must))
        if playcount > upper:
            errors.append('phantom play {}: playcount {} > {} plays'.format(key, playcount, upper))
        if reset_at < 0 and not marks and playcount != len(plays):
            errors.append('play count {}: {} != {} plays (duplicate or lost)'.format(key, playcount, len(plays)))
    return errors


def check_lists(ops, dump):
    errors = []
    by_key = {}
    for op in ops:
        if op['type'] == 'list_set':
            by_key.setdefault(op['key'], []).append(op)
    final = set(dump['lists'])
    for key, items in by_key.items():
        latest = max(o['at'] for o in items)
        candidates = {bool(o['payload'].get('in_list')) for o in items if o['at'] >= latest - TOL_MS}
        if (key in final) not in candidates:
            errors.append('stale wins list {}: in_list={} (ops {})'.format(key, key in final, _short(items)))
    return errors


def check_channels(ops, dump, web):
    errors = []
    deleted = {o['key'] for o in ops if o['type'] == 'channel_delete'}
    server = {c['uuid'] for c in web.channels()}
    for uuid_ in deleted:
        if uuid_ in server:
            errors.append('deleted channel back on the server: {}'.format(uuid_))
        if uuid_ in dump['channels']:
            errors.append('deleted channel back on a device: {}'.format(uuid_))
    return errors


def _short(events):
    return [(e.get('src'), e['type'], e['at'] % 1000000, e['payload'].get('pos', e['payload'].get('in_list'))) for e in sorted(events, key=lambda e: e['at'])]


def check_all(ops, dumps, reference, statuses, web):
    """Returns a list of failure strings (empty = this seed passed)."""
    errors = []
    for name, status in statuses.items():
        if status['outbox']:
            errors.append('{}: outbox not empty ({})'.format(name, status['outbox']))
        if status['journal']:
            errors.append('{}: switch journal left: {}'.format(name, status['journal']))
        if not status['signed_in']:
            errors.append('{}: not signed in at the end'.format(name))
    for name, dump in dumps.items():
        for line in diff(dump, reference)[:12]:
            errors.append('{} != fresh device: {}'.format(name, line))
    server = server_watch(web)
    server = {k: v for k, v in server.items() if v != (0, 0.0)}
    for line in diff(dump_watch(reference), server)[:12]:
        errors.append('fresh device != server watch: {}'.format(line))
    errors += check_watch(ops, server)
    errors += check_lists(ops, reference)
    errors += check_channels(ops, reference, web)
    return errors
