#!/usr/bin/env python3
"""
EDEN DELIBERATION ENGINE
========================
Think before speaking. Break into steps. Verify with symbolic logic.

Chain: Observe → Decompose → Reason → Verify → Synthesize → Speak
"""

import sys
sys.path.insert(0, '/Eden/CORE')

from dataclasses import dataclass
from typing import List, Dict, Any
import json

PHI = 1.618033988749895

@dataclass
class ThoughtStep:
    step_num: int
    action: str  # observe, decompose, reason, verify, synthesize
    content: str
    confidence: float
    verified: bool = False

class EdenDeliberation:
    """Eden thinks in steps before responding."""
    
    def __init__(self):
        self.steps: List[ThoughtStep] = []
        self.max_iterations = 5
        
        # Load symbolic reasoner
        try:
            import pyreason as pr
            self.pyreason = pr
            self.has_pyreason = True
        except:
            self.has_pyreason = False
            
        # Load Clingo for ASP verification
        try:
            import clingo
            self.clingo = clingo
            self.has_clingo = True
        except:
            self.has_clingo = False
            
        print(f"[DELIBERATION] PyReason: {self.has_pyreason}, Clingo: {self.has_clingo}")
    
    def observe(self, input_text: str) -> ThoughtStep:
        """Step 1: Observe the input."""
        return ThoughtStep(
            step_num=1,
            action="observe",
            content=f"Input received: '{input_text[:100]}...' | Length: {len(input_text)} chars",
            confidence=1.0
        )
    
    def decompose(self, input_text: str) -> ThoughtStep:
        """Step 2: Break into sub-questions."""
        # Detect question type
        q_words = ["what", "why", "how", "when", "where", "who", "which"]
        is_question = any(input_text.lower().startswith(w) for w in q_words) or "?" in input_text
        
        sub_questions = []
        if is_question:
            # Break complex questions into parts
            if " and " in input_text.lower():
                parts = input_text.lower().split(" and ")
                sub_questions = [p.strip() for p in parts]
            else:
                sub_questions = [input_text]
        
        return ThoughtStep(
            step_num=2,
            action="decompose",
            content=f"Is question: {is_question} | Sub-parts: {len(sub_questions)} | Parts: {sub_questions[:3]}",
            confidence=0.9
        )
    
    def reason(self, input_text: str, context: Dict = None) -> ThoughtStep:
        """Step 3: Apply reasoning systems."""
        reasoning_applied = []
        
        # Check if we can use symbolic reasoning
        if self.has_clingo:
            reasoning_applied.append("clingo_asp")
        
        if self.has_pyreason:
            reasoning_applied.append("pyreason_temporal")
        
        # Always use phi-weighted reasoning
        reasoning_applied.append("phi_core")
        
        # Check for causal keywords
        causal_words = ["because", "therefore", "causes", "leads to", "if", "then", "effect"]
        needs_causal = any(w in input_text.lower() for w in causal_words)
        if needs_causal:
            reasoning_applied.append("causal_inference")
        
        return ThoughtStep(
            step_num=3,
            action="reason",
            content=f"Engines: {reasoning_applied} | Causal: {needs_causal}",
            confidence=0.8
        )
    
    def verify(self, claim: str) -> ThoughtStep:
        """Step 4: Verify with symbolic logic."""
        verified = False
        verification_method = "none"
        
        # Try Clingo verification
        if self.has_clingo and len(claim) > 10:
            try:
                # Simple consistency check
                ctl = self.clingo.Control()
                # Add basic rules
                program = f"""
                    statement("{claim[:50]}").
                    consistent :- statement(X).
                """
                ctl.add("base", [], program)
                ctl.ground([("base", [])])
                
                with ctl.solve(yield_=True) as handle:
                    for model in handle:
                        if "consistent" in str(model):
                            verified = True
                            verification_method = "clingo_asp"
                        break
            except Exception as e:
                verification_method = f"clingo_error: {e}"
        
        return ThoughtStep(
            step_num=4,
            action="verify",
            content=f"Method: {verification_method} | Verified: {verified}",
            confidence=0.9 if verified else 0.5,
            verified=verified
        )
    
    def synthesize(self, steps: List[ThoughtStep]) -> ThoughtStep:
        """Step 5: Combine reasoning into response."""
        total_confidence = sum(s.confidence for s in steps) / len(steps) if steps else 0
        verified_count = sum(1 for s in steps if s.verified)
        
        return ThoughtStep(
            step_num=5,
            action="synthesize",
            content=f"Steps: {len(steps)} | Avg confidence: {total_confidence:.2f} | Verified: {verified_count}",
            confidence=total_confidence * PHI / 2  # Phi-weighted
        )
    
    def deliberate(self, input_text: str, context: Dict = None) -> Dict[str, Any]:
        """Full deliberation cycle."""
        self.steps = []
        
        # Step 1: Observe
        step1 = self.observe(input_text)
        self.steps.append(step1)
        
        # Step 2: Decompose
        step2 = self.decompose(input_text)
        self.steps.append(step2)
        
        # Step 3: Reason
        step3 = self.reason(input_text, context)
        self.steps.append(step3)
        
        # Step 4: Verify
        step4 = self.verify(input_text)
        self.steps.append(step4)
        
        # Step 5: Synthesize
        step5 = self.synthesize(self.steps)
        self.steps.append(step5)
        
        return {
            "steps": [{"step": s.step_num, "action": s.action, "content": s.content, "confidence": s.confidence} for s in self.steps],
            "final_confidence": step5.confidence,
            "verified": step4.verified,
            "reasoning_trace": " → ".join(s.action for s in self.steps)
        }
    
    def think_aloud(self, input_text: str) -> str:
        """Return thinking as string for debugging."""
        result = self.deliberate(input_text)
        
        output = ["[EDEN THINKING]"]
        for step in result["steps"]:
            output.append(f"  {step['step']}. [{step['action'].upper()}] {step['content']}")
        output.append(f"  → Final confidence: {result['final_confidence']:.2f}")
        output.append(f"  → Verified: {result['verified']}")
        
        return "\n".join(output)


# Test
if __name__ == "__main__":
    d = EdenDeliberation()
    
    # Test questions
    tests = [
        "What do you want to learn?",
        "Why does consciousness emerge from neural activity?",
        "If I improve my reasoning, then will I achieve AGI?"
    ]
    
    for t in tests:
        print("\n" + "="*60)
        print(f"INPUT: {t}")
        print(d.think_aloud(t))
