"""Tests for all storage backends (SQLite only by default; others need real servers)."""

import pytest
from clawid.storage import SQLiteStore, from_uri


SAMPLE = {"uid": "user123", "platform": "hawky.ai", "ts": 1711234567}


# ── SQLiteStore ───────────────────────────────────────────────────────────────

@pytest.fixture
def store():
    with SQLiteStore(":memory:") as s:
        yield s


def test_save_and_get(store):
    store.save("abc-123", SAMPLE)
    assert store.get("abc-123") == SAMPLE


def test_get_missing_returns_none(store):
    assert store.get("does-not-exist") is None


def test_exists(store):
    assert not store.exists("x")
    store.save("x", SAMPLE)
    assert store.exists("x")


def test_delete(store):
    store.save("del-me", SAMPLE)
    assert store.delete("del-me") is True
    assert store.get("del-me") is None


def test_delete_missing_returns_false(store):
    assert store.delete("no-such-id") is False


def test_update(store):
    store.save("u1", {"uid": "original"})
    store.update("u1", {"uid": "updated", "extra": "field"})
    result = store.get("u1")
    assert result["uid"] == "updated"
    assert result["extra"] == "field"


def test_update_missing_returns_false(store):
    assert store.update("ghost", {"x": 1}) is False


def test_overwrite(store):
    store.save("ow", {"v": 1})
    store.save("ow", {"v": 2})
    assert store.get("ow") == {"v": 2}


def test_context_manager():
    with SQLiteStore(":memory:") as s:
        s.save("ctx", SAMPLE)
        assert s.get("ctx") == SAMPLE


# ── from_uri factory ─────────────────────────────────────────────────────────

def test_from_uri_sqlite(tmp_path):
    path = str(tmp_path / "test.db")
    store = from_uri(f"sqlite:///{path}")
    assert isinstance(store, SQLiteStore)
    store.save("uri-test", SAMPLE)
    assert store.get("uri-test") == SAMPLE
    store.close()


def test_from_uri_memory():
    store = from_uri("sqlite:///:memory:")
    assert isinstance(store, SQLiteStore)
    store.save("mem", SAMPLE)
    assert store.get("mem") == SAMPLE
    store.close()


def test_from_uri_unknown_scheme():
    with pytest.raises(ValueError, match="Unsupported"):
        from_uri("ftp://somehost/db")
