import pandas as pd
from ..exceptions import ColumnValidationError
import re

def validate_regex(series: pd.Series, pattern: str, column_name: str):
    """
    Validate that string (non-null) values match regex `pattern`.
    Non-string values will be treated as mismatch (except nulls).
    """
    if pattern is None:
        return
    if series is None:
        raise ColumnValidationError(column_name, "column missing", sample=[])
    # safe vectorized check: convert to str but keep track of originally non-null non-str values
    # We want to treat non-string non-null as mismatch.
    non_null = series.dropna()
    if non_null.empty:
        return
    # Build mask of matches; safe with exceptions
    try:
        # Ensure pattern is valid
        re.compile(pattern)
        # use pandas str.match (works on nan-safe series if converted to str)
        matches = non_null.astype(str).str.match(pattern)
        mismatches = non_null[~matches]
        if not mismatches.empty:
            sample = mismatches.head(10).tolist()
            raise ColumnValidationError(column_name, f"regex mismatch ({pattern})", sample=sample)
    except re.error as e:
        raise ColumnValidationError(column_name, f"invalid regex pattern: {e}", sample=[])
