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

# Regex: 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"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.

    Density Bypass: concise but high-value items (salience >= 4.0 or
    confidence >= 0.85) pass with lower thresholds (25 chars / 5 words).
    Per-item salience scale: 1.0=ambient, 2.0=standard, 4.0=actionable, 7.0=critical.
    """
    words = text.split()
    if salience >= 4.0 or confidence >= 0.85:
        # Diamond signals — concise but high-value (must have signal words)
        if len(text) < 15 or len(words) < 3:
            return False
    else:
        if len(text) < 40 or len(words) < 7:
            return False
    if not _QUALITY_SIGNALS.search(text):
        return False
    if text.rstrip().endswith("..") or text.rstrip().endswith("\u2014"):
        return False
    return True
