#!/usr/bin/env python3
"""
ref - Quick reference and cheatsheet manager

Store and recall quick reference snippets.
"""

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

WORKSPACE = Path("/home/wdjones/.openclaw/workspace")
REF_FILE = WORKSPACE / "data" / "references.json"

def load_refs() -> dict:
    """Load references."""
    REF_FILE.parent.mkdir(parents=True, exist_ok=True)
    if REF_FILE.exists():
        with open(REF_FILE) as f:
            return json.load(f)
    return {}

def save_refs(data: dict):
    """Save references."""
    with open(REF_FILE, 'w') as f:
        json.dump(data, f, indent=2)

def add_ref(key: str, content: str, category: str = 'general'):
    """Add a reference."""
    refs = load_refs()
    
    refs[key] = {
        'content': content,
        'category': category,
        'added': datetime.now().isoformat(),
        'views': 0,
    }
    
    save_refs(refs)
    print(f"📌 Added: {key}")

def get_ref(key: str):
    """Get a reference."""
    refs = load_refs()
    
    # Exact match first
    if key in refs:
        ref = refs[key]
        ref['views'] += 1
        save_refs(refs)
        print(f"\n📌 {key}")
        print("─" * 40)
        print(ref['content'])
        print()
        return
    
    # Partial match
    matches = [k for k in refs if key.lower() in k.lower()]
    if matches:
        if len(matches) == 1:
            get_ref(matches[0])
        else:
            print(f"Multiple matches:")
            for m in matches:
                print(f"  {m}")
    else:
        print(f"Not found: {key}")

def list_refs(category: str = None):
    """List all references."""
    refs = load_refs()
    
    if category:
        refs = {k: v for k, v in refs.items() if v.get('category') == category}
    
    if not refs:
        print("No references yet. Add with: ref add <key> <content>")
        return
    
    # Group by category
    by_cat = {}
    for key, ref in refs.items():
        cat = ref.get('category', 'general')
        if cat not in by_cat:
            by_cat[cat] = []
        by_cat[cat].append(key)
    
    print(f"\n📚 References ({len(refs)})")
    print("=" * 40)
    
    for cat, keys in sorted(by_cat.items()):
        print(f"\n[{cat}]")
        for key in sorted(keys):
            preview = refs[key]['content'][:30].replace('\n', ' ')
            print(f"  {key}: {preview}...")
    
    print()

def main():
    if len(sys.argv) < 2:
        list_refs()
        return
    
    cmd = sys.argv[1]
    
    if cmd == 'add' and len(sys.argv) > 3:
        key = sys.argv[2]
        content = ' '.join(sys.argv[3:])
        add_ref(key, content)
    
    elif cmd == 'list':
        cat = sys.argv[2] if len(sys.argv) > 2 else None
        list_refs(cat)
    
    else:
        # Treat as key lookup
        get_ref(cmd)

if __name__ == "__main__":
    main()
