"""SQLite metadata store implementation.

Thin wrapper around ``_SQLAlchemyMetadataStoreBase`` that validates the
connection string and defaults to the configured database URL.
"""

from __future__ import annotations

import logging
from pathlib import Path

from pycharter.metadata_store._sqlalchemy_base import _SQLAlchemyMetadataStoreBase

logger = logging.getLogger(__name__)

try:
    from pycharter.config import get_database_url
except ImportError:

    def get_database_url() -> str | None:  # type: ignore[misc]
        """Stub when config module is unavailable."""
        return None


class SQLiteMetadataStore(_SQLAlchemyMetadataStoreBase):
    """SQLite-backed metadata store.

    Connection string format: ``sqlite:///path/to/database.db``
    or ``sqlite:///:memory:`` for in-memory databases.

    Usage::

        store = SQLiteMetadataStore("sqlite:///pycharter.db")
        store.connect()  # validates schema exists

    If *connection_string* is ``None``, resolves from env / config.
    """

    def __init__(self, connection_string: str | None = None) -> None:
        resolved = connection_string or get_database_url()
        if not resolved:
            raise ValueError(
                "connection_string is required. Provide it directly, or configure it via:\n"
                "  - Environment variable: PYCHARTER_DATABASE_URL\n"
                "  - Config file: pycharter.cfg [database] PYCHARTER_DATABASE_URL\n"
                "  - Config file: alembic.ini sqlalchemy.url"
            )
        if not resolved.startswith("sqlite://"):
            raise ValueError(
                f"SQLiteMetadataStore requires a sqlite:// URL, got: {resolved!r}"
            )
        # Ensure parent directory exists for file-based databases.
        if resolved.startswith("sqlite:///"):
            db_path = resolved[len("sqlite:///") :]
            if db_path != ":memory:":
                db_file = Path(db_path)
                db_file.parent.mkdir(parents=True, exist_ok=True)
        super().__init__(resolved)

    def connect(
        self,
        validate_schema_on_connect: bool = True,
        auto_initialize: bool = False,
    ) -> None:
        """Connect to the SQLite database.

        Args:
            validate_schema_on_connect: Check that required tables exist.
            auto_initialize: Create tables if missing (default ``False`` —
                use ``pycharter db init`` for production).
        """
        self._connect_engine(
            schema_name=None,
            validate_schema=validate_schema_on_connect,
            auto_initialize=auto_initialize,
        )
