#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Prompt Echo Detection — prevents SCRIBE_PROMPT examples leaking as real knowledge.

Split from retroactive_llm_extractor.py for Law 7 compliance.
"""
import re


def build_echo_filter(prompt_text: str):
    """Build echo detection functions from a prompt's YES:/NO: examples.

    Returns (is_prompt_echo, filter_prompt_echoes) callables.
    """
    # Dynamically extract YES:/NO: example texts from prompt
    fragments = set()
    for m in re.finditer(r'(?:YES|NO):\s*"([^"]+)"', prompt_text):
        fragments.add(m.group(1).strip().lower())

    # Structural markers that only appear in prompt context
    echo_markers = re.compile(
        r"\((?:failure,?\s*not\s*lesson|lesson,?\s*not\s*failure|status\s*update)\)",
        re.IGNORECASE,
    )

    def is_prompt_echo(text: str) -> bool:
        """Return True if text is an echo of prompt example text."""
        if not text or len(text) < 10:
            return False
        low = text.strip().lower()
        if echo_markers.search(text):
            return True
        for frag in fragments:
            if frag in low or low in frag:
                return True
            frag_words = set(frag.split())
            text_words = set(low.split())
            if frag_words:
                overlap = len(frag_words & text_words) / len(frag_words)
                if overlap >= 0.6:
                    return True
        return False

    def filter_prompt_echoes(items: dict) -> dict:
        """Remove items that are echoes of prompt examples."""
        filtered = {}
        for category in ("lessons", "failures", "patterns", "facts"):
            filtered[category] = [
                item for item in items.get(category, [])
                if isinstance(item, str) and not is_prompt_echo(item)
            ]
        return filtered

    return is_prompt_echo, filter_prompt_echoes
