"""PostgreSQL metadata store implementation.

Thin wrapper around ``_SQLAlchemyMetadataStoreBase`` that validates the
connection string and sets the ``pycharter`` schema.
"""

from __future__ import annotations

import logging

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 PostgresMetadataStore(_SQLAlchemyMetadataStoreBase):
    """PostgreSQL-backed metadata store.

    Stores metadata in PostgreSQL tables within the ``pycharter`` schema.

    Usage::

        store = PostgresMetadataStore("postgresql://user:pass@localhost/pycharter")
        store.connect()

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

    def __init__(
        self,
        connection_string: str | None = None,
        schema_name: str = "pycharter",
    ) -> 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(("postgresql://", "postgres://")):
            raise ValueError(
                f"PostgresMetadataStore requires a postgresql:// URL, got: {resolved!r}"
            )
        super().__init__(resolved)
        self._pg_schema_name = schema_name

    def connect(
        self,
        validate_schema_on_connect: bool = True,
        auto_initialize: bool = False,
    ) -> None:
        """Connect to the PostgreSQL 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 PostgreSQL).
        """
        self._connect_engine(
            schema_name=self._pg_schema_name,
            validate_schema=validate_schema_on_connect,
            auto_initialize=auto_initialize,
        )
