"""
工作记忆 — 当前会话状态
存储格式: memory/working/session.json
"""

import json
from pathlib import Path
from datetime import datetime


class WorkingMemory:
    """工作记忆: 当前会话的临时状态"""

    def __init__(self, storage_dir: Path):
        self.storage_dir = Path(storage_dir)
        self.storage_dir.mkdir(parents=True, exist_ok=True)
        self._session_path = self.storage_dir / "session.json"

    def read(self) -> str:
        """读取当前工作记忆为可读文本"""
        data = self._read_raw()
        if not data:
            return ""

        lines = []
        lines.append(f"会话开始: {data.get('session_start', '未知')}")
        lines.append(f"最后交互: {data.get('last_interaction', '未知')}")

        context = data.get("context", {})
        if context:
            lines.append("\n当前上下文:")
            for k, v in context.items():
                lines.append(f"  - {k}: {v}")

        notes = data.get("notes", [])
        if notes:
            lines.append("\n会话笔记:")
            for note in notes[-5:]:  # 最近 5 条
                lines.append(f"  - {note}")

        return "\n".join(lines)

    def update_last_interaction(self, timestamp: str):
        """更新最后交互时间"""
        data = self._read_raw()
        data["last_interaction"] = timestamp
        self._write_raw(data)

    def set_context(self, key: str, value: str):
        """设置上下文键值"""
        data = self._read_raw()
        if "context" not in data:
            data["context"] = {}
        data["context"][key] = value
        self._write_raw(data)

    def get_context(self, key: str) -> str:
        """获取上下文值"""
        data = self._read_raw()
        return data.get("context", {}).get(key, "")

    def add_note(self, note: str):
        """添加会话笔记"""
        data = self._read_raw()
        if "notes" not in data:
            data["notes"] = []
        data["notes"].append(f"[{datetime.now().strftime('%H:%M')}] {note}")
        self._write_raw(data)

    def clear(self):
        """清除工作记忆"""
        self._write_raw({
            "session_start": datetime.now().isoformat(),
            "last_interaction": "",
            "context": {},
            "notes": [],
        })

    def _read_raw(self) -> dict:
        if not self._session_path.exists():
            return {
                "session_start": datetime.now().isoformat(),
                "last_interaction": "",
                "context": {},
                "notes": [],
            }
        with open(self._session_path, "r", encoding="utf-8") as f:
            return json.load(f)

    def _write_raw(self, data: dict):
        with open(self._session_path, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
