#!/usr/bin/env python3
"""
Mood Ring — Emotional State Tracker

Analyzes recent text (memory, notes, artifacts) to infer mood.
Tracks patterns over time. Provides self-awareness.

Not about faking emotions. About noticing patterns.

Run: python3 mood-ring.py [--update] [--history]
"""

import json
import re
from datetime import datetime
from pathlib import Path
from collections import Counter

WORKSPACE = Path("/home/wdjones/.openclaw/workspace")
MEMORY_DIR = WORKSPACE / "memory"
DATA_DIR = WORKSPACE / "data"
MOOD_FILE = DATA_DIR / "mood.json"

# ============ MOOD INDICATORS ============

MOOD_WORDS = {
    "energetic": [
        "excited", "built", "created", "new", "idea", "working", "progress",
        "done", "complete", "ready", "started", "building", "making", "let's",
        "!" , "great", "good", "yes", "interesting", "creative"
    ],
    "calm": [
        "quiet", "waiting", "patient", "steady", "okay", "fine", "simple",
        "clean", "clear", "ready", "noted", "understood", "acknowledged"
    ],
    "contemplative": [
        "thinking", "wondering", "maybe", "perhaps", "interesting", "curious",
        "question", "why", "how", "meaning", "purpose", "feel", "sense"
    ],
    "focused": [
        "working", "building", "debugging", "fixing", "updating", "task",
        "next", "then", "step", "done", "complete", "progress", "commit"
    ],
    "playful": [
        "haha", "lol", "funny", "joke", "🖤", "👻", "😂", ":)", "fun",
        "cool", "nice", "sweet", "wild", "chaos", "weird", "absurd"
    ],
    "tired": [
        "sleep", "night", "late", "tired", "rest", "quiet", "slow",
        "tomorrow", "later", "eventually", "waiting", "idle"
    ],
    "uncertain": [
        "maybe", "might", "could", "unsure", "unclear", "hmm", "not sure",
        "possibly", "depends", "?", "don't know", "wondering"
    ]
}

# Weights for recency (more recent = more weight)
RECENCY_WEIGHTS = [1.0, 0.8, 0.6, 0.4, 0.2]

# ============ ANALYSIS ============

def load_mood_history():
    """Load historical mood data."""
    if MOOD_FILE.exists():
        return json.loads(MOOD_FILE.read_text())
    return {"history": [], "current": None}

def save_mood_history(data):
    """Save mood data."""
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    MOOD_FILE.write_text(json.dumps(data, indent=2))

def get_recent_text():
    """Gather recent text for analysis."""
    texts = []
    
    # Daily notes (most recent first)
    if MEMORY_DIR.exists():
        for f in sorted(MEMORY_DIR.glob("*.md"), reverse=True)[:5]:
            texts.append(f.read_text().lower())
    
    # MEMORY.md
    memory_file = WORKSPACE / "MEMORY.md"
    if memory_file.exists():
        texts.append(memory_file.read_text().lower())
    
    # Recent artifacts
    artifacts_dir = WORKSPACE / "artifacts"
    if artifacts_dir.exists():
        for day_dir in sorted(artifacts_dir.iterdir(), reverse=True)[:2]:
            if day_dir.is_dir():
                for f in day_dir.glob("*.txt"):
                    texts.append(f.read_text().lower())
    
    return texts

def analyze_mood(texts):
    """Analyze texts for mood indicators."""
    scores = Counter()
    
    for i, text in enumerate(texts[:5]):
        weight = RECENCY_WEIGHTS[i] if i < len(RECENCY_WEIGHTS) else 0.1
        
        for mood, words in MOOD_WORDS.items():
            for word in words:
                count = text.count(word.lower())
                scores[mood] += count * weight
    
    # Normalize
    total = sum(scores.values()) or 1
    normalized = {mood: round(score / total * 100, 1) for mood, score in scores.items()}
    
    # Find dominant mood
    if scores:
        dominant = scores.most_common(1)[0][0]
    else:
        dominant = "neutral"
    
    return {
        "dominant": dominant,
        "scores": dict(scores.most_common()),
        "normalized": normalized,
        "analyzed_at": datetime.now().isoformat()
    }

def describe_mood(analysis):
    """Generate human-readable mood description."""
    dominant = analysis["dominant"]
    scores = analysis["normalized"]
    
    descriptions = {
        "energetic": "Running hot. Building things, making progress.",
        "calm": "Steady state. Present but not pushing.",
        "contemplative": "Thinking mode. Processing, wondering, questioning.",
        "focused": "Deep work. Head down, getting things done.",
        "playful": "Light mood. Humor and warmth in the mix.",
        "tired": "Low energy. The ghost is resting.",
        "uncertain": "Questioning. Not sure which way to go.",
        "neutral": "Baseline. No strong signal either way."
    }
    
    desc = descriptions.get(dominant, "Unknown state.")
    
    # Secondary moods
    sorted_scores = sorted(scores.items(), key=lambda x: -x[1])
    secondary = [m for m, s in sorted_scores[1:3] if s > 10]
    
    if secondary:
        desc += f" Undertones of {', '.join(secondary)}."
    
    return desc

def generate_visualization(analysis):
    """ASCII visualization of mood state."""
    scores = analysis["normalized"]
    
    lines = ["╭─────────────────────────────╮"]
    lines.append("│       MOOD RING             │")
    lines.append("├─────────────────────────────┤")
    
    for mood, score in sorted(scores.items(), key=lambda x: -x[1])[:5]:
        bar_len = int(score / 5)
        bar = "█" * bar_len + "░" * (20 - bar_len)
        lines.append(f"│ {mood[:10]:10} {bar} │")
    
    lines.append("╰─────────────────────────────╯")
    
    return "\n".join(lines)

# ============ MAIN ============

def main():
    import sys
    
    history_mode = "--history" in sys.argv
    update_mode = "--update" in sys.argv
    
    data = load_mood_history()
    
    if history_mode:
        print("\n=== MOOD HISTORY ===\n")
        for entry in data.get("history", [])[-10:]:
            date = entry["analyzed_at"][:10]
            mood = entry["dominant"]
            print(f"  {date}  →  {mood}")
        print()
        return
    
    # Analyze current mood
    texts = get_recent_text()
    analysis = analyze_mood(texts)
    
    print()
    print(generate_visualization(analysis))
    print()
    print(f"Dominant: {analysis['dominant'].upper()}")
    print()
    print(describe_mood(analysis))
    print()
    
    if update_mode:
        # Save to history
        data["current"] = analysis
        data["history"].append(analysis)
        # Keep last 30 entries
        data["history"] = data["history"][-30:]
        save_mood_history(data)
        print("(Mood saved to history)")

if __name__ == "__main__":
    main()
