# utils/text_processor.py
from django.utils.html import strip_tags
import re


def clean_content(content):
    """通用内容清洗函数"""
    cleaned = strip_tags(content)  # 去除HTML标签
    cleaned = re.sub(r'\s+', ' ', cleaned)  # 合并空白字符
    return cleaned.strip()


def truncate_text(text, max_length):
    """通用智能截取函数"""
    if not text or max_length <= 0:
        return ''

    if len(text) <= max_length:
        return text

    truncated = text[:max_length]

    # 标点优先级处理
    for punctuation in ['。', '！', '？', '.', '!', '?']:
        last_pos = truncated.rfind(punctuation)
        if last_pos > int(max_length * 0.8):
            return truncated[:last_pos + 1]

    for delimiter in ['；', ';', '，', ',']:
        last_pos = truncated.rfind(delimiter)
        if last_pos > int(max_length * 0.8):
            return truncated[:last_pos + 1]

    last_space = truncated.rfind(' ')
    if last_space > int(max_length * 0.7):
        return truncated[:last_space]

    return truncated + '...'


def clean_truncate_intro(str, config):
    '''    
    只负责清理和截取：将内容主体按config中的要求进行截断，外围判断是否需要清洗和截取
    str:内容主体内容，
    config:可为congtent_config.get_solo()
    '''
    cleaned = clean_content(str)
    return truncate_text(cleaned, config.summary_length)
