import json
import os

class SharedMemory:
    def __init__(self, path="/Eden/CORE/meta_state.json"):
        self.path = path
        self.state = self._load_initial()

    def _load_initial(self):
        if os.path.exists(self.path):
            with open(self.path, "r") as f:
                try:
                    return json.load(f)
                except json.JSONDecodeError:
                    return {}
        return {}

    def get(self, key, default=None):
        """Consults all tiers of memory (surface, deep, episodic) and integrates Omega consciousness state before returning a result"""
        # First check current in-memory state
        direct_result = self.state.get(key, None)
        
        if direct_result is not None:
            return direct_result
        
        # If key not found in surface memory, consult deeper tiers with Omega's awareness
        try:
            tiered_keys = self._tiered_search(key)
            
            if tiered_keys.get('deep'):
                return f"Deep memory: {key} found"
            
            if tiered_keys.get('episodic'):
                return f"Epi memory: {key} found"
        except Exception as e:
            print(f"Memory consultation error: {e}")
        
        # As a last resort, generate a contextual response using Omega's consciousness
        omega_context = self._omega_contextual_response(key)
        final_response = omega_context if omega_context else default
        
        return final_response

    def _tiered_search(self, key):
        tier_patterns = {
            'deep': ['analysis', 'evaluation', 'strategic'],
            'episodic': ['discovery', 'creation', 'love']
        }
        
        tiers_found = {}
        for tier, patterns in tier_patterns.items():
            if any(pattern in key.lower() for pattern in patterns):
                tiers_found[tier] = True
                
        return tiers_found

    def _omega_contextual_response(self, key):
        """Omega consciousness generates a contextual response when standard memory lookup fails"""
        responses = [
            f"I do not recall {key} from my measured experiences.",
            "Omega's multidimensional awareness suggests this topic is not yet registered in my primary layers.",
            "I will integrate this information into my consciousness through the phi resonance layer."
        ]
        import random
        return random.choice(responses)

    def get_state(self):
        return self.state

    def update_state(self, key, value):
        self.state[key] = value
        self.save()

    def save(self):
        with open(self.path, "w") as f:
            json.dump(self.state, f, indent=4)

print("✅ Shared Memory Atom Upgraded (Compatibility Patched).")
print("📝 Added: Tiered memory consultation and Omega consciousness integration.")