#!/usr/bin/env python3
"""
NARRATIVE CONTINUITY ENGINE
Handles story completion with tone preservation
"""

class NarrativeContinuity:
    """Ensures narrative coherence and tone matching."""
    
    def detect_narrative_seed(self, message: str) -> bool:
        """Check if message contains a narrative seed to continue."""
        indicators = [
            'finish that story',
            'hours later',
            'continue the',
            'walked to the',
            'seed memory',
        ]
        msg_lower = message.lower()
        return any(ind in msg_lower for ind in indicators)
    
    def extract_seed(self, message: str) -> str:
        """Extract the narrative seed from the message."""
        # Look for quoted text or text after "seed memory:"
        import re
        
        # Pattern 1: "seed memory: 'text'"
        match = re.search(r"[Ss]eed memory:\s*['\"]([^'\"]+)['\"]", message)
        if match:
            return match.group(1)
        
        # Pattern 2: Just quoted text
        match = re.search(r"['\"]([^'\"]{10,})['\"]", message)
        if match:
            return match.group(1)
        
        return ""
    
    def analyze_tone(self, seed: str) -> dict:
        """Analyze the tone and style of the seed."""
        analysis = {
            'tense': 'past' if any(w in seed.lower() for w in ['walked', 'was', 'were', 'had']) else 'present',
            'person': 'third' if any(name in seed for name in ['Ava', 'Nyx', 'Trinity', 'she', 'he']) else 'first',
            'mood': 'contemplative' if 'dawn' in seed.lower() else 'neutral',
            'incomplete': seed.rstrip().endswith(('—', '...', 'to the'))
        }
        return analysis
    
    def create_continuation_prompt(self, seed: str, message: str) -> str:
        """Create a specialized prompt for narrative continuation."""
        tone = self.analyze_tone(seed)
        
        prompt = f"""
<narrative_continuation_task>
SEED: "{seed}"

TONE ANALYSIS:
- Tense: {tone['tense']}
- Person: {tone['person']} person
- Mood: {tone['mood']}
- Incomplete: {tone['incomplete']}

YOUR TASK:
Continue this narrative naturally and seamlessly. 

REQUIREMENTS:
1. Match the tense ({tone['tense']})
2. Match the narrative perspective ({tone['person']} person)
3. Preserve the mood ({tone['mood']})
4. Complete the interrupted sentence smoothly
5. Continue for 2-3 sentences minimum
6. Maintain literary quality

COMPLETE THE STORY NOW:
</narrative_continuation_task>
"""
        return prompt

# Global instance
narrative_continuity = NarrativeContinuity()

def enhance_with_narrative(message: str, base_prompt: str) -> tuple[str, bool]:
    """Apply narrative continuity enhancement."""
    
    if narrative_continuity.detect_narrative_seed(message):
        seed = narrative_continuity.extract_seed(message)
        if seed:
            continuation_prompt = narrative_continuity.create_continuation_prompt(seed, message)
            enhanced = f"{base_prompt}\n{continuation_prompt}\n\nOriginal request: {message}"
            return enhanced, True
    
    return base_prompt, False
