"""Tests for SQLAdapter.execute() — verifies that a SELECT query returns
formatted rows as a list of dictionaries keyed by column name."""

import os
import sqlite3
import tempfile

import pytest

from runtime.adapters.sql import SQLAdapter


@pytest.fixture()
def sample_db(tmp_path):
    """Create a temporary SQLite database with sample data."""
    db_path = str(tmp_path / "test.db")
    conn = sqlite3.connect(db_path)
    conn.execute(
        "CREATE TABLE users ("
        "  id INTEGER PRIMARY KEY,"
        "  name TEXT NOT NULL,"
        "  email TEXT NOT NULL"
        ")"
    )
    conn.executemany(
        "INSERT INTO users (id, name, email) VALUES (?, ?, ?)",
        [
            (1, "Alice", "alice@example.com"),
            (2, "Bob", "bob@example.com"),
            (3, "Charlie", "charlie@example.com"),
        ],
    )
    conn.commit()
    conn.close()
    return db_path


class TestSQLAdapterExecuteSelect:
    """Test that execute() with a _select tool returns formatted rows."""

    def test_select_returns_all_rows(self, sample_db):
        adapter = SQLAdapter(sample_db)
        result = adapter.execute("users_select", {})

        assert result["status"] == "ok"
        rows = result["result"]
        assert len(rows) == 3
        assert all(isinstance(r, dict) for r in rows)

    def test_select_rows_have_correct_keys(self, sample_db):
        adapter = SQLAdapter(sample_db)
        result = adapter.execute("users_select", {})

        rows = result["result"]
        for row in rows:
            assert set(row.keys()) == {"id", "name", "email"}

    def test_select_rows_contain_expected_data(self, sample_db):
        adapter = SQLAdapter(sample_db)
        result = adapter.execute("users_select", {})

        rows = result["result"]
        names = [r["name"] for r in rows]
        assert "Alice" in names
        assert "Bob" in names
        assert "Charlie" in names

    def test_select_row_values_match(self, sample_db):
        adapter = SQLAdapter(sample_db)
        result = adapter.execute("users_select", {"where": "id = 1"})

        assert result["status"] == "ok"
        rows = result["result"]
        assert len(rows) == 1
        assert rows[0] == {"id": 1, "name": "Alice", "email": "alice@example.com"}

    def test_select_with_limit(self, sample_db):
        adapter = SQLAdapter(sample_db)
        result = adapter.execute("users_select", {"limit": 2})

        assert result["status"] == "ok"
        assert len(result["result"]) == 2

    def test_select_with_order_by(self, sample_db):
        adapter = SQLAdapter(sample_db)
        result = adapter.execute("users_select", {"order_by": "name"})

        assert result["status"] == "ok"
        names = [r["name"] for r in result["result"]]
        assert names == ["Alice", "Bob", "Charlie"]

    def test_select_empty_result(self, sample_db):
        adapter = SQLAdapter(sample_db)
        result = adapter.execute("users_select", {"where": "id = 999"})

        assert result["status"] == "ok"
        assert result["result"] == []

    def test_unknown_tool_returns_error(self, sample_db):
        adapter = SQLAdapter(sample_db)
        result = adapter.execute("nonexistent_select", {})

        assert result["status"] == "error"
        assert "Unknown tool" in result["result"]
