"""Alembic environment configuration for LLMHosts.

Resolves the SQLite database path at runtime using the project's own
config helpers so that migrations always target the correct file
(``~/.llmhosts/llmhost.db`` by default).
"""

from __future__ import annotations

import logging
from logging.config import fileConfig

from alembic import context
from sqlalchemy import engine_from_config, pool

from llmhosts.config import llmhosts_dir
from llmhosts.constants import DB_FILENAME

# Alembic Config object -- provides access to values in alembic.ini
config = context.config

# Set up Python logging from the ini file when present.
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

logger = logging.getLogger("alembic.env")

# No SQLAlchemy MetaData for auto-generate (we manage schema manually).
target_metadata = None


def _get_url() -> str:
    """Build a ``sqlite:///`` URL pointing to the LLMHosts database."""
    db_path = llmhosts_dir() / DB_FILENAME
    return f"sqlite:///{db_path}"


def run_migrations_offline() -> None:
    """Run migrations in 'offline' mode.

    Configures the context with just a URL and not an Engine.  Calls to
    ``context.execute()`` emit the given SQL string to the script output.
    """
    url = _get_url()
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )

    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online() -> None:
    """Run migrations in 'online' mode.

    Creates a synchronous Engine and associates a connection with the
    context.  SQLite is inherently synchronous so this is the standard
    Alembic pattern.
    """
    cfg = config.get_section(config.config_ini_section, {})
    cfg["sqlalchemy.url"] = _get_url()

    connectable = engine_from_config(
        cfg,
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    with connectable.connect() as connection:
        context.configure(connection=connection, target_metadata=target_metadata)

        with context.begin_transaction():
            context.run_migrations()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()
