"""
Alembic 环境配置 - PostgreSQL
"""

import os
import sys
from logging.config import fileConfig

from sqlalchemy import engine_from_config, pool

from alembic import context

# 添加项目路径
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

# 加载环境变量
from dotenv import load_dotenv

load_dotenv()

# 导入模型
from app.db.session import Base
from app.models.bgm_music import BgmMusic  # noqa
from app.models.broll_category import BrollCategory  # noqa
from app.models.broll_material import BrollMaterial  # noqa
from app.models.broll_tag import BrollTag  # noqa
from app.models.cover_background import CoverBackground  # noqa
from app.models.point_batch import PointBatch  # noqa
from app.models.point_recharge_order import PointRechargeOrder  # noqa
from app.models.point_transaction import PointTransaction  # noqa
from app.models.update import AppRelease, ReleasePackage  # noqa
from app.models.user import User  # noqa
from app.models.user_device import UserDevice  # noqa
from app.models.user_point import UserPoint  # noqa

# this is the Alembic Config object
config = context.config

# 从环境变量读取数据库 URL
database_url = os.getenv("DATABASE_URL")
if database_url:
    # 将 asyncpg 转换为 psycopg2 用于 alembic (同步)
    sync_database_url = database_url.replace("+asyncpg", "")
    config.set_main_option("sqlalchemy.url", sync_database_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."""
    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 in 'online' mode."""
    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()
