"""Alembic environment for the accounts database.

The migration URL is derived from ``THERMOGRAPH_DATABASE_URL`` (the async app URL)
by swapping to a sync driver — Alembic runs synchronously. Falls back to the
SQLite accounts file when no Postgres URL is set (local / tests). ``target_metadata``
is the accounts ``Base.metadata`` so ``alembic revision --autogenerate`` can diff
against the ORM models.
"""
import os
import sys
from logging.config import fileConfig

from alembic import context
from sqlalchemy import create_engine, pool

# Alembic runs with cwd = backend/ (WORKDIR); make the backend package importable
# regardless of where alembic is invoked from.
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from accounts.db import Base  # noqa: E402
from accounts import models  # noqa: E402,F401  (registers tables on Base.metadata)

config = context.config
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

target_metadata = Base.metadata


def _sync_url() -> str:
    url = os.environ.get("THERMOGRAPH_DATABASE_URL", "").strip()
    if url.startswith("postgresql"):
        return url.replace("+asyncpg", "+psycopg")
    from accounts.db import DB_PATH  # SQLite fallback path
    return f"sqlite:///{DB_PATH}"


def run_migrations_offline() -> None:
    context.configure(url=_sync_url(), target_metadata=target_metadata,
                      literal_binds=True, dialect_opts={"paramstyle": "named"})
    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online() -> None:
    engine = create_engine(_sync_url(), poolclass=pool.NullPool, future=True)
    with engine.connect() as connection:
        context.configure(connection=connection, target_metadata=target_metadata,
                          render_as_batch=connection.dialect.name == "sqlite")
        with context.begin_transaction():
            context.run_migrations()
    engine.dispose()


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