from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool
# 添加类型导入以解决兼容性问题
from sqlalchemy.types import NullType
# 添加GeoAlchemy2导入
import geoalchemy2

from alembic import context
import os
import sys

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

# 导入数据库连接信息
from app.database import DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME, Base
# 导入所有模型
import app.models

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# 设置数据库连接 URL
section = config.config_ini_section
config.set_section_option(section, 'DB_USER', DB_USER)
config.set_section_option(section, 'DB_PASSWORD', DB_PASSWORD)
config.set_section_option(section, 'DB_HOST', DB_HOST)
config.set_section_option(section, 'DB_PORT', DB_PORT)
config.set_section_option(section, 'DB_NAME', DB_NAME)

# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
target_metadata = Base.metadata

# 定义要忽略的索引名称模式
def include_object(object, name, type_, reflected, compare_to):
    """过滤掉不需要的索引变化和表删除操作"""
    # 如果是表操作，且是删除操作，则忽略
    if type_ == "table" and reflected and not compare_to:
        return False
        
    if type_ == "index":
        # 如果是新表或新列的索引，保留
        if not reflected:
            return True
        # 如果是已存在表的索引，且名称以 'ix_' 开头，忽略
        if name.startswith('ix_'):
            return False
        # 如果是已存在表的索引，且名称以 '_idx' 结尾，忽略
        if name.endswith('_idx'):
            return False
        # 如果是已存在表的索引，且名称以 'idx_' 开头，保留
        if name.startswith('idx_'):
            return True
    return True

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


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

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
        include_object=include_object,  # 添加过滤规则
    )

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


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

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """
    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,
            include_object=include_object,  # 添加过滤规则
        )

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


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