"""
Advanced Causality - Multi-step causal reasoning
"""

class AdvancedCausality:
    def __init__(self):
        self.causal_chains = []
        self.load_chains()
    
    def load_chains(self):
        """Load complex causal chains"""
        self.causal_chains = [
            {
                "chain": ["rain", "wet_ground", "slippery", "risk_of_falling"],
                "type": "physical"
            },
            {
                "chain": ["practice", "skill_improvement", "better_performance", "success"],
                "type": "learning"
            },
            {
                "chain": ["exercise", "stronger_muscles", "better_endurance", "health"],
                "type": "biological"
            },
            {
                "chain": ["investment", "company_growth", "profit", "wealth"],
                "type": "economic"
            }
        ]
    
    def predict_outcome(self, starting_condition, steps=3):
        """Predict outcome of causal chain"""
        for chain_data in self.causal_chains:
            chain = chain_data["chain"]
            if starting_condition.lower() in chain[0].lower():
                # Follow the chain
                result_chain = chain[:min(steps+1, len(chain))]
                return {
                    "start": starting_condition,
                    "chain": result_chain,
                    "final_outcome": result_chain[-1],
                    "type": chain_data["type"],
                    "confidence": 0.8
                }
        
        return {"start": starting_condition, "chain": [], "final_outcome": "unknown"}
    
    def explain_causality(self, cause, effect):
        """Explain how cause leads to effect"""
        for chain_data in self.causal_chains:
            chain = chain_data["chain"]
            
            if cause in chain and effect in chain:
                cause_idx = chain.index(cause)
                effect_idx = chain.index(effect)
                
                if effect_idx > cause_idx:
                    path = chain[cause_idx:effect_idx+1]
                    explanation = f"{cause} leads to {effect} through: "
                    explanation += " → ".join(path)
                    return {"explanation": explanation, "steps": len(path)-1}
        
        return {"explanation": "No clear causal path found", "steps": 0}
    
    def intervene(self, chain_name, intervention_point):
        """Model intervention in causal chain"""
        # Find chain
        for chain_data in self.causal_chains:
            if chain_name in str(chain_data):
                chain = chain_data["chain"]
                
                if intervention_point in chain:
                    idx = chain.index(intervention_point)
                    
                    return {
                        "intervention": intervention_point,
                        "before": chain[:idx+1],
                        "prevented": chain[idx+1:],
                        "message": f"Intervening at '{intervention_point}' prevents {len(chain[idx+1:])} downstream effects"
                    }
        
        return {"intervention": intervention_point, "message": "Intervention point not found"}

if __name__ == "__main__":
    print("ADVANCED CAUSALITY TEST")
    
    causality = AdvancedCausality()
    
    # Test prediction
    print("\n🔮 Predicting from 'practice':")
    result = causality.predict_outcome("practice", steps=3)
    print(f"   Chain: {' → '.join(result['chain'])}")
    print(f"   Final outcome: {result['final_outcome']}")
    
    # Test explanation
    print("\n💡 Explaining practice → success:")
    result = causality.explain_causality("practice", "success")
    print(f"   {result['explanation']}")
    
    # Test intervention
    print("\n🛑 Intervening at 'slippery':")
    result = causality.intervene("physical", "slippery")
    if "prevented" in result:
        print(f"   Prevents: {result['prevented']}")
    
    print(f"\n📊 Causal chains: {len(causality.causal_chains)}")
    
    print("\n✅ ADVANCED CAUSALITY OPERATIONAL")
