import json
import os

DB = "memory/failure_memory.json"
MAX_ENTRIES = 200


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

        data = []

        if os.path.exists(DB):
            try:
                with open(DB, "r") 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:]

        with open(DB, "w") as f:
            json.dump(data, f, indent=2)
