"""Tests for SparkSession creation and basic API."""
import pytest
from singlespark import SparkSession, SparkConf, Row


@pytest.fixture(autouse=True)
def cleanup():
    yield
    # Ensure no session leaks between tests
    if SparkSession._active:
        SparkSession._active.stop()


def test_builder_getorcreate():
    spark = SparkSession.builder.appName("test").getOrCreate()
    assert spark is not None
    assert spark.version.startswith("3.")


def test_builder_singleton():
    s1 = SparkSession.builder.appName("app1").getOrCreate()
    s2 = SparkSession.builder.appName("app2").getOrCreate()
    assert s1 is s2


def test_stop_clears_active():
    spark = SparkSession.builder.getOrCreate()
    spark.stop()
    assert SparkSession._active is None


def test_get_active_session():
    assert SparkSession.getActiveSession() is None
    spark = SparkSession.builder.getOrCreate()
    assert SparkSession.getActiveSession() is spark


def test_version():
    spark = SparkSession.builder.getOrCreate()
    assert "singlespark" in spark.version


def test_context_manager():
    with SparkSession.builder.create() as spark:
        assert spark is not None
    assert SparkSession._active is None


def test_range():
    spark = SparkSession.builder.getOrCreate()
    df = spark.range(5)
    assert df.count() == 5
    assert "id" in df.columns


def test_range_with_start_end():
    spark = SparkSession.builder.getOrCreate()
    df = spark.range(2, 8)
    rows = df.collect()
    assert rows[0]["id"] == 2
    assert rows[-1]["id"] == 7


def test_sparkconf():
    conf = SparkConf().set("spark.app.name", "test").set("spark.master", "local")
    assert conf.get("spark.app.name") == "test"
    assert conf.contains("spark.master")
    assert not conf.contains("spark.nonexistent")
