"""LanceDB connection management — lazy singleton."""

import lancedb

from ars25.core.config import get_settings


_connection: lancedb.DBConnection | None = None


def get_connection() -> lancedb.DBConnection:
    global _connection
    if _connection is None:
        settings = get_settings()
        _connection = lancedb.connect(settings.db_path)
    return _connection


def get_table(table_name: str | None = None) -> lancedb.table.Table:
    settings = get_settings()
    name = table_name or settings.table_name
    conn = get_connection()
    return conn.open_table(name)


def table_exists(table_name: str | None = None) -> bool:
    settings = get_settings()
    name = table_name or settings.table_name
    conn = get_connection()
    return name in conn.table_names()


def reset_connection() -> None:
    global _connection
    _connection = None
