# textanalyzer/sentiment_analyzer.py
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

# 初始化情感分析器（全局初始化，避免重复创建）
sentiment_analyzer = SentimentIntensityAnalyzer()

def analyze_sentiment(text: str) -> dict:
    """
    分析文本情感倾向，返回详细得分
    返回值说明：
    - neg: 负面情感得分 (0-1)
    - neu: 中性情感得分 (0-1)
    - pos: 正面情感得分 (0-1)
    - compound: 综合得分 (-1到1，越接近1越正面，越接近-1越负面)
    """
    # 处理空文本
    if not text.strip():
        return {"neg": 0.0, "neu": 1.0, "pos": 0.0, "compound": 0.0}
    
    scores = sentiment_analyzer.polarity_scores(text)
    return scores

def get_sentiment_label(text: str) -> str:
    """
    根据综合得分返回情感标签：Positive/Negative/Neutral
    """
    scores = analyze_sentiment(text)
    compound_score = scores["compound"]
    
    if compound_score >= 0.05:
        return "Positive"
    elif compound_score <= -0.05:
        return "Negative"
    else:
        return "Neutral"
