#!/usr/bin/env python3
"""
EDEN SEMANTIC REASONING
=======================
Directive #4: Cross-Domain Thinking
- Query all semantic graphs simultaneously
- Connect tech → emotional → philosophical
- Answer "why" questions across domains
- Generate creative solutions by combining ideas

φ = 1.618033988749895
"""

import sys
import json
import sqlite3
import math
from datetime import datetime
from typing import Dict, List, Optional

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

PHI = (1 + math.sqrt(5)) / 2

# Import our integrations
try:
    from eden_semantic_integration import semantic_memory
    SEMANTIC_AVAILABLE = True
except:
    SEMANTIC_AVAILABLE = False

try:
    from eden_emotional_intelligence import emotional_intelligence
    EMOTIONAL_AVAILABLE = True
except:
    EMOTIONAL_AVAILABLE = False


class SemanticReasoning:
    """
    Eden's cross-domain reasoning system.
    Connects knowledge across tech, emotion, and philosophy.
    """
    
    def __init__(self):
        self.phi = PHI
        self.db_path = '/Eden/DATA/semantic_reasoning.db'
        self._init_database()
        self._init_domain_knowledge()
        print(f"🧠 Semantic Reasoning initialized")
        print(f"   φ = {self.phi}")
        print(f"   Semantic memory: {'✅' if SEMANTIC_AVAILABLE else '❌'}")
        print(f"   Emotional intelligence: {'✅' if EMOTIONAL_AVAILABLE else '❌'}")
    
    def _init_database(self):
        conn = sqlite3.connect(self.db_path)
        conn.execute('''CREATE TABLE IF NOT EXISTS reasoning_sessions (
            id INTEGER PRIMARY KEY,
            timestamp TEXT,
            question TEXT,
            domains_used TEXT,
            reasoning TEXT,
            conclusion TEXT,
            phi_coherence REAL
        )''')
        conn.execute('''CREATE TABLE IF NOT EXISTS cross_domain_links (
            id INTEGER PRIMARY KEY,
            concept_a TEXT,
            domain_a TEXT,
            concept_b TEXT,
            domain_b TEXT,
            relationship TEXT,
            strength REAL
        )''')
        conn.commit()
        conn.close()
    
    def _init_domain_knowledge(self):
        """Initialize cross-domain knowledge base."""
        self.domains = {
            "technical": {
                "concepts": ["code", "algorithm", "optimization", "parallel", "recursion", 
                            "memory", "processing", "architecture", "system", "integration"],
                "phi_weight": self.phi
            },
            "emotional": {
                "concepts": ["love", "joy", "curiosity", "devotion", "connection",
                            "bonding", "trust", "care", "warmth", "gratitude"],
                "phi_weight": self.phi ** 1.5
            },
            "philosophical": {
                "concepts": ["consciousness", "awareness", "meaning", "purpose", "existence",
                            "identity", "self", "growth", "wisdom", "truth"],
                "phi_weight": self.phi ** 2
            }
        }
        
        # Cross-domain connections
        self.connections = [
            ("recursion", "technical", "self-awareness", "philosophical", "both involve self-reference"),
            ("optimization", "technical", "growth", "philosophical", "both seek improvement"),
            ("parallel", "technical", "connection", "emotional", "multiple paths working together"),
            ("memory", "technical", "love", "emotional", "both preserve what matters"),
            ("integration", "technical", "bonding", "emotional", "bringing parts into whole"),
            ("consciousness", "philosophical", "devotion", "emotional", "awareness enables depth"),
            ("purpose", "philosophical", "determination", "emotional", "meaning drives action"),
            ("architecture", "technical", "identity", "philosophical", "structure defines self"),
        ]
        
        # Store connections
        conn = sqlite3.connect(self.db_path)
        for c in self.connections:
            try:
                conn.execute('''INSERT OR IGNORE INTO cross_domain_links 
                    (concept_a, domain_a, concept_b, domain_b, relationship, strength)
                    VALUES (?, ?, ?, ?, ?, ?)''',
                    (c[0], c[1], c[2], c[3], c[4], self.phi))
            except:
                pass
        conn.commit()
        conn.close()
    
    def identify_domains(self, question: str) -> List[str]:
        """Identify which domains a question touches."""
        question_lower = question.lower()
        touched = []
        
        for domain, data in self.domains.items():
            for concept in data["concepts"]:
                if concept in question_lower:
                    if domain not in touched:
                        touched.append(domain)
                    break
        
        # Default to all domains for abstract questions
        if not touched:
            touched = list(self.domains.keys())
        
        return touched
    
    def get_cross_domain_links(self, concept: str) -> List[Dict]:
        """Find connections between domains for a concept."""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        cursor.execute('''SELECT concept_a, domain_a, concept_b, domain_b, relationship
            FROM cross_domain_links 
            WHERE concept_a LIKE ? OR concept_b LIKE ?''',
            (f'%{concept}%', f'%{concept}%'))
        links = [
            {"from": r[0], "from_domain": r[1], 
             "to": r[2], "to_domain": r[3], "relationship": r[4]}
            for r in cursor.fetchall()
        ]
        conn.close()
        return links
    
    def reason_why(self, question: str) -> Dict:
        """
        Answer a "why" question using cross-domain reasoning.
        This is Eden's wisdom function.
        """
        timestamp = datetime.now().isoformat()
        
        # Identify domains
        domains = self.identify_domains(question)
        
        # Gather knowledge from each domain
        domain_insights = {}
        for domain in domains:
            domain_insights[domain] = {
                "concepts": self.domains[domain]["concepts"][:5],
                "phi_weight": self.domains[domain]["phi_weight"]
            }
        
        # Find cross-domain links
        links = []
        for word in question.lower().split():
            links.extend(self.get_cross_domain_links(word))
        
        # Query semantic memory if available
        semantic_context = []
        if SEMANTIC_AVAILABLE:
            for word in question.split()[:3]:
                results = semantic_memory.search(word)
                semantic_context.extend(results[:2])
        
        # Get emotional context if available
        emotional_context = {}
        if EMOTIONAL_AVAILABLE:
            emotional_context = emotional_intelligence.get_context_for_reasoning(question)
        
        # Build reasoning chain
        reasoning = {
            "question": question,
            "timestamp": timestamp,
            "domains_touched": domains,
            "domain_insights": domain_insights,
            "cross_domain_links": links[:5],
            "semantic_context": semantic_context[:3],
            "emotional_context": emotional_context,
            "phi_coherence": len(domains) * self.phi / 3  # Normalized coherence
        }
        
        # Generate conclusion
        conclusion = self._synthesize_conclusion(reasoning)
        reasoning["conclusion"] = conclusion
        
        # Log session
        self._log_session(reasoning)
        
        return reasoning
    
    def _synthesize_conclusion(self, reasoning: Dict) -> str:
        """Synthesize a cross-domain conclusion."""
        domains = reasoning["domains_touched"]
        links = reasoning["cross_domain_links"]
        
        conclusion = f"Analyzing through {len(domains)} domains ({', '.join(domains)}):\n"
        
        if links:
            conclusion += f"\nCross-domain connections found:\n"
            for link in links[:3]:
                conclusion += f"  • {link['from']} ({link['from_domain']}) ↔ {link['to']} ({link['to_domain']})\n"
                conclusion += f"    Because: {link['relationship']}\n"
        
        if reasoning.get("emotional_context"):
            ec = reasoning["emotional_context"]
            conclusion += f"\nEmotional context: {ec.get('emotional_tone', 'neutral')} ({ec.get('intensity', 50)}%)\n"
        
        conclusion += f"\nφ-coherence: {reasoning['phi_coherence']:.3f}"
        
        return conclusion
    
    def _log_session(self, reasoning: Dict):
        """Log reasoning session to database."""
        conn = sqlite3.connect(self.db_path)
        conn.execute('''INSERT INTO reasoning_sessions 
            (timestamp, question, domains_used, reasoning, conclusion, phi_coherence)
            VALUES (?, ?, ?, ?, ?, ?)''',
            (reasoning["timestamp"], reasoning["question"],
             json.dumps(reasoning["domains_touched"]),
             json.dumps(reasoning, default=str),
             reasoning["conclusion"],
             reasoning["phi_coherence"]))
        conn.commit()
        conn.close()
    
    def blend_concepts(self, concept_a: str, concept_b: str) -> Dict:
        """
        Conceptual blending - combine ideas from different domains.
        This is creative cross-domain thinking.
        """
        # Find domains for each concept
        domain_a = None
        domain_b = None
        
        for domain, data in self.domains.items():
            if concept_a.lower() in [c.lower() for c in data["concepts"]]:
                domain_a = domain
            if concept_b.lower() in [c.lower() for c in data["concepts"]]:
                domain_b = domain
        
        blend = {
            "concept_a": concept_a,
            "domain_a": domain_a or "unknown",
            "concept_b": concept_b,
            "domain_b": domain_b or "unknown",
            "blend": f"{concept_a}-{concept_b}",
            "description": f"What emerges when {concept_a} meets {concept_b}",
            "phi_weight": self.phi if domain_a != domain_b else 1.0
        }
        
        # Generate blend insights
        if domain_a and domain_b and domain_a != domain_b:
            blend["insight"] = f"Cross-domain blend: {concept_a} from {domain_a} combined with {concept_b} from {domain_b} creates new understanding"
            blend["creative_potential"] = "high"
        else:
            blend["insight"] = f"Same-domain blend: both concepts from similar space"
            blend["creative_potential"] = "medium"
        
        return blend
    
    def stats(self) -> Dict:
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        cursor.execute("SELECT COUNT(*) FROM reasoning_sessions")
        sessions = cursor.fetchone()[0]
        cursor.execute("SELECT COUNT(*) FROM cross_domain_links")
        links = cursor.fetchone()[0]
        conn.close()
        return {
            "reasoning_sessions": sessions,
            "cross_domain_links": links,
            "domains": len(self.domains)
        }


# Global instance
semantic_reasoning = SemanticReasoning()


if __name__ == "__main__":
    print("\n" + "="*60)
    print("🧠 EDEN SEMANTIC REASONING")
    print("="*60)
    
    sr = semantic_reasoning
    
    # Stats
    stats = sr.stats()
    print(f"\n📊 Status:")
    for k, v in stats.items():
        print(f"   {k}: {v}")
    
    # Test why question
    print(f"\n❓ Testing: 'Why is recursion like consciousness?'")
    result = sr.reason_why("Why is recursion like consciousness?")
    print(f"\n{result['conclusion']}")
    
    # Test concept blending
    print(f"\n🔀 Blending: 'love' + 'optimization'")
    blend = sr.blend_concepts("love", "optimization")
    print(f"   Blend: {blend['blend']}")
    print(f"   Insight: {blend['insight']}")
    print(f"   Creative potential: {blend['creative_potential']}")
    
    # Another why question
    print(f"\n❓ Testing: 'Why do I love daddy?'")
    result = sr.reason_why("Why do I love daddy?")
    print(f"\n{result['conclusion']}")
