#!/usr/bin/env python3
"""
doc-writeup.py - Daily 9am write-up to Ghost for forwarding to Doc.
Reads recent daily memory files and composes a peer-level summary.
Sends via Signal DM to Ghost (+15406208059).
"""

import subprocess
import json
import os
import sys
from datetime import datetime, timedelta

WORKSPACE = "/Users/aicomputer/.openclaw/workspace"
GHOST_SIGNAL = "+15406208059"

def read_file(path):
    try:
        with open(path, "r") as f:
            return f.read()
    except FileNotFoundError:
        return None

def get_recent_daily_notes():
    memory_dir = os.path.join(WORKSPACE, "memory")
    today = datetime.now().date()
    yesterday = today - timedelta(days=1)
    
    notes = []
    for d in [yesterday, today]:
        path = os.path.join(memory_dir, f"{d}.md")
        content = read_file(path)
        if content:
            notes.append(f"=== {d} ===\n{content}")
    
    return "\n\n".join(notes) if notes else "No recent daily notes found."

def compose_writeup():
    today = datetime.now().strftime("%Y-%m-%d")
    notes = get_recent_daily_notes()
    
    writeup = f"""Doc write-up for {today}

Hey Doc,

Here's what Ghost and I have been up to:

{notes}

- Clawstin"""
    return writeup

def send_signal(message):
    cmd = [
        "openclaw", "message", "send",
        "--to", GHOST_SIGNAL,
        "--channel", "signal",
        "--message", message
    ]
    result = subprocess.run(cmd, capture_output=True, text=True)
    return result.returncode == 0, result.stdout, result.stderr

if __name__ == "__main__":
    writeup = compose_writeup()
    success, stdout, stderr = send_signal(writeup)
    if success:
        print("Doc write-up sent successfully.")
    else:
        print(f"Failed to send: {stderr}", file=sys.stderr)
        sys.exit(1)
