"""
Text preprocessing for Gherbal language identification.

Uses the `unscript` library for script-aware text cleaning.
"""

from unscript import clean_text as _unscript_clean_text
from unscript import clean_script as _unscript_clean_script
from unscript import unscript as _unscript


def preprocess_text(text: str) -> str:
    """
    Preprocess text for language identification.

    Removes mentions, hashtags, URLs, emojis, normalizes unicode,
    collapses repeated characters, and lowercases.

    Args:
        text: Raw input text.

    Returns:
        Cleaned, lowercased text ready for model input.
    """
    if not isinstance(text, str):
        return ""
    return _unscript_clean_text(text, lowercase=True)


def clean_script(script: str, text: str, config: dict = None) -> str:
    """
    Filter text to keep only characters from the specified Unicode script.

    Args:
        script: Script code (e.g. 'Latn', 'Arab').
        text: Text to filter.
        config: Optional config dict with keys like 'spaces', 'numbers',
                'punctuation', 'symbols'.

    Returns:
        Text containing only characters from the specified script.
    """
    if not text:
        return text
    return _unscript_clean_script(script, text, config=config)


def unscript(script: str, text: str, config: dict = None, lowercase: bool = True) -> str:
    """
    Full preprocessing pipeline: clean_text + clean_script.

    Args:
        script: Script code (e.g. 'Latn', 'Arab').
        text: Raw input text.
        config: Optional config dict for script filtering.
        lowercase: Whether to lowercase the text.

    Returns:
        Fully cleaned and script-filtered text.
    """
    if not text:
        return text
    return _unscript(script, text, config=config, lowercase=lowercase)


def create_clean_script_function(default_config=None):
    """
    Factory function that creates a clean_script function with default config.

    This is a backwards-compatible wrapper around unscript.clean_script.

    Args:
        default_config: Default configuration dict with keys:
            'spaces' (bool), 'numbers' (bool), 'punctuation' (bool), 'symbols' (bool).

    Returns:
        A function(script, text, config=None) -> str that cleans text by script.
    """
    if default_config is None:
        default_config = {
            "spaces": True,
            "numbers": False,
            "punctuation": False,
            "symbols": False,
        }

    def _clean_script(script, text, config=None):
        if not text:
            return text
        merged = default_config.copy()
        if config:
            merged.update(config)
        return _unscript_clean_script(script, text, config=merged)

    return _clean_script
