"""Alembic 환경 설정 — GUARDiA ITSM PostgreSQL 마이그레이션."""
import os
from logging.config import fileConfig

from sqlalchemy import engine_from_config, pool
from alembic import context

# alembic.ini 로거 설정 적용
config = context.config
if config.config_file_name:
    fileConfig(config.config_file_name)

# DATABASE_URL 환경변수 우선 사용
db_url = os.getenv("DATABASE_URL")
if db_url:
    # asyncpg → psycopg2 (Alembic은 동기 실행)
    db_url = db_url.replace("postgresql+asyncpg://", "postgresql+psycopg2://")
    db_url = db_url.replace("postgresql://", "postgresql+psycopg2://")
    config.set_main_option("sqlalchemy.url", db_url)

# 모든 모델 메타데이터 임포트
import sys, pathlib
sys.path.insert(0, str(pathlib.Path(__file__).parent.parent))
from models import Base  # noqa: E402
target_metadata = Base.metadata


def run_migrations_offline() -> None:
    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:
    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()
