from __future__ import annotations

import re
from typing import Sequence

# Environment variable names to look up for DB URL
DEFAULT_DB_ENV_VARS: Sequence[str] = (
    "DATABASE_URL",
    "DB_URL",
)

# Regex used to detect async drivers from URL drivername
ASYNC_DRIVER_HINT = re.compile(r"\+(?:async|asyncpg|aiosqlite|aiomysql|asyncmy|aio\w+)")

# Alembic ini template used by init_alembic
ALEMBIC_INI_TEMPLATE = """# Alembic configuration file, generated by svc-infra
[alembic]
path_separator = os
script_location = {script_location}

# Used only for offline mode; env.py will use DATABASE_URL if set
sqlalchemy.url = {sqlalchemy_url}

dialect_name = {dialect_name}

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

ALEMBIC_SCRIPT_TEMPLATE = '''"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""

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

# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}

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

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

__all__ = [
    "DEFAULT_DB_ENV_VARS",
    "ASYNC_DRIVER_HINT",
    "ALEMBIC_INI_TEMPLATE",
    "ALEMBIC_SCRIPT_TEMPLATE",
]
