"""Alembic migration codegen for NIKAME.

Generates a pre-wired Alembic setup when Postgres is active,
including alembic.ini, env.py, and an initial migration stub.
"""

from __future__ import annotations


def generate_alembic_files(project_name: str, database_url: str) -> list[tuple[str, str]]:
    """Generate all Alembic scaffolding files.

    Args:
        project_name: Name of the project.
        database_url: SQLAlchemy-compatible database URL.

    Returns:
        List of (relative_path, content) tuples.
    """
    files: list[tuple[str, str]] = []

    # 1. alembic.ini
    files.append(("alembic.ini", _alembic_ini(database_url)))

    # 2. alembic/env.py
    files.append(("alembic/env.py", _env_py()))

    # 3. alembic/script.py.mako
    files.append(("alembic/script.py.mako", _script_mako()))

    # 4. alembic/versions/.gitkeep
    files.append(("alembic/versions/.gitkeep", ""))

    # 5. alembic/README
    files.append(("alembic/README", "Database migration scripts managed by Alembic.\n"))

    return files


def _alembic_ini(database_url: str) -> str:
    return f"""# Alembic Configuration — Auto-generated by NIKAME
[alembic]
script_location = alembic
prepend_sys_path = .
sqlalchemy.url = {database_url}

[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console

[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
"""


def _env_py() -> str:
    return '''"""Alembic env.py — Auto-generated by NIKAME.

Imports all SQLAlchemy models so autogenerate can detect schema changes.
"""

import os
import sys
from logging.config import fileConfig

from alembic import context
from sqlalchemy import engine_from_config, pool

# Ensure the app directory is importable
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

# Import your models here so Alembic can auto-detect changes
try:
    from app.api.auth.models import Base as AuthBase  # noqa: F401
except ImportError:
    AuthBase = None

try:
    from app.models.document_meta import Base as DocBase  # noqa: F401
except ImportError:
    DocBase = None

# Use the first available Base for target_metadata
from sqlalchemy.orm import declarative_base
_FallbackBase = declarative_base()

target_metadata = getattr(AuthBase, "metadata", None) or \\
                  getattr(DocBase, "metadata", None) or \\
                  _FallbackBase.metadata

config = context.config

# Override sqlalchemy.url from environment if available
db_url = os.environ.get("DATABASE_URL")
if db_url:
    config.set_main_option("sqlalchemy.url", db_url)

if config.config_file_name is not None:
    fileConfig(config.config_file_name)


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


def _script_mako() -> str:
    return '''"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}


def upgrade() -> None:
    ${upgrades if upgrades else "pass"}


def downgrade() -> None:
    ${downgrades if downgrades else "pass"}
'''
