"""Schema name helper for migrations: use 'pycharter' for PostgreSQL, None for SQLite.

SQLite does not support schemas; it treats schema-qualified names as attached databases.
Migrations use get_schema(bind) and pass the result as schema= to op.create_table, etc.
"""

from __future__ import annotations

from sqlalchemy.engine import Connection
from sqlalchemy.engine.base import Engine


def get_schema(bind: Connection | Engine) -> str | None:
    """Return schema name for the current dialect: 'pycharter' for PostgreSQL, None for SQLite."""
    dialect = getattr(bind, "dialect", None)
    if dialect is not None:
        return None if dialect.name == "sqlite" else "pycharter"
    # op.get_bind() can return a raw DBAPI connection (e.g. sqlite3.Connection)
    mod = type(bind).__module__
    if "sqlite" in mod:
        return None
    return "pycharter"


def ref_table(table_name: str, bind: Connection | Engine) -> str:
    """Return schema-qualified table name for FK references, or plain name for SQLite."""
    schema = get_schema(bind)
    return f"{schema}.{table_name}" if schema else table_name
