# -*- coding: utf-8 -*-
"""The outbox reaches the server in size-limited requests and never stalls (review 2026-11-09, WEB 11-status):
a request stays under BATCH_BYTES, a 413 halves the request, one op the server can never take is dropped instead of
holding every newer op behind it, a network error keeps the ops with their back-off.

python3 -B scripts/account_harness/test_push_batch.py"""
import json
import os
import sys
import unittest
from unittest import mock

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(HERE), 'library_harness'))
import stubs  # noqa: E402

PROFILE = stubs.install()

import xbmcaddon  # noqa: E402

from wcs.account import client, state, sync  # noqa: E402
from wcs.library2 import store  # noqa: E402


class PushBatchTests(unittest.TestCase):
    def setUp(self):
        store.set_path(os.path.join(PROFILE, 'push-batch.db'))
        store.connect().close()
        with store.tx() as conn:
            conn.execute('DELETE FROM sync_outbox')
        xbmcaddon.Addon.settings[state.TOKEN] = 'device'
        state.invalidate()
        self.sent = []

    def queue(self, count, size):
        with store.tx() as conn:
            for index in range(count):
                conn.execute('INSERT INTO sync_outbox(op_id, type, key, at, payload) VALUES(?,?,?,?,?)',
                             ('op{}'.format(index), 'channel_item_set', 'c:movie:{}'.format(index), index,
                              json.dumps({'item': {'overview': 'x' * size}})))

    def server(self, limit_bytes=2 * 1024 * 1024, fail=None):
        def request(method, path, body=None, **_kwargs):
            raw = len(json.dumps(body))
            self.sent.append(len(body['ops']))
            if fail:
                raise client.AccountError(fail, 0)
            if raw > limit_bytes:
                raise client.AccountError('invalid', 413)
            return 200, {'rev': 1, 'results': [{'op_id': op['op_id'], 'status': 'applied', 'rev': 1} for op in body['ops']]}
        return mock.patch.object(client, 'request', side_effect=request)

    def test_requests_stay_under_the_byte_limit(self):
        self.queue(40, 60 * 1024)                    # 40 × 60 kB = 2.4 MB: never one request
        with self.server():
            while sync.push_once():
                pass
        self.assertEqual(sync.outbox_size(), 0)
        self.assertTrue(all(n * 60 * 1024 <= sync.BATCH_BYTES + 60 * 1024 for n in self.sent), self.sent)
        self.assertGreater(len(self.sent), 1)

    def test_413_halves_and_an_op_too_large_is_dropped(self):
        self.queue(1, 3 * 1024 * 1024)               # one op larger than the server takes
        with store.tx() as conn:
            conn.execute("INSERT INTO sync_outbox(op_id, type, key, at, payload) VALUES('after', 'list_set', 'movie:1', 9, '{}')")
        with self.server():
            while sync.push_once():
                pass
        self.assertEqual(sync.outbox_size(), 0, 'the op behind the huge one was sent')

    def test_offline_keeps_the_ops_with_back_off(self):
        self.queue(3, 10)
        with self.server(fail='offline'):
            with self.assertRaises(client.AccountError):
                sync.push_once()
        conn = store.connect()
        try:
            rows = conn.execute('SELECT attempts, next_attempt FROM sync_outbox').fetchall()
        finally:
            conn.close()
        self.assertEqual(len(rows), 3)
        self.assertTrue(all(r[0] == 1 and r[1] > 0 for r in rows))


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