import json
import os
from datetime import datetime

MEMORY_FILE = "memory/conversation.json"


class Memory:
    def __init__(self):
        os.makedirs("memory", exist_ok=True)
        if not os.path.exists(MEMORY_FILE):
            self.save([])

    def load(self):
        with open(MEMORY_FILE, "r") as f:
            return json.load(f)

    def save(self, data):
        with open(MEMORY_FILE, "w") as f:
            json.dump(data, f, indent=2)

    def add(self, role, content):
        history = self.load()
        history.append(
            {"role": role, "content": content, "timestamp": datetime.now().isoformat()}
        )
        self.save(history)

    def get_context(self, limit=10):
        history = self.load()
        return history[-limit:]

    def clear(self):
        self.save([])
