"""
Shared helpers for loading datatype mappings from ``snowflake-data-validation``.

Used by source executor factories (SQL Server, Redshift, etc.) to map
source column types to Snowflake equivalents via the framework's YAML
type-mapping templates.
"""

from __future__ import annotations

import re
from pathlib import Path
from typing import Optional

from snowflake.snowflake_data_validation.utils.constants import (
    COLUMN_DATATYPES_MAPPING_NAME_FORMAT,
    Platform,
)
from snowflake.snowflake_data_validation.utils.helpers.helper_templates import (
    HelperTemplates,
)


_TYPE_BASE_RE = re.compile(r"^([a-zA-Z_][a-zA-Z0-9_]*)")


def pkg_root() -> Path:
    """Return the root directory of the ``snowflake-data-validation`` package."""
    import snowflake.snowflake_data_validation as _pkg
    return Path(_pkg.__file__).resolve().parent


def load_datatypes_mapping(platform: Platform) -> Optional[dict[str, str]]:
    """Load the ``platform`` -> Snowflake YAML type mapping.

    Returns ``None`` if the mapping file does not exist.
    """
    templates_dir = pkg_root() / platform.value / "extractor" / "templates"
    mapping_filename = COLUMN_DATATYPES_MAPPING_NAME_FORMAT.format(
        source_platform=platform.value,
        target_platform=Platform.SNOWFLAKE.value,
    )
    mapping_yaml = templates_dir / mapping_filename
    if not mapping_yaml.exists():
        return None
    return HelperTemplates.load_datatypes_mapping_templates_from_yaml(mapping_yaml)


def base_type_name(type_name: str) -> str:
    """Extract the base type name, stripping ``(precision,scale)`` suffixes.

    Examples::

        "nvarchar(100)"           -> "NVARCHAR"
        "character varying(256)"  -> "CHARACTER"
        "decimal(18,2)"           -> "DECIMAL"
        "int identity"            -> "INT"
        "integer"                 -> "INTEGER"
    """
    m = _TYPE_BASE_RE.match(type_name.strip())
    if m:
        return m.group(1).upper()
    return type_name.strip().upper()
