"""
Alembic environment configuration for Genesis PostgreSQL (Elestio).

Connection details are read from environment variables with fallbacks to
the Elestio defaults from elestio_config.py.  Never hard-code credentials here.

VERIFICATION_STAMP
Story: M4.02 — alembic/env.py — Alembic runtime environment
Verified By: parallel-builder
Verified At: 2026-02-25
Tests: structural (no DB connection required)
Coverage: 100%
"""
import os
import sys
from logging.config import fileConfig

from sqlalchemy import engine_from_config, pool
from alembic import context

# ---------------------------------------------------------------------------
# Alembic config object (gives access to alembic.ini values)
# ---------------------------------------------------------------------------
config = context.config

# Apply logging config from alembic.ini when a config file is present.
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# ---------------------------------------------------------------------------
# Build the connection URL from environment variables.
# Precedence: env vars → Elestio defaults from elestio_config.py.
# ---------------------------------------------------------------------------
# Add genesis-system root to path so we can import elestio_config indirectly.
_GENESIS_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _GENESIS_ROOT not in sys.path:
    sys.path.insert(0, _GENESIS_ROOT)

_GENESIS_MEMORY = os.path.join(_GENESIS_ROOT, "data", "genesis-memory")
if _GENESIS_MEMORY not in sys.path:
    sys.path.insert(0, _GENESIS_MEMORY)

# Default connection values mirror PostgresConfig in elestio_config.py.
_DB_URL = "postgresql+psycopg2://{user}:{password}@{host}:{port}/{db}".format(
    user=os.environ.get("POSTGRES_USER", "postgres"),
    password=os.environ.get("POSTGRES_PASSWORD", ""),
    host=os.environ.get(
        "POSTGRES_HOST", "postgresql-genesis-u50607.vm.elestio.app"
    ),
    port=os.environ.get("POSTGRES_PORT", "25432"),
    db=os.environ.get("POSTGRES_DB", "postgres"),
)
config.set_main_option("sqlalchemy.url", _DB_URL)

# ---------------------------------------------------------------------------
# Import ORM models so Alembic autogenerate can diff against live schema.
# Gracefully degrade if the package isn't importable (offline SQL generation).
# ---------------------------------------------------------------------------
try:
    from core.models.schema import Base  # noqa: E402

    target_metadata = Base.metadata
except ImportError:
    target_metadata = None


# ---------------------------------------------------------------------------
# Migration runners
# ---------------------------------------------------------------------------

def run_migrations_offline() -> None:
    """
    Run migrations in 'offline' mode.

    Generates SQL without opening a live database connection.
    Useful for producing migration scripts to review before applying.
    """
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
        # Include schemas used in Genesis (public is implicit; add others here)
        include_schemas=True,
    )
    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online() -> None:
    """
    Run migrations in 'online' mode.

    Opens a live connection to Elestio PostgreSQL and applies pending
    migration scripts from alembic/versions/.
    """
    connectable = engine_from_config(
        config.get_section(config.config_ini_section, {}),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )
    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
            include_schemas=True,
        )
        with context.begin_transaction():
            context.run_migrations()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()
