"""
Database dialects supported by the test runner.

Covers both source databases (SQL Server, Oracle, Teradata, ...) and the
target database (Snowflake).
"""

from __future__ import annotations

from enum import Enum


class DatabaseDialect(str, Enum):
    """Database dialect identifiers."""

    UNKNOWN = "unknown"
    SQL_SERVER = "sqlserver"
    ORACLE = "oracle"
    TERADATA = "teradata"
    BIG_QUERY = "bigquery"
    REDSHIFT = "redshift"
    GREENPLUM = "greenplum"
    SYBASE = "sybase"
    POSTGRESQL = "postgresql"
    NETEZZA = "netezza"
    DATABRICKS = "databricks"
    SPARK = "spark"
    VERTICA = "vertica"
    HIVE = "hive"
    DB2 = "db2"
    SNOWFLAKE = "snowflake"


# Alias mapping -- normalized (lowercase, no separators) -> DatabaseDialect
_ALIASES: dict[str, DatabaseDialect] = {
    # SQL Server
    "sqlserver": DatabaseDialect.SQL_SERVER,
    "mssql": DatabaseDialect.SQL_SERVER,
    "microsoftsqlserver": DatabaseDialect.SQL_SERVER,
    "transact": DatabaseDialect.SQL_SERVER,
    "tsql": DatabaseDialect.SQL_SERVER,
    "azuresynapse": DatabaseDialect.SQL_SERVER,
    "synapse": DatabaseDialect.SQL_SERVER,
    # Oracle
    "oracle": DatabaseDialect.ORACLE,
    "ora": DatabaseDialect.ORACLE,
    # Teradata
    "teradata": DatabaseDialect.TERADATA,
    "td": DatabaseDialect.TERADATA,
    "t12": DatabaseDialect.TERADATA,
    # BigQuery
    "bigquery": DatabaseDialect.BIG_QUERY,
    "googlebigquery": DatabaseDialect.BIG_QUERY,
    "bq": DatabaseDialect.BIG_QUERY,
    # Redshift
    "redshift": DatabaseDialect.REDSHIFT,
    "amazonredshift": DatabaseDialect.REDSHIFT,
    "rs": DatabaseDialect.REDSHIFT,
    # Postgresql
    "postgresql": DatabaseDialect.POSTGRESQL,
    "postgres": DatabaseDialect.POSTGRESQL,
    "pg": DatabaseDialect.POSTGRESQL,
    # Databricks
    "databricks": DatabaseDialect.DATABRICKS,
    "databrickssql": DatabaseDialect.DATABRICKS,
    "dbx": DatabaseDialect.DATABRICKS,
    # Spark
    "spark": DatabaseDialect.SPARK,
    "sparksql": DatabaseDialect.SPARK,
    # Snowflake (target)
    "snowflake": DatabaseDialect.SNOWFLAKE,
    "sf": DatabaseDialect.SNOWFLAKE,
    # Others
    "greenplum": DatabaseDialect.GREENPLUM,
    "gp": DatabaseDialect.GREENPLUM,
    "sybase": DatabaseDialect.SYBASE,
    "netezza": DatabaseDialect.NETEZZA,
    "nz": DatabaseDialect.NETEZZA,
    "vertica": DatabaseDialect.VERTICA,
    "vt": DatabaseDialect.VERTICA,
    "hive": DatabaseDialect.HIVE,
    "hv": DatabaseDialect.HIVE,
    "db2": DatabaseDialect.DB2,
    "ibmdb2": DatabaseDialect.DB2,
}


def parse_dialect(value: str | None) -> DatabaseDialect:
    """Parse a dialect string into a :class:`DatabaseDialect`.

    Handles aliases and is case-insensitive.
    """
    if not value:
        return DatabaseDialect.UNKNOWN
    normalized = value.lower().replace(" ", "").replace("-", "").replace("_", "")
    return _ALIASES.get(normalized, DatabaseDialect.UNKNOWN)
