import json
import os
from threading import Lock

DB = "memory/failure_memory.json"
MAX_ENTRIES = 200
_MEMORY_LOCK = Lock()


class LearningAgent:
    def learn(self, test_name, reasoning):
        db_dir = os.path.dirname(DB)
        if db_dir:
            os.makedirs(db_dir, exist_ok=True)

        with _MEMORY_LOCK:
            data = []

            if os.path.exists(DB):
                try:
                    with open(DB, "r", encoding="utf-8") as f:
                        content = f.read().strip()
                        if content:
                            data = json.loads(content)
                except Exception:
                    # Corrupted file → reset
                    data = []

            data.append({"test": test_name, "reason": reasoning})

            # Keep file bounded
            if len(data) > MAX_ENTRIES:
                data = data[-MAX_ENTRIES:]

            temp_path = f"{DB}.tmp"
            with open(temp_path, "w", encoding="utf-8") as f:
                json.dump(data, f, indent=2)
            os.replace(temp_path, DB)
