"""Tests for sync scheduler."""
import asyncio

import pytest

from greymatter_core.db import SQLiteDatabase
from greymatter_core.schema.migrations import apply_all
from greymatter_core.sync.scheduler import SyncScheduler
from greymatter_core.sync.tracking import install_sqlite_triggers


def _make_db():
    d = SQLiteDatabase(":memory:")
    apply_all(d)
    install_sqlite_triggers(d)
    return d


class TestSyncScheduler:
    def test_initial_state(self):
        local = _make_db()
        remote = _make_db()
        scheduler = SyncScheduler(local, remote)
        assert not scheduler.is_running
        assert scheduler.sync_count == 0
        assert scheduler.last_result is None

    def test_set_idle_changes_interval(self):
        local = _make_db()
        remote = _make_db()
        scheduler = SyncScheduler(local, remote, active_interval=10, idle_interval=60)
        assert scheduler.current_interval == 10
        scheduler.set_idle(True)
        assert scheduler.current_interval == 60
        scheduler.set_idle(False)
        assert scheduler.current_interval == 10

    @pytest.mark.asyncio
    async def test_start_stop(self):
        local = _make_db()
        remote = _make_db()
        scheduler = SyncScheduler(local, remote, active_interval=0.1)
        await scheduler.start()
        assert scheduler.is_running
        await scheduler.stop()
        assert not scheduler.is_running

    @pytest.mark.asyncio
    async def test_sync_now(self):
        local = _make_db()
        remote = _make_db()
        local.execute(
            "INSERT INTO patterns (id, type, domain, title, observation) "
            "VALUES (?, ?, ?, ?, ?)",
            ("p-1", "process", "testing", "Test", "Obs"),
        )
        scheduler = SyncScheduler(local, remote)
        result = await scheduler.sync_now()
        assert result.success
        assert result.rows_pushed >= 1
        assert scheduler.sync_count == 1

    @pytest.mark.asyncio
    async def test_callback_fires(self):
        local = _make_db()
        remote = _make_db()
        results = []
        scheduler = SyncScheduler(
            local, remote, on_sync_complete=lambda r: results.append(r)
        )
        await scheduler.sync_now()
        assert len(results) == 1
        assert results[0].success
