import os
import sys
from logging.config import fileConfig

from alembic import context
from sqlalchemy import create_engine, pool

# Add project root to path so `app` module is importable
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from app.config import settings
from app.models.base import Base

# Import all models so they register with Base.metadata
from app.models.user import User  # noqa: F401
from app.models.project import Project  # noqa: F401
from app.models.generation_record import GenerationRecord  # noqa: F401
from app.models.credit_record import CreditRecord  # noqa: F401
from app.models.credit_ratio import CreditRatio  # noqa: F401
from app.models.system_config import SystemConfig  # noqa: F401
from app.models.model_config import ModelConfig  # noqa: F401
from app.models.token_usage import TokenUsage  # noqa: F401
from app.models.industry_config import IndustryConfig  # noqa: F401
from app.models.menu_config import MenuConfig  # noqa: F401
from app.models.notification import Notification  # noqa: F401
from app.models.notification_read import NotificationRead  # noqa: F401
from app.models.operation_log import OperationLog  # noqa: F401
from app.models.payment_order import PaymentOrder  # noqa: F401
from app.models.recharge_package import RechargePackage  # noqa: F401
from app.models.video_engine import VideoEngine  # noqa: F401
from app.models.image_engine import ImageEngine  # noqa: F401
from app.models.chat_generation_task import ChatGenerationTask  # noqa: F401
from app.models.chat_generation_task_event import ChatGenerationTaskEvent  # noqa: F401
from app.models.chat_provider_call_log import ChatProviderCallLog  # noqa: F401
from app.models.user_oauth import UserOAuth  # noqa: F401
from app.models.user_oauth_app import UserOAuthApp  # noqa: F401
from app.models.user_oauth_account import UserOAuthAccount  # noqa: F401
from app.models.resources_material import ResourcesMaterial  # noqa: F401
from app.models.material_cost import MaterialCost  # noqa: F401
from app.models.generated_resource import GeneratedResource  # noqa: F401
from app.models.pre_test_template import PreTestTemplate  # noqa: F401
from app.models.upload_task import UploadTask  # noqa: F401
from app.models.open_type import OpenType  # noqa: F401


config = context.config

# Override sqlalchemy.url with the one from app settings
# Convert async driver URLs to sync for Alembic CLI operations
db_url = settings.DATABASE_URL
if "aiosqlite" in db_url:
    db_url = db_url.replace("sqlite+aiosqlite", "sqlite")
elif "asyncpg" in db_url:
    db_url = db_url.replace("postgresql+asyncpg", "postgresql")
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."""
    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 using sync engine."""
    connectable = create_engine(
        config.get_main_option("sqlalchemy.url"),
        poolclass=pool.NullPool,
    )
    with connectable.connect() as connection:
        context.configure(connection=connection, target_metadata=target_metadata)
        with context.begin_transaction():
            context.run_migrations()
    connectable.dispose()


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