"""
Alembic environment for PhotoVault.

Pulls DATABASE_URL from the environment so the same migrations work in
docker compose and locally. Strips the async driver suffix because Alembic
runs synchronously via psycopg2.

Future-migration note
---------------------
Fresh installs run `Base.metadata.create_all` in `app.database.init_db`
*before* migrations would normally apply, so any migration that adds a
column / index / table to an object the model already declares will see
that object already present. Write migrations defensively:

    op.execute("ALTER TABLE photos ADD COLUMN IF NOT EXISTS new_col TEXT")
    op.execute("CREATE INDEX IF NOT EXISTS ix_foo ON foo(bar)")

For brand-new tables that the model also declares, the same applies — use
`op.execute("CREATE TABLE IF NOT EXISTS ...")` or check first.
"""
from logging.config import fileConfig
import os
import sys
from pathlib import Path

from sqlalchemy import engine_from_config, pool
from alembic import context

# Make `app` importable from this script.
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from app.database import Base  # noqa: E402
# Import all models so they're registered on Base.metadata for autogenerate.
from app.models import (  # noqa: E402, F401
    Photo,
    Folder,
    SourceRoot,
    Tag,
    Heap,
    HeapPhoto,
)

config = context.config

# Resolve DATABASE_URL from env. Strip async driver suffixes — Alembic
# uses sync drivers.
db_url = os.environ.get("DATABASE_URL") or config.get_main_option("sqlalchemy.url")
if db_url:
    if "+asyncpg" in db_url:
        db_url = db_url.replace("+asyncpg", "+psycopg2")
    elif db_url.startswith("postgresql://"):
        db_url = db_url.replace("postgresql://", "postgresql+psycopg2://", 1)
    elif "+aiosqlite" in db_url:
        db_url = db_url.replace("+aiosqlite", "")
    config.set_main_option("sqlalchemy.url", db_url)

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

target_metadata = Base.metadata


def run_migrations_offline() -> None:
    """Run migrations in 'offline' mode (emit SQL only)."""
    url = config.get_main_option("sqlalchemy.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 against a live database."""
    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,
        )
        with context.begin_transaction():
            context.run_migrations()


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