"""SQLAlchemy plugin for FastAPI."""

from __future__ import annotations

from typing import Any

from litestar_start.core.plugin import PluginFile, PluginInterface, PluginMetadata, PluginResult


class SQLAlchemyPlugin(PluginInterface):
    """SQLAlchemy ORM integration for FastAPI."""

    metadata = PluginMetadata(
        name="sqlalchemy",
        display_name="SQLAlchemy",
        category="orm",
        description="SQL toolkit and ORM for Python",
        requires=["database"],  # Requires a database plugin to be selected
    )

    def apply(self) -> PluginResult:
        """Apply SQLAlchemy integration.

        Returns:
            PluginResult with files, dependencies, and environment variables.

        """
        database = self.context.config.get("database", "postgresql")

        # Database-specific driver
        drivers = {
            "postgresql": "psycopg2-binary>=2.9.9",
            "mysql": "pymysql>=1.1.0",
            "sqlite": "aiosqlite>=0.19.0",
        }

        dependencies = [
            "sqlalchemy>=2.0.0",
            "alembic>=1.13.0",
            drivers.get(database, ""),
        ]

        files = [
            PluginFile(
                path="app/db/base.py",
                content=self._create_base_module(),
            ),
            PluginFile(
                path="app/db/session.py",
                content=self._create_session_module(database),
            ),
            PluginFile(
                path="app/models/__init__.py",
                content=self._create_models_init(),
            ),
            PluginFile(
                path="alembic.ini",
                content=self._create_alembic_ini(),
            ),
            PluginFile(
                path="alembic/env.py",
                content=self._create_alembic_env(),
            ),
            PluginFile(
                path="app/core/deps.py",
                content=self._create_deps_module(),
                mode="merge",  # Merge with existing deps
            ),
        ]

        env_vars = {
            "DATABASE_URL": self._get_database_url_template(database),
        }

        return PluginResult(
            files=files,
            dependencies=[d for d in dependencies if d],
            env_vars=env_vars,
        )

    def _get_database_url_template(self, database: str) -> str:
        """Get database URL template.

        Args:
            database: Database type.

        Returns:
            Database URL template string.

        """
        templates = {
            "postgresql": "postgresql://user:password@localhost:5432/{project_slug}",
            "mysql": "mysql://user:password@localhost:3306/{project_slug}",
            "sqlite": "sqlite:///./app.db",
        }
        return templates.get(database, "").format(project_slug=self.context.project_slug)

    def get_template_context(self) -> dict[str, Any]:
        """Get template context for rendering.

        Returns:
            Dictionary with template variables.

        """
        return {
            "database": self.context.config.get("database"),
            "async_mode": self.context.config.get("database") != "sqlite",
        }

    @staticmethod
    def _create_base_module() -> str:
        """Create database base module content.

        Returns:
            Database base module content.

        """
        return '''"""Database base configuration."""

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
'''

    @staticmethod
    def _create_session_module(database: str) -> str:
        """Create database session module content.

        Args:
            database: Database type.

        Returns:
            Database session module content.

        """
        return '''"""Database session management."""

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from app.core.config import settings

engine = create_engine(
    settings.DATABASE_URL,
    connect_args={"check_same_thread": False} if "sqlite" in settings.DATABASE_URL else {},
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


def get_db():
    """Get database session.

    Yields:
        Database session.

    """
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
'''

    @staticmethod
    def _create_models_init() -> str:
        """Create models __init__ module content.

        Returns:
            Models __init__ module content.

        """
        return '''"""Database models package."""

from app.db.base import Base

__all__ = ["Base"]
'''

    @staticmethod
    def _create_alembic_ini() -> str:
        """Create alembic.ini content.

        Returns:
            Alembic configuration content.

        """
        return """# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# timezone to use when rendering the date within the migration file
# as well as the filename.
# timezone =

# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; this defaults
# to alembic/versions.  When using multiple version
# directories, initial revisions must be specified with --version-path
# version_locations = %(here)s/bar %(here)s/bat alembic/versions

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url = driver://user:pass@localhost/dbname


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts.  See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
"""

    @staticmethod
    def _create_alembic_env() -> str:
        """Create alembic env.py content.

        Returns:
            Alembic environment configuration.

        """
        return '''"""Alembic migration environment."""

from logging.config import fileConfig

from sqlalchemy import engine_from_config, pool

from alembic import context

# Import your models' Base
from app.db.base import Base
from app.core.config import settings

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

# 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)

# Set SQLAlchemy URL from settings
config.set_main_option("sqlalchemy.url", settings.DATABASE_URL)

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

# 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() -> 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"},
    )

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


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 = 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()
'''

    @staticmethod
    @staticmethod
    def _create_deps_module() -> str:
        """Create dependencies module content.

        Returns:
            Dependencies module content.

        """
        return '''"""FastAPI dependencies."""

from typing import Generator

from app.db.session import SessionLocal


def get_db() -> Generator:
    """Get database session.

    Yields:
        Database session.

    """
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
'''
