from __future__ import annotations

import re

_DML_SQL_PATTERN = re.compile(r"\b(select|insert|update|delete|with|merge|replace)\b", re.IGNORECASE)
_DDL_SQL_PATTERN = re.compile(
    r"^\s*(create|alter|drop)\s+(table|index|view|materialized|schema|database|extension)\b",
    re.IGNORECASE,
)
_IDENTIFIER_PATTERN = re.compile(r"[^a-zA-Z0-9_]")


def normalize_whitespace(text: str) -> str:
    return re.sub(r"\s+", " ", text).strip()


def looks_like_sql(text: str) -> bool:
    normalized = normalize_whitespace(text)
    return bool(_DML_SQL_PATTERN.search(normalized) or _DDL_SQL_PATTERN.search(normalized))


def dedupe_preserve_order(items: list[str]) -> list[str]:
    seen: set[str] = set()
    ordered: list[str] = []
    for item in items:
        if item not in seen:
            seen.add(item)
            ordered.append(item)
    return ordered


def camel_to_snake(name: str) -> str:
    interim = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", name)
    return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", interim).lower()


def sanitize_identifier(value: str) -> str:
    value = value.strip().strip("`\"'")
    value = value.replace("-", "_")
    return _IDENTIFIER_PATTERN.sub("", value.lower())
