"""
Text processing utilities for the survey module.
"""
import re
from typing import Dict, Any


def safe_fill(template: str, mapping: Dict[str, Any]) -> str:
    """
    Safely fill template with mapping values, handling None values.
    
    Args:
        template: Template string with {key} placeholders
        mapping: Dictionary with values to fill
        
    Returns:
        Filled template string
    """
    out = template
    for k, v in mapping.items():
        out = out.replace("{" + k + "}", str(v) if v is not None else "")
    return out


def strategy_without_day_blocks(text: str) -> str:
    """
    Remove possible '<Шаг N: ...>' blocks if model inserted steps into strategy.
    
    Args:
        text: Strategy text to clean
        
    Returns:
        Cleaned strategy text without day blocks
    """
    if not text:
        return text
    
    m = re.search(r"(?:^|\n)\s*Шаг\s*\d+\s*[:\-—]", text, flags=re.IGNORECASE)
    if m:
        return text[:m.start()].rstrip()
    return text


def extract_day_html(steps: Dict[str, Any], day: int) -> str:
    """
    Extract HTML content for a specific day from steps dictionary.
    
    Args:
        steps: Steps dictionary
        day: Day number to extract
        
    Returns:
        HTML content for the day or empty string
    """
    if not isinstance(steps, dict):
        return ""
    
    key = str(day)
    val = steps.get(key)
    
    if isinstance(val, dict):
        return val.get("html", "") or ""
    if isinstance(val, str):
        return val
    return ""


# Banned step patterns for sanitization
BANNED_STEP_PATTERNS = [
    r"определ(и|ение)\s+целев(ой|ої)\s+аудитории",
    r"определи\s+ца",
    r"сформулируй\s+утп",
    r"создай\s+(аккаунт|страницу)\s+в\s+соцсет",
    r"проанализируй\s+конкурентов(?!.*конкретн)",
]


def is_bad_step(text: str) -> bool:
    """
    Check if step text contains banned patterns.
    
    Args:
        text: Step text to check
        
    Returns:
        True if text contains banned patterns
    """
    if not text:
        return False
    
    text_lower = text.lower()
    return any(re.search(pattern, text_lower) for pattern in BANNED_STEP_PATTERNS)
