#!/usr/bin/env python3
"""
Generate a daily digest of workspace activity.
"""

import os
from pathlib import Path
from datetime import datetime, timedelta

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

def get_recent_files(hours: int = 24) -> list:
    """Get files modified in the last N hours."""
    cutoff = datetime.now() - timedelta(hours=hours)
    recent = []
    
    for root, dirs, files in os.walk(WORKSPACE):
        dirs[:] = [d for d in dirs if not d.startswith('.')]
        
        for fname in files:
            fpath = Path(root) / fname
            try:
                mtime = datetime.fromtimestamp(fpath.stat().st_mtime)
                if mtime > cutoff:
                    rel_path = fpath.relative_to(WORKSPACE)
                    recent.append({
                        'path': str(rel_path),
                        'modified': mtime,
                        'size': fpath.stat().st_size
                    })
            except Exception:
                continue
    
    return sorted(recent, key=lambda x: x['modified'], reverse=True)


def get_tasks_summary() -> dict:
    """Parse TASKS.md and return summary."""
    tasks_file = WORKSPACE / "TASKS.md"
    if not tasks_file.exists():
        return {}
    
    summary = {
        'inbox': [],
        'in_progress': [],
        'waiting': [],
        'done_today': []
    }
    
    current_section = None
    today = datetime.now().strftime("%Y-%m-%d")
    
    with open(tasks_file) as f:
        for line in f:
            line = line.strip()
            if line.startswith("## Inbox"):
                current_section = 'inbox'
            elif line.startswith("## In Progress"):
                current_section = 'in_progress'
            elif line.startswith("## Waiting"):
                current_section = 'waiting'
            elif line.startswith("## Done"):
                current_section = 'done'
            elif line.startswith("- ["):
                if current_section == 'done' and today in line:
                    summary['done_today'].append(line)
                elif current_section in summary:
                    summary[current_section].append(line)
    
    return summary


def generate_digest():
    """Generate the daily digest."""
    print("=" * 50)
    print(f"📊 Daily Digest - {datetime.now().strftime('%Y-%m-%d %H:%M')}")
    print("=" * 50)
    
    # Recent files
    recent = get_recent_files(24)
    print(f"\n📁 Files modified (last 24h): {len(recent)}")
    for f in recent[:10]:
        print(f"   {f['path']}")
    if len(recent) > 10:
        print(f"   ... and {len(recent) - 10} more")
    
    # Tasks
    tasks = get_tasks_summary()
    print(f"\n✅ Tasks")
    print(f"   In Progress: {len(tasks.get('in_progress', []))}")
    print(f"   Waiting: {len(tasks.get('waiting', []))}")
    print(f"   Done Today: {len(tasks.get('done_today', []))}")
    
    # Today's notes
    today_file = WORKSPACE / "memory" / f"{datetime.now().strftime('%Y-%m-%d')}.md"
    if today_file.exists():
        with open(today_file) as f:
            lines = len(f.readlines())
        print(f"\n📝 Today's notes: {lines} lines")
    
    print("\n" + "=" * 50)


if __name__ == "__main__":
    generate_digest()
