#!/usr/bin/env python3
"""
Morning briefing generator - creates a daily summary for the human.
"""

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

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

def get_weather_stub():
    """Placeholder for weather - would need API."""
    return "☀️ Weather check not configured"

def get_tasks_summary():
    """Get task summary."""
    tasks_file = WORKSPACE / "TASKS.md"
    if not tasks_file.exists():
        return None
    
    summary = {'in_progress': [], 'waiting': [], 'inbox': []}
    section = None
    
    with open(tasks_file) as f:
        for line in f:
            if "## Inbox" in line: section = 'inbox'
            elif "## In Progress" in line: section = 'in_progress'
            elif "## Waiting" in line: section = 'waiting'
            elif "## Done" in line: section = None
            elif section and line.strip().startswith("- ["):
                task = line.strip()[6:].strip()  # Remove "- [ ] "
                if task:
                    summary[section].append(task)
    
    return summary

def get_yesterday_notes():
    """Get yesterday's notes summary."""
    yesterday = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
    yesterday_file = WORKSPACE / "memory" / f"{yesterday}.md"
    
    if not yesterday_file.exists():
        return None
    
    content = yesterday_file.read_text()
    lines = [l.strip() for l in content.split('\n') if l.strip() and not l.startswith('#')]
    return lines[:5]  # First 5 non-header lines

def get_inbox_items():
    """Check inbox for pending items."""
    inbox_dir = WORKSPACE / "inbox"
    if not inbox_dir.exists():
        return []
    
    items = []
    for f in inbox_dir.iterdir():
        if f.is_file() and not f.name.startswith('.'):
            items.append(f.name)
    return items

def get_clips_recent():
    """Get recent clips."""
    clips_file = WORKSPACE / "docs" / "clips.json"
    if not clips_file.exists():
        return []
    
    try:
        with open(clips_file) as f:
            clips = json.load(f)
        return clips[:3]
    except:
        return []

def generate_briefing():
    """Generate the morning briefing."""
    now = datetime.now()
    
    lines = []
    lines.append(f"# 📋 Briefing - {now.strftime('%A, %B %d, %Y')}")
    lines.append(f"Generated at {now.strftime('%H:%M')}")
    lines.append("")
    
    # Tasks
    tasks = get_tasks_summary()
    if tasks:
        lines.append("## 🎯 Tasks")
        if tasks['in_progress']:
            lines.append(f"**In Progress ({len(tasks['in_progress'])}):**")
            for t in tasks['in_progress'][:3]:
                lines.append(f"  • {t[:60]}...")
        if tasks['waiting']:
            lines.append(f"**Waiting ({len(tasks['waiting'])}):** {len(tasks['waiting'])} items")
        if tasks['inbox']:
            lines.append(f"**Inbox ({len(tasks['inbox'])}):** {len(tasks['inbox'])} items to triage")
        lines.append("")
    
    # Yesterday
    yesterday = get_yesterday_notes()
    if yesterday:
        lines.append("## 📝 Yesterday")
        for note in yesterday[:3]:
            lines.append(f"  • {note[:60]}")
        lines.append("")
    
    # Inbox
    inbox = get_inbox_items()
    if inbox:
        lines.append("## 📬 Inbox")
        lines.append(f"{len(inbox)} items waiting: {', '.join(inbox[:3])}")
        lines.append("")
    
    # Clips
    clips = get_clips_recent()
    if clips:
        lines.append("## 📎 Recent Clips")
        for clip in clips:
            lines.append(f"  • {clip.get('title', 'Untitled')}")
        lines.append("")
    
    lines.append("---")
    lines.append("*What's the focus today?*")
    
    return "\n".join(lines)

def main():
    briefing = generate_briefing()
    print(briefing)

if __name__ == "__main__":
    main()
