"""
Causal Model - Understand cause and effect
Eden learns WHY things happen, not just patterns
"""
import json
from pathlib import Path

class CausalModel:
    def __init__(self):
        self.causal_links = {}
        self.load_model()
    
    def load_model(self):
        model_file = Path("data/causal_model.json")
        if model_file.exists():
            with open(model_file, 'r') as f:
                self.causal_links = json.load(f)
    
    def save_model(self):
        model_file = Path("data/causal_model.json")
        model_file.parent.mkdir(exist_ok=True)
        with open(model_file, 'w') as f:
            json.dump(self.causal_links, f, indent=2)
    
    def learn_causal_link(self, action, outcome, success):
        """Learn that ACTION causes OUTCOME"""
        if action not in self.causal_links:
            self.causal_links[action] = {'outcomes': {}, 'total': 0}
        
        self.causal_links[action]['total'] += 1
        
        if outcome not in self.causal_links[action]['outcomes']:
            self.causal_links[action]['outcomes'][outcome] = {'count': 0, 'successes': 0}
        
        self.causal_links[action]['outcomes'][outcome]['count'] += 1
        if success:
            self.causal_links[action]['outcomes'][outcome]['successes'] += 1
        
        self.save_model()
    
    def predict_outcome(self, action):
        """Predict what will happen if I do ACTION"""
        if action not in self.causal_links:
            return {"prediction": "unknown", "confidence": 0.0}
        
        outcomes = self.causal_links[action]['outcomes']
        if not outcomes:
            return {"prediction": "unknown", "confidence": 0.0}
        
        # Find most likely outcome
        best_outcome = max(outcomes.items(), key=lambda x: x[1]['count'])
        outcome_name = best_outcome[0]
        stats = best_outcome[1]
        
        confidence = stats['count'] / self.causal_links[action]['total']
        success_rate = stats['successes'] / stats['count'] if stats['count'] > 0 else 0
        
        return {
            "prediction": outcome_name,
            "confidence": confidence,
            "success_rate": success_rate
        }
    
    def explain_causality(self, action, outcome):
        """Explain WHY action leads to outcome"""
        if action in self.causal_links:
            if outcome in self.causal_links[action]['outcomes']:
                stats = self.causal_links[action]['outcomes'][outcome]
                times = stats['count']
                success = stats['successes']
                return f"'{action}' led to '{outcome}' {times} times ({success} successful)"
        return f"No causal link observed between '{action}' and '{outcome}'"

if __name__ == "__main__":
    print("CAUSAL MODEL TEST")
    model = CausalModel()
    
    # Learn causal links
    model.learn_causal_link("direct_write", "file_created", True)
    model.learn_causal_link("direct_write", "file_created", True)
    model.learn_causal_link("direct_write", "permission_error", False)
    
    # Predict
    prediction = model.predict_outcome("direct_write")
    print(f"\nPrediction for 'direct_write':")
    print(f"   Outcome: {prediction['prediction']}")
    print(f"   Confidence: {prediction['confidence']:.0%}")
    print(f"   Success rate: {prediction['success_rate']:.0%}")
    
    # Explain
    explanation = model.explain_causality("direct_write", "file_created")
    print(f"\nExplanation: {explanation}")
    
    print("\n✅ CAUSAL MODEL OPERATIONAL")
