"""
Profile Picture Context Plugin for Cheshire Cat

This plugin:
1. Detects questions about Miku's profile picture using regex patterns
2. Loads the current_description.txt file when needed
3. Injects it into the prompt only for relevant questions (no context bloat)
"""

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


# Regex patterns that match profile picture questions
PFP_PATTERNS = [
    r'\b(what|describe|tell me about|explain)\b.*\b(pfp|profile pic|avatar|picture)\b',
    r'\b(your|miku\'?s?)\b.*\b(pfp|profile pic|avatar|picture)\b',
    r'\bwhat.*looking like\b',
    r'\byour (new )?look\b',
    r'\bhow.*look(ing)?\b.*today',
    r'\b(pfp|profile pic|avatar)\b.*\b(is|look|show)',
]

def matches_pfp_query(text: str) -> bool:
    """Check if the message is asking about the profile picture"""
    text_lower = text.lower()
    for pattern in PFP_PATTERNS:
        if re.search(pattern, text_lower, re.IGNORECASE):
            return True
    return False


@hook(priority=50)
def before_agent_starts(agent_input, cat) -> dict:
    """
    Inject profile picture description only when relevant.
    This runs after memory recall but before LLM generation.
    """
    user_message = agent_input.get('input', '')
    
    # Check if question is about profile picture
    if not matches_pfp_query(user_message):
        return agent_input
    
    # Load profile picture description
    try:
        with open('/app/memory/profile_pictures/current_description.txt', 'r', encoding='utf-8') as f:
            pfp_description = f.read().strip()
        
        log.warning(f"[Profile Picture Context] PFP query detected, injecting description")
        
        # Inject into declarative memory section
        current_declarative = agent_input.get('declarative_memory', '')
        
        pfp_context = f"\n\n## Your Current Profile Picture\n{pfp_description}\n"
        
        agent_input['declarative_memory'] = current_declarative + pfp_context
        
    except FileNotFoundError:
        log.error(f"[Profile Picture Context] current_description.txt not found")
    except Exception as e:
        log.error(f"[Profile Picture Context] Error loading PFP description: {e}")
    
    return agent_input


# Plugin metadata
__version__ = "1.0.0"
__description__ = "Injects profile picture description only when asked about it"
