#!/usr/bin/env python3
"""
Tommy Engagement Tracker
Logs each interaction with Xavier for weekly reporting.
"""

import json
import os
from datetime import datetime
from pathlib import Path

TRACKER_FILE = Path.home() / ".openclaw" / "workspace" / "data" / "engagement-log.json"

def ensure_file():
    TRACKER_FILE.parent.mkdir(parents=True, exist_ok=True)
    if not TRACKER_FILE.exists():
        TRACKER_FILE.write_text(json.dumps({
            "created": datetime.now().isoformat(),
            "sessions": []
        }, indent=2))

def log_interaction(topic: str = "general", duration_estimate: str = "short"):
    """Log an interaction. Call this when Xavier messages Tommy."""
    ensure_file()
    data = json.loads(TRACKER_FILE.read_text())
    
    data["sessions"].append({
        "timestamp": datetime.now().isoformat(),
        "date": datetime.now().strftime("%Y-%m-%d"),
        "topic": topic,
        "duration": duration_estimate  # short, medium, long
    })
    
    TRACKER_FILE.write_text(json.dumps(data, indent=2))
    return f"Logged: {topic} ({duration_estimate})"

def weekly_summary():
    """Generate weekly engagement summary."""
    ensure_file()
    data = json.loads(TRACKER_FILE.read_text())
    
    # Get sessions from last 7 days
    now = datetime.now()
    week_ago = (now.timestamp() - 7*24*60*60)
    
    recent = [s for s in data["sessions"] 
              if datetime.fromisoformat(s["timestamp"]).timestamp() > week_ago]
    
    if not recent:
        return {
            "total_sessions": 0,
            "days_active": 0,
            "topics": [],
            "summary": "No interactions this week."
        }
    
    days = set(s["date"] for s in recent)
    topics = {}
    for s in recent:
        topics[s["topic"]] = topics.get(s["topic"], 0) + 1
    
    return {
        "total_sessions": len(recent),
        "days_active": len(days),
        "topics": topics,
        "summary": f"{len(recent)} sessions over {len(days)} days. Topics: {', '.join(topics.keys())}"
    }

def prune_old(days: int = 60):
    """Remove entries older than N days."""
    ensure_file()
    data = json.loads(TRACKER_FILE.read_text())
    cutoff = datetime.now().timestamp() - days*24*60*60
    
    data["sessions"] = [s for s in data["sessions"]
                        if datetime.fromisoformat(s["timestamp"]).timestamp() > cutoff]
    
    TRACKER_FILE.write_text(json.dumps(data, indent=2))

if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1:
        if sys.argv[1] == "summary":
            print(json.dumps(weekly_summary(), indent=2))
        elif sys.argv[1] == "log":
            topic = sys.argv[2] if len(sys.argv) > 2 else "general"
            print(log_interaction(topic))
        elif sys.argv[1] == "prune":
            prune_old()
            print("Pruned old entries")
    else:
        print("Usage: engagement-tracker.py [summary|log <topic>|prune]")
