"""
Text utility functions for HTML sanitization and text processing.
"""
import re
import bleach
import subprocess


def chinese_to_pinyin(chinese_text):
    """将汉字转换为拼音"""
    if not chinese_text:
        return ""
    import pypinyin
    pinyin_list = pypinyin.lazy_pinyin(chinese_text)
    return "".join(pinyin_list)


def sanitize_html(text):
    """
    Sanitize HTML content to prevent XSS attacks and code execution.
    This function removes dangerous content while preserving safe formatting.
    """
    if not text:
        return ""
    
    # First, remove any template syntax that could be dangerous
    # Remove Jinja2/Flask template syntax
    text = re.sub(r'\{\{.*?\}\}', '', text, flags=re.DOTALL)
    text = re.sub(r'\{%.*?%\}', '', text, flags=re.DOTALL)
    
    # Remove other template-like syntax
    text = re.sub(r'<%.*?%>', '', text, flags=re.DOTALL)
    text = re.sub(r'<\?.*?\?>', '', text, flags=re.DOTALL)
    
    # Define allowed tags and attributes for safe HTML
    allowed_tags = [
        'p', 'br', 'strong', 'b', 'em', 'i', 'u', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
        'ul', 'ol', 'li', 'blockquote', 'code', 'pre', 'a', 'img', 'table', 'thead', 
        'tbody', 'tr', 'th', 'td', 'dl', 'dt', 'dd', 'div', 'span', 'hr', 'sup', 'sub'
    ]
    
    allowed_attributes = {
        'a': ['href', 'title'],
        'img': ['src', 'alt', 'title', 'width', 'height'],
        'code': ['class'],  # For syntax highlighting
        'pre': ['class'],   # For syntax highlighting
        'div': ['class'],   # For code blocks
        'span': ['class'],  # For syntax highlighting
        'th': ['align'],
        'td': ['align'],
        'table': ['class']
    }
    
    # Sanitize the HTML to remove dangerous content
    sanitized_html = bleach.clean(
        text,
        tags=allowed_tags,
        attributes=allowed_attributes,
        protocols=['http', 'https', 'mailto'],
        strip=True  # Strip disallowed tags instead of escaping them
    )
    
    return sanitized_html


def get_version():
    """获取应用版本号"""
    # Try reading VERSION file first (works in Docker)
    try:
        with open('VERSION', 'r') as f:
            return f.read().strip()
    except FileNotFoundError:
        pass
    
    # Fall back to git tags (works in development)
    try:
        return subprocess.check_output(['git', 'describe', '--tags', '--abbrev=0'], 
                                     stderr=subprocess.DEVNULL).decode().strip()
    except:
        pass
    
    # Final fallback
    return "unknown"
