#!/usr/bin/env python3
"""
Reflex Demotion — demote contradicted knowledge when errors are detected.

When the reflex arc detects "the bug was X", this module finds existing
lessons that match X and reduces their confidence. This closes the
error-to-learning loop: the mistake is recorded AND the wrong knowledge
that led to it gets weakened.

Expert 3 (Consolidation) P0-2 recommendation.
"""
import logging

log = logging.getLogger("pulse.reflex_demotion")


def demote_contradicted_knowledge(error_description: str) -> int:
    """Find and demote lessons that match the detected error.

    Returns count of demoted items.
    """
    if not error_description or len(error_description) < 20:
        return 0
    try:
        from pulse.core.brain_db import get_conn
        conn = get_conn()
        search_term = error_description[:100].lower()
        search_term = search_term[:50].replace('"', '').replace("'", "")
        if len(search_term) < 10:
            return 0
        rows = conn.execute(
            "SELECT item_id, table_name FROM knowledge_fts "
            "WHERE content MATCH ? AND table_name = 'lessons' LIMIT 5",
            (search_term,)
        ).fetchall()
        demoted = 0
        for r in rows:
            conn.execute(
                "UPDATE lessons SET confidence = MAX(0.15, confidence * 0.6) "
                "WHERE id = ?", (r[0],))
            demoted += 1
        if demoted:
            conn.commit()
            log.info("Demoted %d contradicted lessons for: %s", demoted, search_term[:60])
        return demoted
    except Exception as e:
        log.debug("Demotion failed: %s", e)
        return 0
