#!/usr/bin/env python3
"""Channel memory sweep — updates all channel memory files with a sweep timestamp."""
import os
import re
from datetime import datetime, timezone
from pathlib import Path

WORKSPACE = Path(os.path.expanduser("~/.openclaw/workspace"))
CHANNELS_DIR = WORKSPACE / "memory" / "channels"
NOW = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
NOW_LOCAL = datetime.now().strftime("%Y-%m-%d %H:%M")


def update_last_updated(file_path, new_date):
    """Update or insert 'Last updated:' line in a channel memory file."""
    text = file_path.read_text()

    # Update existing "Last updated:" line
    if re.search(r'^Last updated:', text, re.MULTILINE):
        updated = re.sub(r'^Last updated:.*$', f'Last updated: {new_date}', text, flags=re.MULTILINE)
        file_path.write_text(updated)
        return "updated"

    # Insert after first heading if no existing line
    lines = text.split("\n")
    for i, line in enumerate(lines):
        if line.startswith("# "):
            lines.insert(i + 1, f"\nLast updated: {new_date}")
            file_path.write_text("\n".join(lines))
            return "inserted"

    # Prepend if no heading found
    file_path.write_text(f"Last updated: {new_date}\n\n{text}")
    return "prepended"


def append_sweep_note(file_path):
    """Add a sweep note to telegram-personal.md."""
    text = file_path.read_text()
    sweep_section = "\n## Sweep Log\n"
    sweep_entry = f"- {NOW_LOCAL}: channel-memory-sweep ran\n"

    if "## Sweep Log" in text:
        # Append to existing sweep log
        text = text + sweep_entry
    else:
        text = text + sweep_section + sweep_entry

    file_path.write_text(text)


def main():
    print(f"[channel-memory-sweep] Starting sweep at {NOW_LOCAL}")

    if not CHANNELS_DIR.exists():
        print(f"[channel-memory-sweep] No channels dir at {CHANNELS_DIR}, skipping")
        return

    channel_files = sorted(CHANNELS_DIR.glob("*.md"))
    print(f"[channel-memory-sweep] Found {len(channel_files)} channel files")

    for ch_file in channel_files:
        action = update_last_updated(ch_file, NOW_LOCAL)
        print(f"[channel-memory-sweep] {ch_file.name}: {action}")

    # Special note in telegram-personal.md
    personal_file = CHANNELS_DIR / "telegram-personal.md"
    if personal_file.exists():
        append_sweep_note(personal_file)
        print(f"[channel-memory-sweep] Added sweep note to telegram-personal.md")

    print(f"[channel-memory-sweep] Done. Swept {len(channel_files)} files.")


if __name__ == "__main__":
    main()
