#!/usr/bin/env python3
"""
gratitude - Daily gratitude log

Track things you're grateful for.
"""

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

WORKSPACE = Path("/home/wdjones/.openclaw/workspace")
GRATITUDE_FILE = WORKSPACE / "data" / "gratitude.json"

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

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

def add_entry(text: str):
    """Add a gratitude entry."""
    entries = load_gratitude()
    
    entry = {
        'id': len(entries) + 1,
        'text': text,
        'date': datetime.now().isoformat(),
    }
    
    entries.append(entry)
    save_gratitude(entries)
    print(f"🙏 Grateful for: {text}")

def show_today():
    """Show today's entries."""
    entries = load_gratitude()
    today = datetime.now().strftime("%Y-%m-%d")
    
    today_entries = [e for e in entries if e['date'].startswith(today)]
    
    if not today_entries:
        print("No gratitude entries today. Add one!")
        return
    
    print(f"\n🙏 Today's Gratitude ({len(today_entries)})")
    print("=" * 40)
    
    for e in today_entries:
        print(f"  • {e['text']}")
    
    print()

def show_random():
    """Show a random past gratitude."""
    entries = load_gratitude()
    
    if not entries:
        print("No entries yet")
        return
    
    entry = random.choice(entries)
    date = entry['date'][:10]
    
    print(f"\n🌟 From {date}:")
    print(f"   {entry['text']}")
    print()

def show_recent(days: int = 7):
    """Show recent gratitude."""
    entries = load_gratitude()
    cutoff = datetime.now() - timedelta(days=days)
    
    recent = [e for e in entries if datetime.fromisoformat(e['date']) > cutoff]
    
    if not recent:
        print(f"No entries in the last {days} days")
        return
    
    print(f"\n🙏 Recent Gratitude ({len(recent)})")
    print("=" * 40)
    
    # Group by date
    by_date = {}
    for e in recent:
        date = e['date'][:10]
        if date not in by_date:
            by_date[date] = []
        by_date[date].append(e['text'])
    
    for date in sorted(by_date.keys(), reverse=True):
        print(f"\n  {date}")
        for text in by_date[date]:
            print(f"    • {text}")
    
    print()

def stats():
    """Show gratitude statistics."""
    entries = load_gratitude()
    
    if not entries:
        print("No entries yet")
        return
    
    # Count by day
    by_date = {}
    for e in entries:
        date = e['date'][:10]
        by_date[date] = by_date.get(date, 0) + 1
    
    print(f"\n📊 Gratitude Stats")
    print("=" * 40)
    print(f"  Total entries: {len(entries)}")
    print(f"  Days logged: {len(by_date)}")
    print(f"  Avg per day: {len(entries) / len(by_date):.1f}")
    print()

def main():
    if len(sys.argv) < 2:
        show_today()
        return
    
    cmd = sys.argv[1]
    
    if cmd in ['add', '-a'] and len(sys.argv) > 2:
        text = ' '.join(sys.argv[2:])
        add_entry(text)
    
    elif cmd == 'today':
        show_today()
    
    elif cmd == 'random':
        show_random()
    
    elif cmd == 'recent':
        days = int(sys.argv[2]) if len(sys.argv) > 2 else 7
        show_recent(days)
    
    elif cmd == 'stats':
        stats()
    
    else:
        # Treat as entry
        text = ' '.join(sys.argv[1:])
        add_entry(text)

if __name__ == "__main__":
    main()
