import re

from fliiq.runtime.config import resolve_fliiq_dir
from fliiq.runtime.memory.manager import MemoryManager

_DATE_PATTERN = re.compile(r"^\d{4}-\d{2}-\d{2}$")


async def handler(params: dict) -> dict:
    """Write or append to a memory file."""
    name = params["name"]
    content = params["content"]
    mode = params.get("mode", "overwrite")

    manager = MemoryManager(resolve_fliiq_dir() / "memory")
    manager.ensure_dirs()

    if mode == "append" and _DATE_PATTERN.match(name.replace(".md", "")):
        path = manager.append_daily(name.replace(".md", ""), content)
        return {"result": f"Appended to daily log {name}", "path": str(path)}

    path = manager.save_memory(name, content)
    return {"result": f"Wrote memory '{name}'", "path": str(path)}
