import asyncio  # noqa: INP001
import sys
from pathlib import Path
from typing import Any

import structlog
from alembic import context
from alembic.context import config
from sqlalchemy import Connection, pool
from sqlalchemy.ext.asyncio import async_engine_from_config
from structlog import BoundLogger

from csirtmu.perun_sync.config import AppConfig
from csirtmu.perun_sync.perun_sync.models import Base

BASE_DIR = Path(__file__).parent.parent

logger: BoundLogger = structlog.get_logger()

app_config = AppConfig.get()

logger.info("Running migrations...")
config.set_main_option(
    "sqlalchemy.url",
    f"postgresql+psycopg://{app_config.database.username}:{app_config.database.password}"
    f"@{app_config.database.host}:{app_config.database.port}/{app_config.database.database}",
)

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

# Copied to tests/test_migrations.py - glorious imports - update both


def include_tables_from_metadata(name: str, type_: Any, parents_name: str) -> bool:  # noqa: ARG001
    return not ((type_ == "schema" and name is None) or (type_ == "table" and name == "alembic_version"))


def include_objects_from_database(
    object: Any,  # noqa: ARG001
    name: str,
    type_: Any,
    reflected: Any,  # noqa: ARG001
    compare_to: Any,  # noqa: ARG001
) -> bool:
    return not ((type_ == "schema" and name is None) or (type_ == "table" and name == "alembic_version"))


def run_migrations_offline() -> None:
    """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_name=include_tables_from_metadata,  # type: ignore
        include_object=include_objects_from_database,  # type: ignore
        include_schemas=True,
        version_table_schema="public",
    )

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


def do_run_migrations(connection: Connection) -> None:
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        include_name=include_tables_from_metadata,  # type: ignore
        include_object=include_objects_from_database,  # type: ignore
        include_schemas=True,
        version_table_schema="public",
    )

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


async def run_async_migrations() -> None:
    connectable = async_engine_from_config(
        config.get_section(config.config_ini_section),  # type: ignore
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    async with connectable.connect() as connection:
        connection.dialect.default_schema_name = "alembic_fake_schema"
        await connection.run_sync(do_run_migrations)

    await connectable.dispose()


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

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

    """

    connectable = config.attributes.get("connection", None)

    if connectable is None:
        if sys.platform.startswith("win"):
            asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())  # type: ignore
        asyncio.run(run_async_migrations())
    else:
        do_run_migrations(connectable)


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

logger.info("Migrations finished")
