"""Emotional valence analysis - VADER-inspired, zero-dependency."""

from __future__ import annotations

import re

from neurovault.models import EmotionalValence

POSITIVE_WORDS = {
    "good", "great", "excellent", "amazing", "wonderful", "fantastic",
    "awesome", "beautiful", "brilliant", "outstanding", "superb",
    "love", "happy", "joy", "excited", "thrilled", "delighted",
    "success", "win", "perfect", "best", "solved", "fixed",
    "breakthrough", "impressive", "remarkable", "incredible",
    "proud", "confident", "optimistic", "grateful", "pleased",
    "efficient", "elegant", "innovative", "creative", "accomplished",
}

NEGATIVE_WORDS = {
    "bad", "terrible", "awful", "horrible", "worst", "hate",
    "angry", "frustrated", "annoyed", "disappointed", "failed",
    "broken", "bug", "error", "crash", "issue", "problem",
    "confused", "worried", "stressed", "anxious", "overwhelmed",
    "slow", "ugly", "messy", "complicated", "nightmare",
    "stuck", "blocked", "dead", "killed", "destroyed",
    "impossible", "useless", "waste", "pain", "suffering",
}

HIGH_AROUSAL_WORDS = {
    "urgent", "critical", "emergency", "immediately", "asap",
    "exciting", "thrilling", "amazing", "incredible", "shocking",
    "furious", "outraged", "terrified", "ecstatic", "explosive",
    "breaking", "crashed", "destroyed", "panic", "alarm",
}

DOMINANCE_HIGH = {
    "solved", "fixed", "accomplished", "conquered", "mastered", "built", "created"
}
DOMINANCE_LOW = {"confused", "lost", "stuck", "helpless", "overwhelmed", "uncertain", "unsure"}


class EmotionalAnalyzer:
    """Lightweight emotional valence analysis."""

    def analyze(self, content: str) -> EmotionalValence:
        words = set(re.findall(r"\w+", content.lower()))

        pos_count = len(words & POSITIVE_WORDS)
        neg_count = len(words & NEGATIVE_WORDS)
        valence = (pos_count - neg_count) / max(pos_count + neg_count, 1)
        valence = max(-1.0, min(1.0, valence))

        arousal = 0.0
        arousal += len(words & HIGH_AROUSAL_WORDS) * 0.2
        arousal += content.count("!") * 0.1
        arousal += content.count("?") * 0.05
        arousal += len(re.findall(r"\b[A-Z]{3,}\b", content)) * 0.15
        if "!!!" in content:
            arousal += 0.3
        arousal = min(arousal, 1.0)

        dom_high = len(words & DOMINANCE_HIGH)
        dom_low = len(words & DOMINANCE_LOW)
        dominance = 0.5 + (dom_high - dom_low) * 0.15
        dominance = max(0.0, min(1.0, dominance))
        dominance -= content.count("?") * 0.05
        dominance = max(0.0, dominance)

        return EmotionalValence(
            valence=round(valence, 3),
            arousal=round(arousal, 3),
            dominance=round(dominance, 3),
        )
