"""
Discord Bridge Plugin for Cheshire Cat

This plugin enriches Cat's memory system with Discord context:
- Unified user identity across all servers and DMs
- Guild/channel metadata for context tracking
- Minimal filtering before storage (only skip obvious junk)
- Marks memories as unconsolidated for nightly processing

Phase 1 Implementation
"""

from cat.mad_hatter.decorators import hook
from datetime import datetime
import re


@hook(priority=100)
def before_cat_reads_message(user_message_json: dict, cat) -> dict:
    """
    Enrich incoming message with Discord metadata.
    This runs BEFORE the message is processed.
    
    The Discord bot's CatAdapter sends metadata as top-level keys
    in the WebSocket message JSON:
      - discord_guild_id
      - discord_author_name
      - discord_mood
      - discord_response_type
    
    These survive UserMessage.model_validate() as extra attributes
    (BaseModelDict has extra="allow"). We read them via .get() and
    store them in working_memory for downstream hooks.
    """
    # Extract Discord context from the message payload
    # (sent by CatAdapter.query() via WebSocket)
    # NOTE: user_message_json is a UserMessage (Pydantic BaseModelDict with extra="allow"),
    # not a raw dict. Extra keys survive model_validate() as extra attributes.
    # We use .get() since BaseModelDict implements it, but NOT .pop().
    guild_id = user_message_json.get('discord_guild_id', None)
    author_name = user_message_json.get('discord_author_name', None)
    mood = user_message_json.get('discord_mood', None)
    response_type = user_message_json.get('discord_response_type', None)

    # Also check working memory for backward compatibility
    if not guild_id:
        guild_id = cat.working_memory.get('guild_id')
    
    # Store in working memory so other hooks can access it
    cat.working_memory['guild_id'] = guild_id or 'dm'
    cat.working_memory['author_name'] = author_name
    cat.working_memory['mood'] = mood
    cat.working_memory['response_type'] = response_type
    
    return user_message_json


@hook(priority=100)
def before_cat_stores_episodic_memory(doc, cat):
    """
    Filter and enrich memories before storage.
    
    Phase 1: Minimal filtering
    - Skip only obvious junk (1-2 char messages, pure reactions)
    - Store everything else temporarily
    - Mark as unconsolidated for nightly processing
    """
    message = doc.page_content.strip()
    
    # Skip only the most trivial messages
    skip_patterns = [
        r'^\w{1,2}$',  # 1-2 character messages: "k", "ok"
        r'^(lol|lmao|haha|hehe|xd|rofl)$',  # Pure reactions
        r'^:[\w_]+:$',  # Discord emoji only: ":smile:"
    ]
    
    for pattern in skip_patterns:
        if re.match(pattern, message.lower()):
            print(f"🗑️  [Discord Bridge] Skipping trivial message: {message}")
            return None  # Don't store at all
    
    # Add Discord metadata to memory
    doc.metadata['consolidated'] = False  # Needs nightly processing
    doc.metadata['stored_at'] = datetime.now().isoformat()
    
    # Get Discord context from working memory (set by before_cat_reads_message)
    guild_id = cat.working_memory.get('guild_id', 'dm')
    author_name = cat.working_memory.get('author_name')
    
    doc.metadata['guild_id'] = guild_id
    doc.metadata['source'] = cat.user_id  # CRITICAL: Cat filters episodic by source=user_id!
    doc.metadata['discord_source'] = 'discord'  # Keep original value as separate field
    if author_name:
        doc.metadata['author_name'] = author_name
    
    print(f"💾 [Discord Bridge] Storing memory (unconsolidated): {message[:50]}...")
    print(f"   User: {cat.user_id}, Guild: {guild_id}, Author: {author_name}")
    
    return doc


@hook(priority=50)
def after_cat_recalls_memories(cat):
    """
    Log memory recall for debugging.
    Access recalled memories via cat.working_memory.
    """    
    # Get recalled memories from working memory
    episodic_memories = cat.working_memory.get('episodic_memories', [])
    declarative_memories = cat.working_memory.get('declarative_memories', [])
    
    if episodic_memories:
        print(f"🧠 [Discord Bridge] Recalled {len(episodic_memories)} episodic memories for user {cat.user_id}")
        guilds = set()
        for doc, score, *rest in episodic_memories:
            guild = doc.metadata.get('guild_id', 'unknown')
            guilds.add(guild)
        print(f"   From guilds: {', '.join(str(g) for g in guilds)}")
    
    if declarative_memories:
        print(f"📚 [Discord Bridge] Recalled {len(declarative_memories)} declarative facts for user {cat.user_id}")


# Plugin metadata
__version__ = "1.0.0"
__description__ = "Discord bridge with unified user identity and sleep consolidation support"
