#!/usr/bin/env python3
"""
The Amygdala — Salience Detection & Emotional Tagging
Determines what matters. High amygdala salience gates all other processing.
"""
import re
from brain.state import new_signal, EMOTIONAL_TAGS

# Keyword maps for rapid tagging
SALIENT_KEYWORDS = [
    "urgent", "emergency", "critical", "breaking", "immediately",
    "danger", "threat", "attack", "broken", "fail", "error", "crash",
    "love", "excited", "amazing", "terrified", "devastated"
]

EMOTION_MAP = {
    "curious": ["how", "why", "what", "explain", "wonder", "?"],
    "anxious": ["worried", "afraid", "scared", "nervous", "stress", "fear"],
    "joyful": ["happy", "excited", "great", "amazing", "love", "wonderful"],
    "frustrated": ["broken", "error", "fail", "wrong", "stuck", "can't", "annoyed"],
    "creative": ["create", "build", "design", "imagine", "art", "new", "make"],
    "urgent": ["urgent", "now", "immediately", "asap", "emergency", "critical"],
    "peaceful": ["calm", "quiet", "still", "rest", "peace", "tranquil"],
    "confused": ["confused", "unclear", "don't understand", "lost", "?"],
    "determined": ["will", "must", "going to", "commit", "finish", "complete"],
}

CONTENT_WORDS = ["good", "great", "excellent", "love", "like", "best", "nice"]
DETRACT_WORDS = ["bad", "wrong", "fail", "hate", "worst", "terrible", "awful"]

def tag_emotions(raw_input):
    """Return list of emotional tags found in input."""
    text = raw_input.lower()
    tags = []
    for emotion, keywords in EMOTION_MAP.items():
        if any(kw in text for kw in keywords):
            tags.append(emotion)
    if not tags:
        tags.append("neutral")
    return tags[:5]  # Cap at 5 tags

def detect_salience(raw_input, emotional_tags):
    """Score salience 0.0–1.0. High salience gates the system."""
    score = 0.0
    text = raw_input.lower()

    # Explicit urgency markers
    if any(kw in text for kw in SALIENT_KEYWORDS):
        score += 0.4

    # Emotional intensity
    high_intensity = ["urgent", "anxious", "joyful", "frustrated", "terrified"]
    if any(t in emotional_tags for t in high_intensity):
        score += 0.3

    # Length + complexity signal
    words = len(raw_input.split())
    if words > 100:
        score += 0.15
    elif words > 50:
        score += 0.1

    # Punctuation intensity (exclamation, caps)
    exclaim_count = raw_input.count("!")
    if exclaim_count >= 3:
        score += 0.15
    elif exclaim_count >= 1:
        score += 0.05

    # ALL CAPS word detection
    caps_words = re.findall(r'\b[A-Z]{3,}\b', raw_input)
    if len(caps_words) >= 2:
        score += 0.15
    elif len(caps_words) >= 1:
        score += 0.05

    return min(score, 1.0)

def detect_valence(emotional_tags):
    """Determine overall valence."""
    positive = ["joyful", "peaceful", "creative", "determined"]
    negative = ["anxious", "frustrated", "confused"]
    if any(t in emotional_tags for t in positive):
        return "positive"
    elif any(t in emotional_tags for t in negative):
        return "negative"
    return "neutral"

def detect_arousal(salience, emotional_tags):
    """Determine arousal state."""
    if salience >= 0.7:
        return "overload"
    elif salience >= 0.4:
        return "activated"
    return "calm"

def process(signal):
    """
    Process a signal through amygdala.
    Reads: signal['raw_input']
    Writes: signal['amygdala'] block
    Returns: modified signal
    """
    raw = signal.get("raw_input", "")
    tags = tag_emotions(raw)
    salience = detect_salience(raw, tags)
    valence = detect_valence(tags)
    arousal = detect_arousal(salience, tags)

    signal["amygdala"] = {
        "salience": round(salience, 3),
        "emotional_tags": tags,
        "valence": valence,
        "arousal": arousal
    }

    return signal
