#!/usr/bin/env python3
"""Merge at sign-in (WEB docs/plan/account-sync S28, T37, phase A12) end to end: a Kodi with its own data signs in to
an account that another device already uses, chooses „Sloučit s účtem“, and the account gets the union by the sync's
rules. Starts its own harness backend (WEB scripts/harness/sync-backend.ts) on --port 5249 and stops it.

python3 -B scripts/account_harness/test_merge.py"""
import json
import os
import subprocess
import sys
import unittest
import urllib.parse
import uuid

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import sim  # noqa: E402
from sim_actors import http_json  # noqa: E402

PORT = 5249
SERVER, HELPER = 'http://127.0.0.1:{}/'.format(PORT), 'http://127.0.0.1:{}'.format(PORT + 1)
CHANNEL = '21664483-2472-4a4b-a37b-000000000001'


class Proc(object):
    def __init__(self):
        self.p = subprocess.Popen([sys.executable, '-B', os.path.join(HERE, 'device_proc.py'), SERVER, HELPER],
                                  stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)

    def __getattr__(self, name):
        def call(*args):
            self.p.stdin.write(json.dumps({'method': name, 'args': list(args)}) + '\n')
            self.p.stdin.flush()
            answer = json.loads(self.p.stdout.readline())
            if not answer['ok']:
                raise AssertionError(answer['error'] + '\n' + answer.get('trace', ''))
            return answer['result']
        return call

    def close(self):
        self.p.stdin.close()
        self.p.wait(10)


def db(sql):
    return http_json(HELPER + '/db?sql=' + urllib.parse.quote(sql))


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


class MergeAtSignIn(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.backend = sim.start_backend(PORT, 10)

    @classmethod
    def tearDownClass(cls):
        cls.backend.terminate()
        try:
            cls.backend.wait(timeout=10)
        except Exception:
            cls.backend.kill()

    def setUp(self):
        self.email = 'merge-{}@harness.test'.format(uuid.uuid4().hex[:8])
        http_json(HELPER + '/user', {'email': self.email, 'name': 'Merge'})
        self.kodi, self.other = Proc(), Proc()
        self.addCleanup(self.kodi.close)
        self.addCleanup(self.other.close)

    def sync_until_sent(self, device):
        for _ in range(10):
            if device.sync()['outbox'] == 0:
                return
        self.fail('the outbox did not empty')

    def test_merge_adds_the_kodi_data_by_the_sync_rules(self):
        kodi, other = self.kodi, self.other
        # this Kodi's own data, before it ever signs in
        kodi.progress('movie', 501, 600, 6000)
        kodi.watched('movie', 502)
        kodi.list_add('movie', 503)
        kodi.list_add('tv', 601)
        kodi.progress('tv', 602, 120, 1500, 1, 2)
        kodi.channel(CHANNEL, 'Kodi kanál', [{'id': 1668, 'name': 'Friends'}], 'tv')
        kodi.channel_progress(CHANNEL, 'tv', 1668, {'season': 1, 'episode': 2, 'watched': False}, 'tv')
        # the account, used by another device afterwards: a newer position of 501, 503 added and removed again, 504
        self.assertTrue(other.pair(self.email))
        other.progress('movie', 501, 900, 6000)
        other.list_add('movie', 503)
        other.list_add('movie', 503, False)
        other.list_add('movie', 504)
        self.sync_until_sent(other)

        self.assertTrue(kodi.pair(self.email))
        counts = kodi.merge_summary()
        self.assertEqual(counts, {'movies': 1, 'series': 1, 'in_progress': 2, 'watched': 1, 'mytv': 1, 'mycinema': 0})
        self.assertGreater(kodi.merge(), 0)
        self.sync_until_sent(kodi)
        kodi.sync()
        other.sync()

        for state in (other.dump(), kodi.dump()):
            self.assertEqual(state['movies'].get('501'), [0, 900.0], 'the newer position of the account wins')
            self.assertEqual(state['movies'].get('502'), [1, 0.0], 'a watched of the Kodi is never lost')
            self.assertEqual(state['episodes'].get('602:1:2'), [0, 120.0])
            self.assertIn('tv:601', state['lists'])
            self.assertIn('movie:504', state['lists'])
            self.assertNotIn('movie:503', state['lists'], 'removed in the account after the Kodi added it: stays removed')
            self.assertEqual(state['channels'].get(remapped(self.email, CHANNEL)), ['tv', 'Kodi kanál', ['1668']])
        progress = db("SELECT c.uuid AS uuid, p.tmdb_id AS tmdb FROM channel_progress p JOIN channels c ON c.id = p.channel_id "
                      "JOIN users u ON u.id = p.user_id WHERE u.email = '{}'".format(self.email))
        self.assertEqual(progress, [{'uuid': remapped(self.email, CHANNEL), 'tmdb': 1668}])

        # the same data merged again (sign-out, sign-in, „Sloučit“ again) changes nothing: the server answers duplicate
        before = db("SELECT w.tmdb_id, w.playcount, w.position FROM watch_state w JOIN users u ON u.id = w.user_id "
                    "WHERE u.email = '{}' ORDER BY w.tmdb_id, w.episode".format(self.email))
        kodi.merge()
        self.sync_until_sent(kodi)
        after = db("SELECT w.tmdb_id, w.playcount, w.position FROM watch_state w JOIN users u ON u.id = w.user_id "
                   "WHERE u.email = '{}' ORDER BY w.tmdb_id, w.episode".format(self.email))
        self.assertEqual(after, before)

    def test_nothing_to_offer_without_own_data(self):
        self.assertTrue(self.kodi.pair(self.email))
        self.assertEqual(sum(self.kodi.merge_summary().values()), 0)


if __name__ == '__main__':
    unittest.main()
