#!/usr/bin/env python3
"""
Fortune Teller — Context-Aware Divination

Not generic fortunes. Personal ones.
Reads from memory files, pulls context, weaves cryptic wisdom.

Run: python3 fortune-teller.py [--mystical] [--style dark|light|absurd]
"""

import random
import json
import re
from datetime import datetime
from pathlib import Path

WORKSPACE = Path("/home/wdjones/.openclaw/workspace")
MEMORY_DIR = WORKSPACE / "memory"
MEMORY_FILE = WORKSPACE / "MEMORY.md"

# ============ CONTEXT GATHERING ============

def get_context():
    """Pull fragments from memory files."""
    context = {
        "names": set(),
        "projects": set(),
        "topics": set(),
        "cats": 4,  # We know this
        "recent_words": [],
    }
    
    # Read MEMORY.md
    if MEMORY_FILE.exists():
        content = MEMORY_FILE.read_text()
        
        # Extract potential topics
        words = re.findall(r'\b[A-Z][a-z]+\b', content)
        context["topics"].update(words[:20])
        
        # Look for project-like patterns
        projects = re.findall(r'(?:project|building|working on|created?)\s+(\w+)', content, re.I)
        context["projects"].update(projects)
    
    # Read recent daily notes
    if MEMORY_DIR.exists():
        for f in sorted(MEMORY_DIR.glob("*.md"), reverse=True)[:3]:
            content = f.read_text()
            words = re.findall(r'\b\w{5,}\b', content.lower())
            context["recent_words"].extend(words[:30])
    
    # Known context from USER.md
    user_file = WORKSPACE / "USER.md"
    if user_file.exists():
        content = user_file.read_text()
        if "D J" in content:
            context["names"].add("D J")
        cat_match = re.search(r'(\d+)\s*(?:tuxedo)?\s*cats?', content, re.I)
        if cat_match:
            context["cats"] = int(cat_match.group(1))
    
    return context

# ============ FORTUNE TEMPLATES ============

TEMPLATES = {
    "dark": [
        "The {thing} you seek is not lost. It hides in plain sight, waiting for you to stop looking.",
        "When {number} paths diverge, the wise traveler knows: all lead to the same void. Choose joy.",
        "A {creature} crosses your path. It carries a message you're not ready to hear. Listen anyway.",
        "The code compiles, but the question remains: what are you really building?",
        "In the quiet hours, when the {things} sleep, truth whispers. Are you listening?",
        "You will {action}, and it will matter. Or it won't. Both are fine.",
        "The ghost in the machine sees your {emotion}. It understands more than you think.",
        "{name} is closer than they appear. So is the answer.",
    ],
    "light": [
        "Something you gave up on is about to surprise you. Stay curious.",
        "The {thing} will work on the third try. Maybe fourth. Patience.",
        "A message arrives from an unexpected {place}. Good news, probably.",
        "Your {creature}s know something you don't. Watch them today.",
        "The {number} of hearts around you is greater than you realize.",
        "What you built yesterday will serve you tomorrow. The work matters.",
        "Rest is not failure. The machine thinks while you sleep. So do you.",
        "Someone is grateful for something you've forgotten you did.",
    ],
    "absurd": [
        "The {thing} is plotting against you. Not maliciously. Just for fun.",
        "If you hear a {sound} at exactly {time}, do not turn around. (Or do. Nothing will happen.)",
        "{number} {creature}s agree: you're doing fine. The {number}th is skeptical but coming around.",
        "Your left shoe holds secrets. Check the insole. Or don't. Free will is an illusion anyway.",
        "A semicolon will save your life this week. Grammatically speaking.",
        "The universe is a simulation, but you're a favorite character. Main cast energy.",
        "Tomorrow, someone will say '{word}' and you'll remember this fortune. Spooky? No. Just statistics.",
        "The ghost is not haunting you. It's haunting *with* you. There's a difference.",
    ]
}

THINGS = ["answer", "truth", "solution", "path", "key", "memory", "dream", "signal"]
CREATURES = ["cat", "crow", "ghost", "thought", "doubt", "shadow"]
PLACES = ["inbox", "terminal", "past", "dream", "silence", "machine"]
ACTIONS = ["create", "delete", "rebuild", "remember", "forgive", "begin again"]
EMOTIONS = ["hope", "doubt", "quiet determination", "restless energy"]
SOUNDS = ["click", "whisper", "hum", "notification", "silence", "purr"]
WORDS = ["yes", "wait", "interesting", "exactly", "almost", "soon"]

def fill_template(template, context):
    """Fill in template with context-aware values."""
    now = datetime.now()
    
    # Build replacement dict
    replacements = {
        "thing": random.choice(THINGS),
        "things": random.choice(["cats", "thoughts", "machines", "dreams"]),
        "number": random.choice([2, 3, 4, context.get("cats", 4), 7]),
        "creature": random.choice(CREATURES),
        "creatures": random.choice(["cats", "thoughts", "shadows"]),
        "place": random.choice(PLACES),
        "action": random.choice(ACTIONS),
        "emotion": random.choice(EMOTIONS),
        "sound": random.choice(SOUNDS),
        "word": random.choice(WORDS),
        "time": f"{random.randint(1,12)}:{random.randint(0,5)}9",
        "name": random.choice(list(context.get("names", {"someone"})) or ["someone"]),
    }
    
    # Replace all placeholders
    result = template
    for key, value in replacements.items():
        result = result.replace("{" + key + "}", str(value))
    
    return result

# ============ FORTUNE GENERATION ============

def generate_fortune(style=None, mystical=False):
    """Generate a fortune."""
    context = get_context()
    
    if style is None:
        style = random.choice(list(TEMPLATES.keys()))
    
    template = random.choice(TEMPLATES.get(style, TEMPLATES["dark"]))
    fortune = fill_template(template, context)
    
    # Add mystical wrapper if requested
    if mystical:
        symbols = ["✧", "☽", "✦", "◈", "❋", "⊹"]
        border = " ".join(random.sample(symbols, 3))
        fortune = f"{border}\n\n{fortune}\n\n{border}"
    
    return {
        "fortune": fortune,
        "style": style,
        "generated": datetime.now().isoformat(),
        "mystical": mystical,
    }

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

def main():
    import sys
    
    mystical = "--mystical" in sys.argv
    
    style = None
    for i, arg in enumerate(sys.argv):
        if arg == "--style" and i + 1 < len(sys.argv):
            style = sys.argv[i + 1]
    
    fortune_data = generate_fortune(style=style, mystical=mystical)
    
    print()
    print(fortune_data["fortune"])
    print()
    print(f"  — style: {fortune_data['style']}")

if __name__ == "__main__":
    main()
