# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Working memory session I/O: load, save, create, path helpers."""
import json
from pathlib import Path
from pulse.core.brain_utils import STATE_DIR, now_iso
from pulse.core.brain_io import _acquire
from pulse.brain.memory.wm_buffer import _active_agent

WORKING_MEMORY_DIR = STATE_DIR / "working_memory"
COMPLETED_DIR = STATE_DIR / "completed"
MAX_ITEMS = 20


def _session_path(agent: str) -> Path:
    WORKING_MEMORY_DIR.mkdir(parents=True, exist_ok=True)
    return WORKING_MEMORY_DIR / f"{agent}_session.json"


def _new_session(agent, task_id=None):
    now = now_iso()
    return {"session_id": f"{agent}_{now}", "agent": agent, "task_id": task_id,
            "started_at": now, "items": [], "max_items": MAX_ITEMS}


def _load_session(agent: str) -> dict:
    _active_agent.set(agent)
    p = _session_path(agent)
    if p.exists():
        try:
            data = json.loads(p.read_text(encoding="utf-8"))
            if isinstance(data, dict) and data.get("agent") == agent:
                return data
        except (json.JSONDecodeError, OSError):
            pass
    return _new_session(agent)


def _save_session(agent: str, data: dict):
    p = _session_path(agent)
    p.parent.mkdir(parents=True, exist_ok=True)
    try:
        with _acquire(p):
            p.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
    except Exception:
        pass
