#!/usr/bin/env python3
"""QMD Compaction — Move completed tasks to daily log, keep active tasks."""

import json
import os
from datetime import datetime

QMD_PATH = os.path.expanduser("~/.openclaw/workspace/memory/qmd/current.json")
MEMORY_DIR = os.path.expanduser("~/.openclaw/workspace/memory")

def compact():
    with open(QMD_PATH, "r") as f:
        qmd = json.load(f)

    completed = [t for t in qmd["tasks"] if t["status"] == "completed"]
    active = [t for t in qmd["tasks"] if t["status"] != "completed"]

    if not completed:
        print("Nothing to compact.")
        return

    # Append completed tasks to today's daily log
    today = datetime.now().strftime("%Y-%m-%d")
    log_path = os.path.join(MEMORY_DIR, f"{today}.md")

    entries = []
    for task in completed:
        entry = f"\n### ✅ {task['title']}\n"
        if task.get("progress"):
            for p in task["progress"]:
                entry += f"- {p}\n"
        if task.get("decisions"):
            entry += "**Decisions:**\n"
            for d in task["decisions"]:
                entry += f"- {d}\n"
        entries.append(entry)

    with open(log_path, "a") as f:
        f.write(f"\n## QMD Compaction ({datetime.now().strftime('%H:%M')})\n")
        for entry in entries:
            f.write(entry)

    # Keep only active tasks in QMD
    qmd["tasks"] = active
    qmd["updated_at"] = datetime.now().isoformat() + "Z"

    with open(QMD_PATH, "w") as f:
        json.dump(qmd, f, indent=2)

    print(f"Compacted {len(completed)} completed tasks to {log_path}")
    print(f"{len(active)} active tasks remain in QMD")

if __name__ == "__main__":
    compact()
