"""Tests for CockroachDatabase placeholder conversion and import guard.

Full integration tests require a running CockroachDB instance.
These unit tests focus on the placeholder conversion logic and
import error handling.
"""
import pytest

from greymatter_core.db import CockroachDatabase, PSYCOPG2_AVAILABLE


class TestPlaceholderConversion:
    """Test the ? → %s placeholder conversion."""

    def test_simple_replacement(self):
        result = CockroachDatabase._convert_placeholders(
            "SELECT * FROM t WHERE id = ? AND name = ?"
        )
        assert result == "SELECT * FROM t WHERE id = %s AND name = %s"

    def test_no_placeholders(self):
        query = "SELECT * FROM t"
        result = CockroachDatabase._convert_placeholders(query)
        assert result == query

    def test_preserves_single_quoted_strings(self):
        result = CockroachDatabase._convert_placeholders(
            "SELECT * FROM t WHERE name = '?' AND id = ?"
        )
        assert result == "SELECT * FROM t WHERE name = '?' AND id = %s"

    def test_preserves_double_quoted_strings(self):
        result = CockroachDatabase._convert_placeholders(
            'SELECT * FROM t WHERE "col?" = ?'
        )
        assert result == 'SELECT * FROM t WHERE "col?" = %s'

    def test_mixed_quoted_and_unquoted(self):
        result = CockroachDatabase._convert_placeholders(
            "INSERT INTO t (a, b, c) VALUES (?, '?', ?)"
        )
        assert result == "INSERT INTO t (a, b, c) VALUES (%s, '?', %s)"

    def test_empty_query(self):
        assert CockroachDatabase._convert_placeholders("") == ""

    def test_datetime_function_preserved(self):
        result = CockroachDatabase._convert_placeholders(
            "SELECT * FROM t WHERE created_at > datetime('now', '-3 days') AND id = ?"
        )
        # The ? inside datetime('now', '-3 days') should not be converted
        # because there is no ? inside the single quotes
        assert result.endswith("AND id = %s")

    def test_on_conflict_pattern(self):
        result = CockroachDatabase._convert_placeholders(
            "INSERT INTO t (id, val) VALUES (?, ?) ON CONFLICT (id) DO NOTHING"
        )
        assert result == "INSERT INTO t (id, val) VALUES (%s, %s) ON CONFLICT (id) DO NOTHING"


@pytest.mark.skipif(not PSYCOPG2_AVAILABLE, reason="psycopg2 not installed")
class TestCockroachDatabaseInit:
    """Tests that require psycopg2 to be installed (but not a running CRDB)."""

    def test_init_with_bad_url_raises(self):
        """Connecting to a non-existent host should raise."""
        with pytest.raises(Exception):
            CockroachDatabase("postgresql://root@localhost:99999/nonexistent")

    def test_static_method_accessible(self):
        """_convert_placeholders is callable without an instance."""
        result = CockroachDatabase._convert_placeholders("SELECT ?")
        assert result == "SELECT %s"


@pytest.mark.skipif(PSYCOPG2_AVAILABLE, reason="Test only relevant when psycopg2 missing")
class TestCockroachDatabaseNoPsycopg2:
    """Tests for graceful degradation when psycopg2 is not installed."""

    def test_init_raises_import_error(self):
        with pytest.raises(ImportError, match="psycopg2"):
            CockroachDatabase("postgresql://root@localhost:26257/greymatter")
