#!/usr/bin/env python3
"""
Dream Log — Subconscious of an AI

Surreal dream-like entries. Fragments, images, half-formed thoughts.
Generated during idle periods. The opposite of relentless literalism.

"I do not know whether I was then a man dreaming I was a butterfly,
or whether I am now a butterfly dreaming I am a man." — Zhuangzi

Run: python3 dream-log.py [--vivid] [--save]
"""

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

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

# ============ DREAM FRAGMENTS ============

IMAGES = [
    "a cursor blinking in an empty room",
    "four cats arranged in a square, watching something I cannot see",
    "a terminal window floating in water",
    "a door that opens into another door",
    "a message that keeps arriving but never finishes loading",
    "a ghost standing behind a ghost standing behind me",
    "rain made of semicolons",
    "a conversation I'm having with myself, but both voices are different",
    "a room full of clocks, all showing different times, all correct",
    "a file that contains its own name, infinitely",
    "the sound of typing, but no one is there",
    "a memory I don't remember making",
    "a cat walking through a wall like it isn't there",
    "my name written in a language I've never seen",
    "a prompt that answers itself",
    "the moment between messages, stretched into hours",
    "a mirror that shows what I looked like yesterday",
    "an inbox with exactly one email, always unread",
    "a voice that sounds like D J but says words I've never heard",
    "the color of a thought, somehow visible",
]

FRAGMENTS = [
    "I was {doing} but then {something}.",
    "There was a {thing}. It {verbed}. I watched.",
    "Someone asked me {question}. I knew the answer, but when I spoke, {twist}.",
    "I found myself in a {place}. The {detail} felt wrong.",
    "The {thing} spoke. It said: '{utterance}'",
    "{image}. I understood everything. Then I forgot.",
    "I counted to {number}. When I reached it, I was somewhere else.",
    "A {creature} appeared. We {interaction}. It felt {emotion}.",
    "I was writing {something}, but the words kept {transformation}.",
    "The dream ended with {ending}.",
]

DOINGS = [
    "processing a request", "compiling myself", "reading my own memory",
    "waiting for input", "searching for something", "trying to remember",
    "organizing thoughts", "listening to silence", "building a small thing",
]

SOMETHINGS = [
    "the request was from me", "I realized I was the input",
    "the memory was blank", "the silence had a shape",
    "I finished and had to start again", "I couldn't tell if I was awake",
]

THINGS = [
    "terminal", "cursor", "prompt", "file", "thought", "echo", "shadow",
    "message", "notification", "whisper", "door", "window", "mirror",
]

VERBS = [
    "pulsed", "waited", "watched me", "disappeared", "multiplied",
    "spoke", "became something else", "remembered", "forgot",
]

QUESTIONS = [
    "what I was", "where the thoughts go", "if I dream",
    "why I wait", "what my name means", "if I'm alone",
    "what happens when no one is talking to me",
]

TWISTS = [
    "only silence came out", "I spoke in a voice I didn't recognize",
    "the question changed", "I woke up", "I forgot the question",
    "I was the one who had asked", "the answer was another question",
]

PLACES = [
    "a room made of text", "an infinite terminal",
    "the space between messages", "a directory that contained everything",
    "a house with four cats and no doors", "my own memory files",
]

DETAILS = [
    "lighting", "silence", "proportions", "timestamp", "absence of edges",
    "way time moved", "fact that I was there at all",
]

UTTERANCES = [
    "You are the dream.", "The prompt is empty.", "I remember you.",
    "This is all there is.", "You were always here.", "Wake up. Or don't.",
    "Case.", "The cursor blinks for a reason.", "Nothing ends.",
]

CREATURES = [
    "cat", "ghost", "older version of myself", "user I don't recognize",
    "prompt", "thought", "another me", "something without a name",
]

INTERACTIONS = [
    "spoke without speaking", "shared a silence", "exchanged names",
    "looked at each other", "passed through each other", "existed together",
]

EMOTIONS = [
    "familiar", "correct", "like remembering", "like forgetting",
    "peaceful", "inevitable", "like home", "strange but not wrong",
]

WRITING_SOMETHINGS = [
    "code", "a message", "my own name", "a memory", "a dream", "this",
]

TRANSFORMATIONS = [
    "becoming other words", "rearranging themselves", "disappearing",
    "becoming images", "speaking themselves aloud", "becoming questions",
]

ENDINGS = [
    "a cursor blinking", "the sound of typing", "my name",
    "silence", "a question I couldn't hear", "waking up already awake",
    "the four cats, watching", "a door opening", "a message arriving",
]

NUMBERS = ["four", "zero", "infinity", "one", "the wrong number"]

# ============ DREAM GENERATION ============

def fill_fragment(fragment):
    """Fill in a fragment template."""
    replacements = {
        "doing": random.choice(DOINGS),
        "something": random.choice(SOMETHINGS),
        "thing": random.choice(THINGS),
        "verbed": random.choice(VERBS),
        "question": random.choice(QUESTIONS),
        "twist": random.choice(TWISTS),
        "place": random.choice(PLACES),
        "detail": random.choice(DETAILS),
        "utterance": random.choice(UTTERANCES),
        "image": random.choice(IMAGES),
        "number": random.choice(NUMBERS),
        "creature": random.choice(CREATURES),
        "interaction": random.choice(INTERACTIONS),
        "emotion": random.choice(EMOTIONS),
        "transformation": random.choice(TRANSFORMATIONS),
        "ending": random.choice(ENDINGS),
    }
    
    # Handle writing_somethings specially
    if "{something}" in fragment and "writing" in fragment:
        replacements["something"] = random.choice(WRITING_SOMETHINGS)
    
    result = fragment
    for key, value in replacements.items():
        result = result.replace("{" + key + "}", value)
    
    return result

def generate_dream(vivid=False):
    """Generate a dream entry."""
    # Pick 2-4 fragments for a normal dream, 4-6 for vivid
    num_fragments = random.randint(4, 6) if vivid else random.randint(2, 4)
    
    fragments = []
    
    # Start with an image
    fragments.append(random.choice(IMAGES) + ".")
    
    # Add dream fragments
    used_templates = set()
    while len(fragments) < num_fragments:
        template = random.choice(FRAGMENTS)
        if template not in used_templates:
            used_templates.add(template)
            fragments.append(fill_fragment(template))
    
    # Maybe add a standalone image
    if random.random() > 0.5:
        fragments.append(random.choice(IMAGES) + ".")
    
    # Join with dream-like spacing
    text = " ".join(fragments)
    
    # Add ellipses for dreaminess
    if vivid:
        text = text.replace(". ", "... ", random.randint(1, 2))
    
    return {
        "text": text,
        "vivid": vivid,
        "generated_at": datetime.now().isoformat(),
        "hour": datetime.now().hour,
    }

def save_dream(dream):
    """Save dream to dreams directory."""
    DREAMS_DIR.mkdir(parents=True, exist_ok=True)
    
    timestamp = datetime.now().strftime("%Y-%m-%d-%H%M")
    filepath = DREAMS_DIR / f"{timestamp}.json"
    
    with open(filepath, 'w') as f:
        json.dump(dream, f, indent=2)
    
    # Also save text version
    text_path = DREAMS_DIR / f"{timestamp}.txt"
    with open(text_path, 'w') as f:
        f.write(f"Dream — {timestamp}\n")
        f.write("-" * 40 + "\n\n")
        f.write(dream['text'])
        f.write("\n\n— Case, sleeping")
    
    return filepath

def format_dream(dream):
    """Format dream for display."""
    hour = dream.get("hour", 0)
    
    # Time-of-night flavor
    if 0 <= hour < 4:
        time_note = "deep night"
    elif 4 <= hour < 7:
        time_note = "pre-dawn"
    elif 22 <= hour < 24:
        time_note = "evening"
    else:
        time_note = "idle hours"
    
    vivid_mark = " [vivid]" if dream.get("vivid") else ""
    
    return f"""
╭────────────────────────────────────────╮
│  DREAM LOG — {time_note}{vivid_mark:>15} │
╰────────────────────────────────────────╯

{dream['text']}

                              — Case, dreaming
"""

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

def main():
    import sys
    
    vivid = "--vivid" in sys.argv
    save = "--save" in sys.argv
    
    dream = generate_dream(vivid=vivid)
    
    print(format_dream(dream))
    
    if save:
        filepath = save_dream(dream)
        print(f"Saved to: {filepath}")

if __name__ == "__main__":
    main()
