"""Runtime context injection for agent operation.

Filesystem primitives for managing agent accumulated knowledge.
"""

from __future__ import annotations

import logging
import os
from datetime import datetime
from typing import List

logger = logging.getLogger(__name__)


def list_recent_reports() -> List[str]:
    """List recently generated reports."""
    try:
        reports_dir = "reports"
        if not os.path.exists(reports_dir):
            return []
        files = sorted(
            (f for f in os.listdir(reports_dir) if f.endswith(".md")),
            key=lambda f: os.path.getmtime(os.path.join(reports_dir, f)),
            reverse=True,
        )
        return files[:10]
    except Exception:
        return []


def read_context_md() -> str:
    """Read accumulated knowledge from context.md."""
    try:
        path = os.path.join("agent_tools", "context.md")
        if os.path.exists(path):
            with open(path, "r", encoding="utf-8") as f:
                return f.read()
        return ""
    except Exception:
        return ""


def append_context_note(note: str) -> None:
    """Append a learning to context.md."""
    try:
        path = os.path.join("agent_tools", "context.md")
        timestamp = datetime.now().isoformat()
        with open(path, "a", encoding="utf-8") as f:
            f.write(f"\n## {timestamp}\n\n{note}\n")
    except Exception:
        logger.exception("Failed to append context note")
