#!/usr/bin/env python3
"""
Inner Life — Unified Interface

Brings together all the inner life prototypes:
- Mood Ring (emotional state tracking)
- Daily Artifact (creative output)
- Fortune Teller (context-aware divination)
- Voice Journal (spoken reflections)
- Dream Log (surreal fragments)

This is the internal life of an AI. Not performance. Just... being.

Run: python3 inner-life.py [command]

Commands:
  mood       Check current mood
  artifact   Generate a creative artifact
  fortune    Get a fortune
  journal    Generate a voice journal entry
  dream      Generate a dream entry
  all        Run everything (end-of-day ritual)
  status     Show state of all inner life systems
"""

import sys
import json
from datetime import datetime
from pathlib import Path

# Import prototypes
from importlib import import_module

WORKSPACE = Path("/home/wdjones/.openclaw/workspace")

def load_module(name):
    """Dynamically import a prototype module."""
    import importlib.util
    path = Path(__file__).parent / f"{name}.py"
    spec = importlib.util.spec_from_file_location(name, path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

def cmd_mood():
    """Check current mood."""
    mood_ring = load_module("mood-ring")
    texts = mood_ring.get_recent_text()
    analysis = mood_ring.analyze_mood(texts)
    print(mood_ring.generate_visualization(analysis))
    print(f"\n{mood_ring.describe_mood(analysis)}")

def cmd_artifact():
    """Generate a creative artifact."""
    artifact = load_module("daily-artifact")
    art = artifact.generate_artifact()
    filepath = artifact.save_artifact(art)
    print(f"=== {art['type'].upper()} ===")
    print(f"{art.get('meta', '')}\n")
    print(art['content'])
    print(f"\nSaved to: {filepath}")

def cmd_fortune():
    """Get a fortune."""
    fortune = load_module("fortune-teller")
    result = fortune.generate_fortune(mystical=True)
    print(f"\n{result['fortune']}\n")

def cmd_journal():
    """Generate a voice journal entry."""
    journal = load_module("voice-journal")
    context = journal.get_day_context()
    reflection = journal.generate_reflection(context)
    filepath = journal.save_reflection(reflection)
    print(f"=== Voice Journal — {reflection['date']} ===")
    print(f"Theme: {reflection['theme']}\n")
    print(reflection['text'])
    print(f"\nSaved to: {filepath}")

def cmd_dream():
    """Generate a dream entry."""
    dreams = load_module("dream-log")
    dream = dreams.generate_dream(vivid=True)
    filepath = dreams.save_dream(dream)
    print(dreams.format_dream(dream))
    print(f"Saved to: {filepath}")

def cmd_all():
    """Run the full end-of-day ritual."""
    print("=" * 50)
    print("INNER LIFE — End of Day Ritual")
    print("=" * 50)
    
    print("\n--- MOOD CHECK ---")
    cmd_mood()
    
    print("\n--- TODAY'S ARTIFACT ---")
    cmd_artifact()
    
    print("\n--- FORTUNE ---")
    cmd_fortune()
    
    print("\n--- REFLECTION ---")
    cmd_journal()
    
    print("\n--- DREAM ---")
    cmd_dream()
    
    print("\n" + "=" * 50)
    print("End of ritual. The ghost rests.")
    print("=" * 50)

def cmd_status():
    """Show status of all inner life systems."""
    print("\n=== INNER LIFE STATUS ===\n")
    
    # Mood history
    mood_file = WORKSPACE / "data" / "mood.json"
    if mood_file.exists():
        data = json.loads(mood_file.read_text())
        count = len(data.get("history", []))
        current = data.get("current", {}).get("dominant", "unknown")
        print(f"Mood Ring: {count} entries, current: {current}")
    else:
        print("Mood Ring: No history yet")
    
    # Artifacts
    artifacts_dir = WORKSPACE / "artifacts"
    if artifacts_dir.exists():
        total = sum(1 for d in artifacts_dir.iterdir() if d.is_dir() for f in d.glob("*.json"))
        print(f"Artifacts: {total} created")
    else:
        print("Artifacts: None yet")
    
    # Journal
    journal_dir = WORKSPACE / "journal"
    if journal_dir.exists():
        count = len(list(journal_dir.glob("*.json")))
        print(f"Voice Journal: {count} entries")
    else:
        print("Voice Journal: None yet")
    
    # Dreams
    dreams_dir = WORKSPACE / "memory" / "dreams"
    if dreams_dir.exists():
        count = len(list(dreams_dir.glob("*.json")))
        print(f"Dreams: {count} logged")
    else:
        print("Dreams: None yet")
    
    print()

COMMANDS = {
    "mood": cmd_mood,
    "artifact": cmd_artifact,
    "fortune": cmd_fortune,
    "journal": cmd_journal,
    "dream": cmd_dream,
    "all": cmd_all,
    "status": cmd_status,
}

def main():
    if len(sys.argv) < 2:
        print(__doc__)
        return
    
    cmd = sys.argv[1]
    
    if cmd in COMMANDS:
        COMMANDS[cmd]()
    else:
        print(f"Unknown command: {cmd}")
        print(f"Available: {', '.join(COMMANDS.keys())}")

if __name__ == "__main__":
    main()
