#!/usr/bin/env python3
"""
wisdom - Collect and recall quotes, ideas, and wisdom

Store things worth remembering and get random inspiration.
"""

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

WORKSPACE = Path("/home/wdjones/.openclaw/workspace")
WISDOM_FILE = WORKSPACE / "data" / "wisdom.json"

CATEGORIES = {
    'quote': '💬',
    'idea': '💡',
    'lesson': '📚',
    'principle': '⚖️',
    'reminder': '🔔',
    'goal': '🎯',
}

def load_wisdom() -> list:
    """Load wisdom entries."""
    WISDOM_FILE.parent.mkdir(parents=True, exist_ok=True)
    if WISDOM_FILE.exists():
        with open(WISDOM_FILE) as f:
            return json.load(f)
    return []

def save_wisdom(entries: list):
    """Save wisdom entries."""
    with open(WISDOM_FILE, 'w') as f:
        json.dump(entries, f, indent=2)

def add(text: str, category: str = 'quote', source: str = None, tags: list = None):
    """Add a new wisdom entry."""
    entries = load_wisdom()
    
    entry = {
        'id': len(entries) + 1,
        'text': text,
        'category': category if category in CATEGORIES else 'quote',
        'source': source,
        'tags': tags or [],
        'added': datetime.now().isoformat(),
        'views': 0,
    }
    
    entries.append(entry)
    save_wisdom(entries)
    
    emoji = CATEGORIES.get(category, '💬')
    print(f"{emoji} Added #{entry['id']}: {text[:50]}...")

def random_wisdom(category: str = None):
    """Get a random piece of wisdom."""
    entries = load_wisdom()
    
    if not entries:
        print("No wisdom yet. Add some with: wisdom add <text>")
        return
    
    if category:
        entries = [e for e in entries if e['category'] == category]
        if not entries:
            print(f"No entries in category: {category}")
            return
    
    entry = random.choice(entries)
    entry['views'] += 1
    save_wisdom(load_wisdom())  # Update view count
    
    show_entry(entry)

def show_entry(entry: dict):
    """Display a wisdom entry nicely."""
    emoji = CATEGORIES.get(entry['category'], '💬')
    
    print()
    print("─" * 50)
    print(f"{emoji} {entry['text']}")
    if entry.get('source'):
        print(f"   — {entry['source']}")
    print("─" * 50)
    
    tags = ' '.join(f"#{t}" for t in entry.get('tags', []))
    if tags:
        print(f"   {tags}")
    print()

def list_wisdom(category: str = None, limit: int = 10):
    """List wisdom entries."""
    entries = load_wisdom()
    
    if category:
        entries = [e for e in entries if e['category'] == category]
    
    if not entries:
        print("No wisdom found")
        return
    
    print(f"\n📚 Wisdom Collection ({len(entries)} entries)\n")
    
    for entry in entries[-limit:]:
        emoji = CATEGORIES.get(entry['category'], '💬')
        text = entry['text'][:50]
        if len(entry['text']) > 50:
            text += "..."
        print(f"  #{entry['id']:3} {emoji} {text}")
    
    print()

def search_wisdom(query: str):
    """Search wisdom entries."""
    entries = load_wisdom()
    query_lower = query.lower()
    
    matches = []
    for entry in entries:
        searchable = f"{entry['text']} {entry.get('source', '')} {' '.join(entry.get('tags', []))}".lower()
        if query_lower in searchable:
            matches.append(entry)
    
    if not matches:
        print(f"No matches for: {query}")
        return
    
    print(f"\n🔍 Found {len(matches)} matches:\n")
    for entry in matches:
        emoji = CATEGORIES.get(entry['category'], '💬')
        print(f"  #{entry['id']} {emoji} {entry['text'][:50]}...")
    print()

def daily():
    """Show the daily wisdom (same one each day, changes daily)."""
    entries = load_wisdom()
    
    if not entries:
        print("No wisdom yet. Add some with: wisdom add <text>")
        return
    
    # Use the date as seed for consistent daily selection
    day_seed = int(datetime.now().strftime("%Y%m%d"))
    random.seed(day_seed)
    entry = random.choice(entries)
    random.seed()  # Reset seed
    
    print("\n🌅 Today's Wisdom:")
    show_entry(entry)

def main():
    if len(sys.argv) < 2:
        print("Usage:")
        print("  wisdom                     - Random wisdom")
        print("  wisdom daily               - Today's wisdom")
        print("  wisdom add <text>          - Add wisdom")
        print("  wisdom add -c quote <text> - Add with category")
        print("  wisdom add -s 'Author' <text> - Add with source")
        print("  wisdom list [category]     - List entries")
        print("  wisdom search <query>      - Search")
        print("")
        print(f"Categories: {', '.join(CATEGORIES.keys())}")
        
        # Show random by default
        random_wisdom()
        return
    
    cmd = sys.argv[1]
    
    if cmd == 'daily':
        daily()
    elif cmd == 'add' and len(sys.argv) > 2:
        # Parse arguments
        args = sys.argv[2:]
        category = 'quote'
        source = None
        
        # Check for flags
        while args and args[0].startswith('-'):
            if args[0] == '-c' and len(args) > 1:
                category = args[1]
                args = args[2:]
            elif args[0] == '-s' and len(args) > 1:
                source = args[1]
                args = args[2:]
            else:
                args = args[1:]
        
        text = ' '.join(args)
        add(text, category, source)
    
    elif cmd == 'list':
        category = sys.argv[2] if len(sys.argv) > 2 else None
        list_wisdom(category)
    
    elif cmd == 'search' and len(sys.argv) > 2:
        search_wisdom(' '.join(sys.argv[2:]))
    
    else:
        random_wisdom()

if __name__ == "__main__":
    main()
