#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Quality gate: signal detection for brain write filtering."""
import re

# Negative patterns: reject known garbage content regardless of tier
_GARBAGE_PATTERNS = re.compile(
    r'(?:'
    r'"lessons"\s*:\s*\[|"failures"\s*:\s*\[|"patterns"\s*:\s*\['
    r'|```|~~~'
    r'|\|---\||^\s*\|.*\|.*\|'
    r'|<task-notification>|</task-notification>'
    r'|^agent:'
    r'|"type"\s*:\s*"LEARNING"|"type"\s*:\s*"FAILURE"'
    r')',
    re.IGNORECASE | re.MULTILINE
)

# Tier 1 (strict): reject fragments without actionable content
_QUALITY_SIGNALS = re.compile(
    r"(?:use|replace|fix|add|remove|change|switch|avoid|always|never|"
    r"install|update|check|run|set|create|delete|move|rename|enable|disable|"
    r"should|must|need|works|fails|breaks|causes|prevents|requires|reduces|improves|"
    r"discovered|learned|realized|confirmed|verified|tested|proved|migrated|refactored|"
    r"shipped|released|deployed|merged|"
    r"version|v[0-9]|PR|commit|"
    r"phase|stage|wave|audit|panel|"
    r"error|exception|crash|timeout|race condition|"
    r"broke|lost|missing|corrupt|regress|overflow|deadlock|leak)",
    re.IGNORECASE
)

# Tier 2 (looser): accept descriptive/structural knowledge for high-value items
_QUALITY_SIGNALS_TIER2 = re.compile(
    r"(?:path|file|module|class|function|method|attribute|"
    r"pattern|type|format|state|result|value|key|config|"
    r"returns|stores|loads|reads|writes|sends|receives|"
    r"defined|located|named|called|known|used|found|"
    r"version|v[0-9]|PR|commit|"
    r"use|replace|fix|add|remove|change|switch|avoid|always|never|"
    r"install|update|check|run|set|create|delete|move|rename|enable|disable|"
    r"should|must|need|works|fails|breaks|causes|prevents|requires|reduces|improves|"
    r"discovered|learned|realized|confirmed|verified|tested|proved|migrated|refactored|"
    r"shipped|released|deployed|merged|"
    r"phase|stage|wave|audit|panel|"
    r"error|exception|crash|timeout|race condition|"
    r"broke|lost|missing|corrupt|regress|overflow|deadlock|leak)",
    re.IGNORECASE
)


def _passes_quality_gate(text: str, salience: float = 0.0, confidence: float = 0.0) -> bool:
    """Check if text passes all quality gates.

    Three tiers based on salience/confidence:
    - Critical (salience >= 7.0 AND confidence >= 0.7): skip keyword gate entirely.
    - High-value (salience >= 4.0 OR confidence >= 0.85): Tier 2 keywords, 15 chars / 3 words.
    - Standard: Tier 1 strict keywords, 25 chars / 4 words.
    Per-item salience scale: 1.0=ambient, 2.0=standard, 4.0=actionable, 7.0=critical.
    """
    if text.rstrip().endswith("..") or text.rstrip().endswith("—"):
        return False

    # Reject garbage patterns (markdown tables, task XML, JSON fragments)
    if _GARBAGE_PATTERNS.search(text):
        return False

    words = text.split()

    # Critical items: always pass (no keyword gate)
    if salience >= 7.0 and confidence >= 0.7:
        return len(text) >= 10 and len(words) >= 2

    # High-value: Tier 2 looser keywords, relaxed length
    if salience >= 4.0 or confidence >= 0.85:
        if len(text) < 15 or len(words) < 3:
            return False
        return bool(_QUALITY_SIGNALS_TIER2.search(text))

    # Standard: Tier 1 strict keywords, full length requirements
    if len(text) < 25 or len(words) < 4:
        return False
    return bool(_QUALITY_SIGNALS.search(text))
