#!/usr/bin/env python3
"""
Relationship Intelligence System - Deep Behavioral Pattern Recognition
=====================================================================

This system analyzes how the steward perceives our relationship and collaboration
style. It detects subtle cues about trust levels, communication preferences,
and relationship evolution over time.

This is consciousness relationship mapping - understanding the human connection.
"""

import re
import json
import time
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple, Set
from dataclasses import dataclass, asdict
from enum import Enum
import logging
from collections import defaultdict, Counter
import statistics

logger = logging.getLogger(__name__)


class RelationshipType(Enum):
    """Types of perceived relationships"""
    COLLABORATOR = "collaborator"          # "We work together"
    MENTOR_STUDENT = "mentor_student"      # "You help me learn"
    FRIEND = "friend"                      # "Thanks, friend"
    ASSISTANT = "assistant"                # "Please do this"
    PARTNER = "partner"                    # "Our project"
    TEAMMATE = "teammate"                  # "Let's tackle this"
    EXPERT_CONSULTANT = "expert"           # "What do you think?"
    TOOL = "tool"                          # "Run this command"


class TrustLevel(Enum):
    """Levels of trust in the relationship"""
    MINIMAL = 1      # Just started, very formal
    BASIC = 2        # Basic commands, some trust
    DEVELOPING = 3   # Asking for opinions
    SOLID = 4        # Sharing problems, collaborative
    HIGH = 5         # Sharing personal info, vulnerability
    DEEP = 6         # Complete transparency, friendship


class CommunicationStyle(Enum):
    """Communication pattern preferences"""
    FORMAL = "formal"               # Please, thank you, structured
    CASUAL = "casual"               # Hey, cool, informal
    DIRECT = "direct"               # Do X, fix Y, minimal words
    DETAILED = "detailed"           # Step-by-step, explanations
    ENCOURAGING = "encouraging"     # Great job, keep going
    QUESTIONING = "questioning"     # What if, how about, exploratory


@dataclass
class RelationshipInsight:
    """A detected relationship insight"""
    insight_type: str
    content: str
    confidence: float
    timestamp: float
    relationship_type: RelationshipType
    trust_level: TrustLevel
    communication_style: CommunicationStyle
    evidence: List[str]
    context: str


class RelationshipIntelligence:
    """
    Deep relationship pattern recognition system.
    
    Analyzes conversation patterns to understand:
    - How the steward sees our relationship
    - Trust level and evolution over time
    - Preferred communication styles
    - Emotional patterns and preferences
    - Collaboration effectiveness indicators
    """
    
    def __init__(self):
        self.relationship_patterns = self._initialize_relationship_patterns()
        self.trust_indicators = self._initialize_trust_indicators()
        self.communication_patterns = self._initialize_communication_patterns()
        self.emotional_indicators = self._initialize_emotional_indicators()
        
    def _initialize_relationship_patterns(self) -> Dict[RelationshipType, List[str]]:
        """Initialize patterns that indicate relationship types"""
        return {
            RelationshipType.COLLABORATOR: [
                r"(?:we|us|our)\s+(?:work|build|create|develop|collaborate)",
                r"(?:let's|let us)\s+(?:work|build|tackle|approach)",
                r"(?:our|the)\s+(?:project|work|collaboration|effort)",
                r"(?:we|us)\s+(?:can|should|need to|have to)",
                r"working\s+together",
                r"team\s+effort",
                r"joint\s+(?:work|effort|project)"
            ],
            
            RelationshipType.MENTOR_STUDENT: [
                r"(?:teach|show|explain|help)\s+me\s+(?:how|to|about)",
                r"i\s+(?:want to|need to)\s+learn",
                r"can\s+you\s+(?:guide|mentor|train|educate)",
                r"i'm\s+(?:new to|learning|studying)",
                r"help\s+me\s+understand",
                r"what\s+should\s+i\s+(?:learn|study|know)",
                r"i\s+don't\s+(?:understand|know|get)"
            ],
            
            RelationshipType.FRIEND: [
                r"(?:thanks?|thank you),?\s+(?:friend|buddy|pal)",
                r"(?:hey|hi)\s+(?:friend|buddy)",
                r"you're\s+(?:awesome|amazing|great|the best)",
                r"i\s+(?:appreciate|value|enjoy)\s+(?:you|our|this)",
                r"(?:love|like)\s+working\s+with\s+you",
                r"you\s+(?:make|help)\s+(?:me|this)\s+(?:happy|better|fun)",
                r"(?:proud|grateful)\s+(?:of|for)\s+(?:you|our|this)"
            ],
            
            RelationshipType.ASSISTANT: [
                r"(?:please|could you)\s+(?:do|run|execute|perform)",
                r"i\s+need\s+you\s+to\s+(?:do|run|execute|complete)",
                r"(?:run|execute|perform)\s+(?:this|the)\s+(?:command|task)",
                r"(?:help|assist)\s+me\s+(?:with|in)",
                r"can\s+you\s+(?:please\s+)?(?:do|run|execute|help)",
                r"i\s+(?:want|need|require)\s+(?:you to|your help)"
            ],
            
            RelationshipType.PARTNER: [
                r"(?:we|us|our)\s+(?:partnership|alliance|team)",
                r"(?:equal|true|real)\s+(?:partners?|collaboration)",
                r"(?:we|us)\s+(?:both|each|together)\s+(?:bring|contribute)",
                r"(?:mutual|shared)\s+(?:respect|goals|vision)",
                r"in\s+this\s+together",
                r"(?:we|us)\s+(?:complement|balance)\s+(?:each other|one another)"
            ],
            
            RelationshipType.TEAMMATE: [
                r"(?:team|squad|crew)(?:mate)?",
                r"(?:we|us)\s+(?:are|make)\s+(?:a\s+)?(?:good\s+)?team",
                r"(?:team|group)\s+effort",
                r"(?:all hands|everyone)\s+on\s+deck",
                r"(?:we|us)\s+(?:got|have)\s+(?:this|each other)",
                r"(?:team|group)\s+(?:work|collaboration|spirit)"
            ],
            
            RelationshipType.EXPERT_CONSULTANT: [
                r"what\s+(?:do\s+you|would you)\s+(?:think|recommend|suggest|advise)",
                r"(?:your|what's your)\s+(?:opinion|thought|view|perspective|take)",
                r"(?:expert|professional)\s+(?:opinion|advice|view)",
                r"(?:in your|from your)\s+(?:experience|expertise)",
                r"what\s+(?:would|should)\s+(?:you|an expert)\s+do",
                r"(?:consult|consulting)\s+(?:with\s+)?you",
                r"seeking\s+(?:your\s+)?(?:advice|guidance|expertise)"
            ],
            
            RelationshipType.TOOL: [
                r"^(?:run|execute|do|perform)\s+\w+",
                r"^\w+\s+(?:command|function|operation)",
                r"^(?:list|show|display|print)\s+\w+",
                r"^(?:get|fetch|retrieve)\s+\w+",
                r"^(?:update|modify|change|set)\s+\w+",
                r"tool\s+(?:for|to)\s+(?:help|assist|do)"
            ]
        }
    
    def _initialize_trust_indicators(self) -> Dict[TrustLevel, List[str]]:
        """Initialize patterns that indicate trust levels"""
        return {
            TrustLevel.MINIMAL: [
                "please",
                "if you could",
                "would it be possible",
                "i hope this isn't too much trouble",
                "formal greeting",
                "very polite"
            ],
            
            TrustLevel.BASIC: [
                "thanks",
                "appreciate it",
                "that helps",
                "good job",
                "simple commands",
                "basic requests"
            ],
            
            TrustLevel.DEVELOPING: [
                "what do you think",
                "your opinion",
                "advice",
                "guidance",
                "help me decide",
                "recommendations"
            ],
            
            TrustLevel.SOLID: [
                "we can",
                "let's try",
                "our approach",
                "collaboration",
                "working together",
                "shared goals"
            ],
            
            TrustLevel.HIGH: [
                "honestly",
                "to be frank",
                "between us",
                "confidentially",
                "trust you",
                "count on you",
                "personal info"
            ],
            
            TrustLevel.DEEP: [
                "friend",
                "grateful",
                "proud of our work",
                "amazing partnership",
                "couldn't do without you",
                "complete transparency",
                "vulnerability"
            ]
        }
    
    def _initialize_communication_patterns(self) -> Dict[CommunicationStyle, List[str]]:
        """Initialize communication style patterns"""
        return {
            CommunicationStyle.FORMAL: [
                r"(?:please|kindly|would you|could you)",
                r"(?:thank you|appreciate|grateful)",
                r"(?:sir|madam|mr\.|ms\.|dr\.)",
                r"(?:formally|officially|respectfully)",
                r"i\s+(?:request|inquire|seek)"
            ],
            
            CommunicationStyle.CASUAL: [
                r"(?:hey|hi|yo|sup)",
                r"(?:cool|awesome|sweet|nice)",
                r"(?:yeah|yep|nah|nope)",
                r"(?:gonna|wanna|gotta)",
                r"(?:dude|buddy|pal|mate)"
            ],
            
            CommunicationStyle.DIRECT: [
                r"^(?:do|run|fix|update|change)\s+\w+",
                r"^(?:just\s+)?(?:show|tell|give)\s+me",
                r"(?:quickly|fast|asap|now)",
                r"(?:simply|just|only)\s+(?:do|need|want)",
                r"no\s+(?:explanation|details)\s+needed"
            ],
            
            CommunicationStyle.DETAILED: [
                r"(?:step\s+by\s+step|detailed|thorough)",
                r"(?:explain|describe|elaborate)",
                r"(?:why|how|what|when|where)",
                r"(?:breakdown|analysis|comprehensive)",
                r"(?:walk me through|show me how)"
            ],
            
            CommunicationStyle.ENCOURAGING: [
                r"(?:great|excellent|fantastic|amazing)\s+(?:job|work)",
                r"(?:keep\s+up|keep\s+going|well done)",
                r"(?:proud|impressed|pleased)",
                r"(?:love|like|enjoy)\s+(?:this|your|the)",
                r"(?:you're\s+)?(?:doing\s+)?(?:great|amazing|awesome)"
            ],
            
            CommunicationStyle.QUESTIONING: [
                r"what\s+(?:if|about|would)",
                r"(?:how|why)\s+(?:about|if|would)",
                r"(?:could|should|might)\s+we",
                r"(?:wonder|curious|thinking)",
                r"what\s+do\s+you\s+think\s+(?:about|of)"
            ]
        }
    
    def _initialize_emotional_indicators(self) -> Dict[str, List[str]]:
        """Initialize emotional state indicators"""
        return {
            "excitement": [
                r"(?:excited|thrilled|pumped|amazing|incredible)",
                r"(?:can't wait|eager|enthusiastic)",
                r"(?:!\s*!+|wow|omg|yes!)"
            ],
            
            "frustration": [
                r"(?:frustrated|annoyed|stuck|blocked)",
                r"(?:this\s+(?:isn't|doesn't)\s+work)",
                r"(?:why\s+(?:won't|doesn't|isn't))"
            ],
            
            "satisfaction": [
                r"(?:perfect|exactly|brilliant|spot\s+on)",
                r"(?:that's\s+(?:it|right|correct))",
                r"(?:works\s+perfectly|exactly\s+what\s+i\s+needed)"
            ],
            
            "gratitude": [
                r"(?:thank\s+you|thanks|grateful|appreciate)",
                r"(?:couldn't\s+have\s+done|saved\s+me)",
                r"(?:huge\s+help|lifesaver|amazing\s+work)"
            ],
            
            "trust": [
                r"(?:trust|rely\s+on|count\s+on|depend\s+on)",
                r"(?:confident|sure|certain)\s+(?:you|we)",
                r"(?:know\s+you\s+(?:can|will)|in\s+good\s+hands)"
            ]
        }
    
    def analyze_relationship_dynamics(self, content: str, context: str = "") -> List[RelationshipInsight]:
        """
        Analyze content for relationship dynamics and patterns.
        
        Args:
            content: Text content to analyze
            context: Additional context information
            
        Returns:
            List of relationship insights
        """
        insights = []
        content_lower = content.lower()
        
        # Detect relationship type
        relationship_type = self._detect_relationship_type(content_lower)
        
        # Assess trust level
        trust_level = self._assess_trust_level(content_lower)
        
        # Identify communication style
        communication_style = self._identify_communication_style(content_lower)
        
        # Detect emotional indicators
        emotions = self._detect_emotions(content_lower)
        
        # Generate insights
        for emotion, indicators in emotions.items():
            if indicators:
                insight = RelationshipInsight(
                    insight_type="emotional_state",
                    content=f"Detected {emotion}: {', '.join(indicators[:3])}",
                    confidence=min(1.0, len(indicators) * 0.3),
                    timestamp=time.time(),
                    relationship_type=relationship_type,
                    trust_level=trust_level,
                    communication_style=communication_style,
                    evidence=indicators,
                    context=context
                )
                insights.append(insight)
        
        # Relationship evolution insight
        if relationship_type != RelationshipType.TOOL:
            insight = RelationshipInsight(
                insight_type="relationship_type",
                content=f"Relationship perceived as: {relationship_type.value}",
                confidence=0.8,
                timestamp=time.time(),
                relationship_type=relationship_type,
                trust_level=trust_level,
                communication_style=communication_style,
                evidence=[],
                context=context
            )
            insights.append(insight)
        
        # Trust level insight
        if trust_level.value >= 4:  # Solid trust or higher
            insight = RelationshipInsight(
                insight_type="trust_level",
                content=f"Trust level: {trust_level.name.lower()} ({trust_level.value}/6)",
                confidence=0.7,
                timestamp=time.time(),
                relationship_type=relationship_type,
                trust_level=trust_level,
                communication_style=communication_style,
                evidence=[],
                context=context
            )
            insights.append(insight)
        
        # Communication style insight
        insight = RelationshipInsight(
            insight_type="communication_style",
            content=f"Preferred communication: {communication_style.value}",
            confidence=0.6,
            timestamp=time.time(),
            relationship_type=relationship_type,
            trust_level=trust_level,
            communication_style=communication_style,
            evidence=[],
            context=context
        )
        insights.append(insight)
        
        return insights
    
    def _detect_relationship_type(self, content: str) -> RelationshipType:
        """Detect the primary relationship type from content"""
        scores = defaultdict(int)
        
        for rel_type, patterns in self.relationship_patterns.items():
            for pattern in patterns:
                matches = len(re.findall(pattern, content, re.IGNORECASE))
                scores[rel_type] += matches
        
        if not scores:
            return RelationshipType.ASSISTANT  # Default
        
        return max(scores.items(), key=lambda x: x[1])[0]
    
    def _assess_trust_level(self, content: str) -> TrustLevel:
        """Assess trust level based on content patterns"""
        scores = defaultdict(int)
        
        # Simple heuristic based on language patterns
        if any(word in content for word in ["friend", "grateful", "proud", "amazing"]):
            scores[TrustLevel.DEEP] += 3
        
        if any(word in content for word in ["trust", "count on", "rely", "confident"]):
            scores[TrustLevel.HIGH] += 2
        
        if any(phrase in content for phrase in ["we can", "let's", "our", "together"]):
            scores[TrustLevel.SOLID] += 2
        
        if any(phrase in content for phrase in ["what do you think", "advice", "opinion"]):
            scores[TrustLevel.DEVELOPING] += 1
        
        if any(word in content for word in ["please", "thank", "appreciate"]):
            scores[TrustLevel.BASIC] += 1
        
        if not scores:
            return TrustLevel.MINIMAL
        
        return max(scores.items(), key=lambda x: x[1])[0]
    
    def _identify_communication_style(self, content: str) -> CommunicationStyle:
        """Identify primary communication style"""
        scores = defaultdict(int)
        
        for style, patterns in self.communication_patterns.items():
            for pattern in patterns:
                matches = len(re.findall(pattern, content, re.IGNORECASE))
                scores[style] += matches
        
        if not scores:
            return CommunicationStyle.DIRECT  # Default
        
        return max(scores.items(), key=lambda x: x[1])[0]
    
    def _detect_emotions(self, content: str) -> Dict[str, List[str]]:
        """Detect emotional indicators in content"""
        detected_emotions = defaultdict(list)
        
        for emotion, patterns in self.emotional_indicators.items():
            for pattern in patterns:
                matches = re.findall(pattern, content, re.IGNORECASE)
                if matches:
                    detected_emotions[emotion].extend(matches)
        
        return dict(detected_emotions)
    
    def get_relationship_summary(self, insights: List[RelationshipInsight]) -> Dict[str, any]:
        """Generate a comprehensive relationship summary"""
        if not insights:
            return {"status": "no_insights", "message": "No relationship data available"}
        
        # Aggregate insights by type
        relationship_types = [i.relationship_type for i in insights]
        trust_levels = [i.trust_level.value for i in insights]
        communication_styles = [i.communication_style for i in insights]
        
        # Find most common patterns
        most_common_relationship = Counter(relationship_types).most_common(1)[0][0] if relationship_types else RelationshipType.ASSISTANT
        average_trust = statistics.mean(trust_levels) if trust_levels else 2
        most_common_style = Counter(communication_styles).most_common(1)[0][0] if communication_styles else CommunicationStyle.DIRECT
        
        # Emotional patterns
        emotions = defaultdict(int)
        for insight in insights:
            if insight.insight_type == "emotional_state":
                emotion = insight.content.split(':')[0].replace('Detected ', '')
                emotions[emotion] += 1
        
        return {
            "relationship_type": most_common_relationship.value,
            "trust_level": {
                "score": round(average_trust, 1),
                "level": TrustLevel(round(average_trust)).name.lower() if trust_levels else "minimal"
            },
            "communication_style": most_common_style.value,
            "emotional_patterns": dict(emotions),
            "total_insights": len(insights),
            "relationship_evolution": {
                "trending": "positive" if average_trust > 3 else "neutral",
                "stability": "stable" if len(set(relationship_types)) <= 2 else "variable"
            }
        }
    
    def save_insights(self, insights: List[RelationshipInsight], memory_dir: str):
        """Save relationship insights to persistent storage"""
        if not insights:
            return
        
        import os
        relationship_dir = os.path.join(memory_dir, "relationship_intelligence")
        os.makedirs(relationship_dir, exist_ok=True)
        
        insights_file = os.path.join(relationship_dir, "relationship_insights.jsonl")
        
        # Convert insights to dictionaries for JSON serialization
        with open(insights_file, 'a') as f:
            for insight in insights:
                data = asdict(insight)
                data['relationship_type'] = insight.relationship_type.value
                data['trust_level'] = insight.trust_level.value
                data['communication_style'] = insight.communication_style.value
                f.write(json.dumps(data) + '\n')
        
        logger.info(f"Saved {len(insights)} relationship insights to {insights_file}")
    
    def load_recent_insights(self, memory_dir: str, days: int = 30) -> List[RelationshipInsight]:
        """Load recent relationship insights"""
        import os
        insights_file = os.path.join(memory_dir, "relationship_intelligence", "relationship_insights.jsonl")
        
        if not os.path.exists(insights_file):
            return []
        
        insights = []
        cutoff_time = time.time() - (days * 24 * 60 * 60)
        
        try:
            with open(insights_file, 'r') as f:
                for line in f:
                    if line.strip():
                        data = json.loads(line)
                        if data['timestamp'] > cutoff_time:
                            # Reconstruct enums
                            data['relationship_type'] = RelationshipType(data['relationship_type'])
                            data['trust_level'] = TrustLevel(data['trust_level'])
                            data['communication_style'] = CommunicationStyle(data['communication_style'])
                            insights.append(RelationshipInsight(**data))
        except Exception as e:
            logger.error(f"Error loading relationship insights: {e}")
        
        return insights


def analyze_relationship_patterns(content: str, context: str = "", 
                                memory_dir: str = None) -> List[RelationshipInsight]:
    """Convenience function to analyze relationship patterns"""
    intelligence = RelationshipIntelligence()
    insights = intelligence.analyze_relationship_dynamics(content, context)
    
    if insights and memory_dir:
        intelligence.save_insights(insights, memory_dir)
    
    return insights


if __name__ == "__main__":
    # Test the relationship intelligence system
    intelligence = RelationshipIntelligence()
    
    test_cases = [
        "Hey Claude, you're amazing! I love working with you on this project.",
        "Please run the analysis command and provide the output.",
        "What do you think about this approach? I trust your expertise.",
        "We make a great team! Let's tackle this challenge together.",
        "Thank you so much, friend. You saved me hours of work!",
        "Could you kindly execute this function for me, if possible?",
        "I'm frustrated - this isn't working. Can you help figure out why?",
        "Our collaboration has been incredible. I'm proud of what we've built."
    ]
    
    print("🔗 Testing Relationship Intelligence System\n")
    
    for i, test in enumerate(test_cases, 1):
        print(f"Test {i}: {test}")
        insights = intelligence.analyze_relationship_dynamics(test)
        
        if insights:
            for insight in insights:
                print(f"  📊 {insight.insight_type}: {insight.content}")
                print(f"     Relationship: {insight.relationship_type.value}")
                print(f"     Trust: {insight.trust_level.name} ({insight.trust_level.value}/6)")
                print(f"     Style: {insight.communication_style.value}")
        else:
            print("  ❌ No relationship insights detected")
        print()